Add some model form validation for Diaper Change and Feeding.

This commit is contained in:
Christopher Charbonneau Wells 2017-10-31 15:26:37 -04:00
parent 9c0989d22b
commit c565bfc59a
1 changed files with 42 additions and 0 deletions

View File

@ -64,6 +64,31 @@ class DiaperChangeForm(forms.ModelForm):
kwargs = set_default_child(kwargs)
super(DiaperChangeForm, self).__init__(*args, **kwargs)
def clean(self):
"""Additional form validation/cleaning.
"""
errors = {}
# One or both of Wet and Solid is required.
if not self.cleaned_data['wet'] and not self.cleaned_data['solid']:
errors['wet'] = forms.ValidationError(
'Wet and/or solid is required.',
code='missing-wet-or-solid')
errors['solid'] = forms.ValidationError(
'Wet and/or solid is required.',
code='missing-wet-or-solid')
# Color is required when Solid is selected.
if self.cleaned_data['solid'] and not self.cleaned_data['color']:
errors['color'] = forms.ValidationError(
'Color is required for solid changes.',
code='missing-color')
if len(errors) > 0:
raise forms.ValidationError(errors)
return self.cleaned_data
class FeedingForm(forms.ModelForm):
class Meta:
@ -86,6 +111,23 @@ class FeedingForm(forms.ModelForm):
kwargs = set_default_duration(kwargs)
super(FeedingForm, self).__init__(*args, **kwargs)
def clean(self):
"""Additional form validation/cleaning.
"""
errors = {}
# "Formula" Type may only be associated with "Bottle" Method.
if (self.cleaned_data['type'] == 'formula'
and self.cleaned_data['method'] != 'bottle'):
errors['method'] = forms.ValidationError(
'Only "Bottle" method is allowed with type "Formula".',
code='bottle-formula-mismatch')
if len(errors) > 0:
raise forms.ValidationError(errors)
return self.cleaned_data
def save(self, commit=True):
instance = super(FeedingForm, self).save(commit=False)
if self.timer_id: