我有一個注冊視圖,其中包含電子郵件、密碼、確認密碼和額外的字符串,這些字符串必須是唯一的。我所有的驗證錯誤都正確返回(例如,如果電子郵件重復,它顯示這必須是唯一的,如果密碼不匹配則顯示密碼不匹配)。但是,額外的字符串會顯示帶有驗證錯誤的 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
提交
取消