【发布时间】:2020-01-13 18:03:33
【问题描述】:
Django 不会引发针对用户名和密码添加到 forms.py 的验证错误。它确实会根据核心密码验证显示密码验证错误,但不会检查密码是否相同。这一切都基于 Django 中的基本用户模型。
您能帮我弄清楚为什么表单验证不起作用吗?我收到以下错误是用户名已在使用中或密码不匹配:“表单无效。” if 语句 if form.is_valid(): 失败。
Forms.py:
class CustomUserCreationForm(forms.ModelForm):
username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'class': "form-control"}))
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"}))
class Meta:
model = User
fields = ['username']
def clean_password(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords do not match")
return password2
def clean_username(self):
username = self.cleaned_data.get('username')
user_name = User.objects.filter(username=username)
if user_name.exists:
raise forms.ValidationError("Username already exists. Please try again.")
return username
def save(self, commit=True):
user = super(CustomUserCreationForm, self).save(commit=False)
user.username = self.cleaned_data['username']
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
Views.py:
def payments(request):
form = CustomUserCreationForm(request.POST)
if form.is_valid():
password1 = form.cleaned_data['password1']
#this works to do Django core validation, but not form validation
try:
validate_password(password1)
except ValidationError as e:
form.add_error('password1', e) # to be displayed with the field's errors
username = form.cleaned_data['username']
#this does not work
try:
validate_username(username)
except ValidationError as e:
form.add_error('username', e)
user = form.save(commit=False)
user.is_active = True
user.set_password(form.cleaned_data['password1'])
user.save()
else:
raise ValidationError("Form is not valid. Try Again.")
return render(request, 'next.html', {'form': form})
else:
form = CustomUserCreationForm()
return render(request, 'next.html', {'form': form})
模板
<div class="col-md-6 mb-4">
<h3 class="font-weight-bold">Register now</h3>
<div class="card">
<div class="card-body">
<p>Already have an account? <a href="{% url 'login' %}"> Login</a></p>
<form method="POST" class="post-form">
{% csrf_token %}
{{ form }}
<div class="text-center mt-4">
<button type="submit" class="btn btn-secondary">Register</button>
</div>
</form>
</div>
</div>
</div>
</div>
【问题讨论】:
-
你是如何在模板中渲染的?
-
@Matthew 添加了模板。
标签: django django-forms