我有一个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")
现在这个错误没有显示在表单中。当调试为真时,它会显示在我的浏览器上。 我不想使用模型形式。
需要有关如何在表单中打印此错误的建议
最佳答案
您需要将所有验证逻辑存储在 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/
关于python - django打印模板中的表单错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31283741/