Django self.cleaned_data Keyerror

折月煮酒 提交于 2019-12-18 17:32:25

问题


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?


回答1:


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.




回答2:


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



回答3:


Replace

end_date = self.cleaned_data['end_date']

with

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

OR

Clean end_date field before start_date .



来源:https://stackoverflow.com/questions/21497497/django-self-cleaned-data-keyerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!