I need to override the clean()
method of my Django form to test two datefields together: a begin_date and a end_date (is the end date posterior to start date, and is the begin date posterior to now).
The problem is that when one of these two fields is empty or invalid, I got an exception (KeyError). I'd like to got a simple error form like I got with empty charfields.
I was pretty sure to find the answer here: Django self.cleaned_data Keyerror but I didn't.
Here is the code:
class MyForm(forms.Form):
begin_date = forms.DateField()
end_date = forms.DateField()
#...
def clean(self):
cleaned_data = super(MyForm, self).clean()
errors = []
begin_date = cleaned_data['begin_date']
end_date = cleaned_data['end_date']
#...
# Test 1
if begin_date < date.today():
errors.append(forms.ValidationError(
"La date de début doit être postérieure à la date actuelle"))
# Test 2
if end_date < begin_date:
errors.append(forms.ValidationError(
"La date de fin doit être posétieure à la date de début"))
if errors:
raise forms.ValidationError(errors)
return cleaned_data