From c565bfc59ac62ddd3a98f47959029605277d6727 Mon Sep 17 00:00:00 2001 From: Christopher Charbonneau Wells Date: Tue, 31 Oct 2017 15:26:37 -0400 Subject: [PATCH] Add some model form validation for Diaper Change and Feeding. --- core/forms.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/core/forms.py b/core/forms.py index ae488075..a236d79c 100644 --- a/core/forms.py +++ b/core/forms.py @@ -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: