I'm writing a Django website and i'm writing my own validation for a form :
class CreateJobOpportunityForm(forms.Form):
subject = forms.CharField(max_length=30)
start_date = forms.DateField(widget=SelectDateWidget)
end_date = forms.DateField(widget=SelectDateWidget)
def clean_start_date(self):
start_date = self.cleaned_data['start_date']
end_date = self.cleaned_data['end_date']
if start_date > end_date :
raise forms.ValidationError("Start date should be before end date.")
return start_date
but when the start_date is less than end_date it says :
KeyError at /create_job_opportunity
'end_date'
why doesn't it recognize the 'end_date'
key?
Since one field depends on another field, it's best if you did your cleaning in the clean
method for the form, instead of the individual clean_field
method.
def clean(self):
cleaned_data = super(CreateJobOpportunityForm, self).clean()
end_date = cleaned_data['end_date']
start_date = cleaned_data['start_date']
# do your cleaning here
return cleaned_data
Else you would have to ensure that your end_date
field gets cleaned before start_date
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With