Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django self.cleaned_data Keyerror

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?

like image 998
Navid777 Avatar asked Dec 03 '22 20:12

Navid777


1 Answers

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.

like image 67
elssar Avatar answered Dec 05 '22 11:12

elssar