【发布时间】:2020-11-22 05:23:27
【问题描述】:
我有一个注册视图,其中包含电子邮件、密码、确认密码和额外的字符串,这些字符串必须是唯一的。我的所有验证错误都正确返回(例如,如果电子邮件重复,则显示这必须是唯一的,如果密码不匹配则显示密码不匹配)。但是,额外的字符串会显示带有验证错误的 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"""
extra= self.cleaned_data.get("extra_string")
if len(ExtraString.objects.filter(name=extra)) > 0:
raise forms.ValidationError("Ana Group Name must be unique.") #: This displays django debug page
return extra
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.clean_password2())
user.extra_string = self.ensure_unique_string()
user.has_migrated_pwd = True
if commit:
user.save()
return user
注册视图:
class SignUpView(View):
template_name = "account/signup.html"
def get(self, request):
form = UserCreationForm()
return render(request=request, template_name=self.template_name, context={
"form": form
})
def post(self, request):
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
messages.success(request, 'Successfully Registered')
next_url = request.POST.get('next') if 'next' in request.POST else 'profile'
return redirect(next_url)
return render(request, template_name=self.template_name, context={"form": form})
【问题讨论】:
标签: python python-3.x django exception