gpt4 book ai didi

django - 如何在发生这种情况的字段附近的模板中打印 ValidationError?

转载 作者:行者123 更新时间:2023-12-01 12:41:47 26 4
gpt4 key购买 nike

我正在覆盖方法 clean_:

def clean_password(self):
value_password = self.cleaned_data.get('password')
if len(str(self.cleaned_data['password'])) < 6:
raise forms.ValidationError("Password must been more then 6 symbols")
elif len(str(self.cleaned_data['password'])) > 45:
raise forms.ValidationError("Password must been less 45 symbols")
elif value_password is None:
raise forms.ValidationError("Field of password can't are blank")
return value_password

def clean_password2(self):
value_password2 = self.cleaned_data.get('password2')
if len(str(self.cleaned_data['password2'])) < 6:
raise forms.ValidationError(self.error_messages['password_mismatch'],
code='password_mismathc')
elif len(str(self.cleaned_data['password2'])) > 45:
raise forms.ValidationError("Password must been less 45 symbols")
return value_password2

def clean(self):
super(Form_registration, self).clean()
data = self.cleaned_data
if data["password"] != data["password2"]:
raise forms.ValidationError("Password must been are equal")
return data

如果我写这个 {{ form.errors }} 然后在首页打印错误,但我希望错误打印在表单密码附近。

我应该做什么?

最佳答案

更改您的 clean方法通过将字段名称传递给它来引发验证错误。

def clean(self):
super(Form_registration, self).clean()
data = self.cleaned_data
if data["password"] != data["password2"]:
raise forms.ValidationError({'password': ["Passwords must be the same."]})
return data

编辑:

您的模板应如下所示:
<form action="" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.password.errors }}
<label for="{{ form.password.id_for_label }}">Password:</label>
{{ form.password }}
</div>
<div class="fieldWrapper">
{{ form.password2.errors }}
<label for="{{ form.password2.id_for_label }}">Confirm Password:</label>
{{ form.password2 }}
</div>
</form>

关于django - 如何在发生这种情况的字段附近的模板中打印 ValidationError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23818234/

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