Navid777
Navid777

Reputation: 3681

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?

Upvotes: 4

Views: 10428

Answers (3)

Priyank Patel
Priyank Patel

Reputation: 3535

Replace

end_date = self.cleaned_data['end_date']

with

end_date = self.data.get('end_date')

OR

Clean end_date field before start_date .

Upvotes: 4

Yogesh dwivedi Geitpl
Yogesh dwivedi Geitpl

Reputation: 4462

This happen because you trying to get clean_data of end_date before checking end_date is valid or not. if you declare end_date before the start_date in this case end_date is validated, after that clean_start_date is called. Declare end_date before the start_date like this :

class CreateJobOpportunityForm(forms.Form):
    subject = forms.CharField(max_length=30)
    end_date = forms.DateField(widget=SelectDateWidget)
    start_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

Upvotes: 4

elssar
elssar

Reputation: 5861

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.

Upvotes: 9

Related Questions