繁体   English   中英

Django中的打印表单错误

[英]django print form errors in template

我有一个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")

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

需要建议如何在表格中打印此错误

您需要将所有验证逻辑存储在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()引发的任何错误都不会与任何特定字段相关联。 可能需要添加{{form.non_field_errors}}才能在模板中列出此类错误

了解更多: https//docs.djangoproject.com/en/1.8/ref/forms/validation/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM