django打印模板中的错误

时间:2015-07-08 04:51:38

标签: python django forms validation

我有forms.Form

class RegistrationForm(forms.Form):
    username = forms.CharField(max_length=20)
    password1 = forms.CharField(max_length=20)
    password2 = forms.CharField(max_length=20)
    email = forms.EmailField(max_length=50)

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(" The two password didn't match")

        return password2

在我看来,我正在检查重复的用户名或电子邮件。

if User.objects.filter(Q(username=username) | Q(email=user_email)).exists():
    raise ValidationError("Username or email exist")

现在此错误未在表单中显示。当调试为真时,它在我的浏览器上显示。 我不想使用模型表格。

需要建议如何以表格

打印此错误

1 个答案:

答案 0 :(得分:1)

您需要在Form类中存储所有验证逻辑。这正是django中Forms层的目的。

您可以覆盖clean方法以访问用户名和密码字段数据:

def clean(self):
   cleaned_data = super(RegistrationForm, self).clean()
   username = cleaned_data['username']
   user_email = cleaned_data['email']
   if User.objects.filter(Q(username=username) | Q(email=user_email)).exists():
        raise ValidationError("Username or email exist")

Form.clean()引发的任何错误都不会与任何字段相关联。可能需要添加{{forms.non_field_errors}}来列出模板中的错误

了解详情:https://docs.djangoproject.com/en/1.8/ref/forms/validation/