【问题标题】:Validate form with raise errors with django使用 django 验证带有引发错误的表单
【发布时间】:2015-07-06 05:04:49
【问题描述】:

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

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 字段上方有这一行:{{form.proposal.errors.as_text}}

我放在这里的验证“311”只是一个例子,但是有了这个,我无法让它工作,我在proposal字段中写了“311”并且错误没有显示,我该如何实现这个?

【问题讨论】:

    标签: python django validation django-forms


    【解决方案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
    

    【讨论】:

    猜你喜欢
    • 2016-09-16
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2016-03-20
    相关资源
    最近更新 更多