使用django验证带有引发错误的表单

时间:2015-07-06 05:04:49

标签: python django validation django-forms

我正在尝试验证表单,用户无法通过表单发送联系信息,为此,我有:

null

在模板中,我在字段class ActualizarCotizacionForm(ModelForm): def __init__(self, *args, **kwargs): super(ActualizarCotizacionForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control' self.fields['proposal'].widget.attrs['rows'] = '4' self.fields['deliverable'].widget.attrs['rows'] = '4' class Meta(): model = AffiliateQuote fields = ['proposal','deliverable','delivery_time','fee'] def clean(self): data = self.cleaned_data['proposal'] if "311" in data: raise forms.ValidationError("You cant send phone numbers through the form") return data 上方有这一行:proposal

验证“311”,我放在这里仅仅是例如,但有了这个,我不能把它工作,我在{{form.proposal.errors.as_text}}字段写“311”并且错误没有显示,我怎么能实现这个目标?

1 个答案:

答案 0 :(得分:1)

请将此验证放在clean_proposal方法中,例如:

def clean_proposal(self):
        data = self.cleaned_data['proposal']
        if "311" in data:
            raise forms.ValidationError("You cant send phone numbers through the form")
        return data