我有一个注册视图,其中包含电子邮件、密码、确认密码和额外的字符串,这些字符串必须是唯一的。我所有的验证错误都正确返回(例如,如果电子邮件重复,它显示这必须是唯一的,如果密码不匹配则显示密码不匹配)。但是,额外的字符串会显示带有验证错误的 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"""
1 回答
慕神8447489
TA贡献1780条经验 获得超1个赞
因为你在保存方法中提出,当你在保存时,告诉你所有的字段都是有效的,所以你需要在调用保存方法之前验证你的字段。
你有 2 个解决方案:
在 clean_FIELD_NAME 中:
def clean_extra_string(self, data):
if len(ExtraString.objects.filter(name=data)) > 0:
raise forms.ValidationError("Ana Group Name must be unique.")
return data
在验证方法中:
def validate(self, validate_data):
if len(ExtraString.objects.filter(name=validate_data['extra'])) > 0:
raise forms.ValidationError("Ana Group Name must be unique.")
return validate_data
添加回答
举报
0/150
提交
取消