-
Ernesto Rico Schmidt authoredErnesto Rico Schmidt authored
updatenote.py 2.30 KiB
import sys
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from django.core.management.base import BaseCommand, CommandError
from program.models import Note, Show
from program.utils import parse_date
class Command(BaseCommand):
help = "updates title and content of a note for a timeslot by reading both from stdin."
def add_arguments(self, parser):
parser.add_argument("show_id", help="ID of the show", type=int)
parser.add_argument("date", help="date of the timeslot", type=str)
parser.add_argument(
"index",
default=None,
help="index of the timeslot within the date. (default: 0)",
nargs="?",
type=int,
)
def handle(self, *args, **options):
try:
show = Show.objects.get(pk=options["show_id"])
except ObjectDoesNotExist as e:
raise CommandError(e)
try:
date = parse_date(options["date"])
except ValueError as e:
raise CommandError(e)
else:
year, month, day = date.year, date.month, date.day
try:
note = Note.objects.get(
timeslot__schedule__show=show,
timeslot__start__day=day,
timeslot__start__month=month,
timeslot__start__year=year,
)
except ObjectDoesNotExist as e:
raise CommandError(e)
except MultipleObjectsReturned:
if not options["index"]:
raise CommandError(f"more than one note within {date}. Please provide an index.")
try:
note = Note.objects.filter(
timeslot__schedule__show=show,
timeslot__start__day=day,
timeslot__start__month=month,
timeslot__start__year=year,
).order_by("timeslot__start")[options["index"]]
except IndexError as e:
raise CommandError(e)
try:
title = sys.stdin.readline().strip()
content = sys.stdin.read()
except Exception as e:
raise CommandError(e)
note.title = title
note.content = content
note.save()
self.stdout.write(self.style.SUCCESS(f'updated note "{title}" for {note.timeslot}'))