gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:31:47 25 4
gpt4 key购买 nike

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

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

现在,当从您的 View 中调用 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"]

关于Django 将自定义表单错误添加到 form.errors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33237866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com