Django self.cleaned_data Keyerror

时间:2014-02-01 11:32:24

标签: python django django-forms

我正在写一个Django网站,我正在为表单编写自己的验证:

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

但是当start_date小于end_date时,它会显示:

KeyError at /create_job_opportunity
'end_date'

为什么它不识别'end_date'密钥?

3 个答案:

答案 0 :(得分:9)

由于一个字段取决于另一个字段,因此最好使用表单的clean方法进行清理,而不是使用单个clean_field方法。

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

否则,您必须确保在end_date之前清除start_date字段。

答案 1 :(得分:3)

这是因为在检查end_date是否有效之前尝试获取end_date的clean_data。如果在start_date之前声明end_date,则在此情况下验证end_date,之后调用clean_start_date。 在start_date之前声明end_date,如下所示:

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

答案 2 :(得分:2)

替换

end_date = self.cleaned_data['end_date']

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

OR

end_date之前清除start_date字段。