我有一个注册视图,其中包含电子邮件、密码、确认密码和额外的字符串,这些字符串必须是唯一的。我所有的验证错误都正确返回(例如,如果电子邮件重复,它显示这必须是唯一的,如果密码不匹配则显示密码不匹配)。但是,额外的字符串会显示带有验证错误的 Django 调试页面,而不是将其显示到表单中。为什么会这样?
Django调试页面报错:
ValidationError at /signup/
['Extra string must be unique.']
模板摘录:
{% for field in form %}
<div class="form-group">
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
<label for="{{ field.id_for_label }}">{{ field.label }}:</label>
{{ field }}
</div>
{% endfor %}
形式:
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': 'form-control'}))
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput(attrs={'class': 'form-control'}))
email = forms.CharField(label='Email', widget=forms.EmailInput(attrs={'class': 'form-control'}))
extra_string = forms.CharField(label='Extra String (Must be unique)', widget=forms.TextInput(attrs={'class': 'form-control'}))
class Meta:
model = User
fields = ('email',)
def clean_password2(self):
"""A function to check that the two passwords provided by the user match."""
# Check that the two password entries match
#: User's password.
password1 = self.cleaned_data.get("password1")
#: Password confirm.
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("The passwords must match.") #: This displays properly
return password2
def ensure_unique_string(self):
"""Checks that the entered extra string is unique"""
慕神8447489
相关分类