Django 将自定义表单错误添加到 form.errors

Django add custom form errors to form.errors

我想写一个用户注册表格。我想实现一个 密码匹配 ,用户必须在其中输入两次密码。这是我当前的表格:

from django import forms
from passwords.fields import PasswordField

class AccountForm(forms.Form):
    email = forms.EmailField(max_length=255)
    username = forms.CharField(max_length=40)
    password = PasswordField(label="Password")
    password_confirm = PasswordField(label="Password")

在我看来,我想检查验证,如果某些内容无效,我想在我的模板中打印特定错误。这是我目前的观点:

def signup(request):
    if request.method == 'POST':
        form = AccountForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            password_confirm = form.cleaned_data['password_confirm']

            if password != password_confirm:
                print("Password don't match")

            #Account.objects.create_user(email, password, username = username)

        else:
            print(form.errors)
            form = Account()
    return render(request, 'authentication/auth.html', {'signup': form})

现在我的目标是将表单错误传递给模板。例如,我检查 passwordpassword_confirm 变量的匹配。如果它们不匹配,我希望它在模板中可见。你们知道我如何将我的自定义表单错误/验证添加到我的表单并在我的模板中显示这些错误吗?

为此,您需要使用clean方法。

class AccountForm(forms.Form):
    email = forms.EmailField(max_length=255)
    username = forms.CharField(max_length=40)
    password = PasswordField(label="Password")
    password_confirm = PasswordField(label="Password")

    def clean(self):
        cd = self.cleaned_data
        if cd.get('password') != cd.get('password_confirm'):
            self.add_error('password_confirm', "passwords do not match !")
        return cd

现在,当从您的视图调用 form.is_valid() 时,将隐式调用表单的 clean 方法并执行此验证。

阅读此内容:clean values that depend on each other 了解更多信息。

Note that any errors raised by your Form.clean() override will not be associated with any field in particular. They go into a special “field” (called all), which you can access via the non_field_errors() method if you need to. If you want to attach errors to a specific field in the form, you need to call add_error().

此外,请注意 .add_error 是在 django 1.7 中引入的。

如果您使用的是 django 1.6 或更低版本,您会这样做:

if cd.get('password') != cd.get('password_confirm'):
    self._errors["password_confirm"] = self.error_class(["Passwords do not match"])
    del cleaned_data["password_confirm"]
class AccountForm(forms.Form):
    ....your stuff

    def clean_password(self):
        if self.data['password'] != self.data['password_confirm']:
            raise forms.ValidationError('Passwords are not the same')
        return self.data['password']