Django表单-两次显示验证错误

时间:2019-06-21 12:14:06

标签: python django django-forms

我想以表格的形式显示一些验证错误:

  • 如果电子邮件已经存在
  • 如果用户名少于8个字符
  • 如果密码不匹配
  • 如果密码字段少于8个字符

forms.py

class RegisterForm(forms.Form):

    username = forms.CharField(widget = forms.TextInput(attrs ={"class":"form-control mb-2 mr-sm-2" ,"placeholder":"username"}))
    email = forms.EmailField(widget = forms.TextInput(attrs = {"class":"form-control mb-2 mr-sm-2"}))
    password = forms.CharField(widget = forms.PasswordInput(attrs = {"class":"form-control mb-2 mr-sm-2"}))
    password2 = forms.CharField(label = "Confirm Password",widget = forms.PasswordInput(attrs = {"class":"form-control mb-2 mr-sm-2"}))

    def clean(self):
        data = self.cleaned_data
        password = self.cleaned_data.get('password')
        password2 = self.cleaned_data.get('password2')
        if password2!=password:
            raise forms.ValidationError("Passwords dont match")
        if len(password)<8:
            raise forms.ValidationError("Password must be atleast 8 characters long")
        return data

    def clean_username(self):
        username = self.cleaned_data.get('username')
        qs = User.objects.filter(username = username)
        if qs.exists():
            raise forms.ValidationError("username exists")
        return username

    def clean_email(self):
        email = self.cleaned_data.get('email')
        qs = User.objects.filter(email = email)
        if qs.exists():
            raise forms.ValidationError("email exists",code="error1")
        return email'''

register.html

<form method="POST" class="was-validated">

    {% csrf_token %}
    <div class="form-group">
        {% if form.errors %}
        {% for field in form %}
        {% for error in field.errors %}
        <div class="alert alert-danger">
            <strong>{{ error|escape }}</strong>
        </div>
        {% endfor %}
        {% endfor %}
        {% for error in form.non_field_errors %}
        <div class="alert alert-danger">
            <strong>{{ error|escape }}</strong>
        </div>
    {% endfor %}
    {%endif%}

        {{form.as_p}}
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>'''

我希望验证错误仅显示一次。我不希望每个字段上方出现错误。我只希望所有错误都在顶部。

1 个答案:

答案 0 :(得分:0)

您可以使用self.add_error而不是引发表格。ValidationError:

class UserRegisterForm(forms.Form):
    # [...stuff...]
    password = forms.CharField(widget=forms.PasswordInput)
    password_confirm = forms.CharField(widget=forms.PasswordInput)

    def clean(self):
        '''Required custom validation for the form.'''
        super(forms.Form,self).clean()
        if 'password' in self.cleaned_data and 'password_confirm' in self.cleaned_data:
            if self.cleaned_data['password'] != self.cleaned_data['password_confirm']:
                self._errors['password'] = [u'Passwords must match.']
                self._errors['password_confirm'] = [u'Passwords must match.']
        return self.cleaned_data

您可以在模板中使用:

   {% for error in form.non_field_errors %}
        {{error}}
    {% endfor %}

您在表单上设置_errors ['FIELDNAME']以标记无效字段。 (请记住,clean方法必须返回cleaned_data成员。这让我在后面感到了一阵子。)

要了解更多信息,请参见this