Catch invalid object ID in form initial setup

Fixes #735
This commit is contained in:
Christopher C. Wells 2024-01-27 09:32:51 -08:00
parent 267780d113
commit e65b1749e0
2 changed files with 14 additions and 7 deletions

View File

@ -9,6 +9,7 @@ from taggit.forms import TagField
from babybuddy.widgets import DateInput, DateTimeInput, TimeInput from babybuddy.widgets import DateInput, DateTimeInput, TimeInput
from core import models from core import models
from core.models import Timer
from core.widgets import TagsEditor, ChildRadioSelect from core.widgets import TagsEditor, ChildRadioSelect
@ -43,10 +44,13 @@ def set_initial_values(kwargs, form_type):
# Set start and end time based on Timer from `timer` kwarg. # Set start and end time based on Timer from `timer` kwarg.
timer_id = kwargs.get("timer", None) timer_id = kwargs.get("timer", None)
if timer_id: if timer_id:
timer = models.Timer.objects.get(id=timer_id) try:
kwargs["initial"].update( timer = models.Timer.objects.get(id=timer_id)
{"timer": timer, "start": timer.start, "end": timezone.now()} kwargs["initial"].update(
) {"timer": timer, "start": timer.start, "end": timezone.now()}
)
except Timer.DoesNotExist:
pass
# Set type and method values for Feeding instance based on last feed. # Set type and method values for Feeding instance based on last feed.
if form_type == FeedingForm and "child" in kwargs["initial"]: if form_type == FeedingForm and "child" in kwargs["initial"]:

View File

@ -124,10 +124,13 @@ class InitialValuesTestCase(FormsTestCaseBase):
self.assertEqual(page.context["form"].initial["type"], f_three.type) self.assertEqual(page.context["form"].initial["type"], f_three.type)
self.assertEqual(page.context["form"].initial["method"], f_three.method) self.assertEqual(page.context["form"].initial["method"], f_three.method)
def test_timer_form_field_set(self): def test_start_end_set_from_timer(self):
self.timer.stop() page = self.c.get("/sleep/add/?timer={}".format(self.timer.id))
self.assertTrue("start" in page.context["form"].initial)
self.assertTrue("end" in page.context["form"].initial)
page = self.c.get("/sleep/add/") def test_start_end_not_set_from_invalid_timer(self):
page = self.c.get("/sleep/add/?timer={}".format(42))
self.assertTrue("start" not in page.context["form"].initial) self.assertTrue("start" not in page.context["form"].initial)
self.assertTrue("end" not in page.context["form"].initial) self.assertTrue("end" not in page.context["form"].initial)