简体   繁体   中英

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?

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 .

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

Replace

end_date = self.cleaned_data['end_date']

with

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

OR

Clean end_date field before start_date .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM