我有一个用户登录表单
class PersonLoginForm(forms.Form):
username = forms.CharField(max_length=20, required=True)
password = forms.CharField(max_length=100, required=True)
def clean_password(self):
user = Person.objects.get(username=self.cleaned_data['username'])
if not user.check_password(self.cleaned_data['password']):
self.add_error('password', 'That password is incorrect!')
return self.cleaned_data
在那里我检查密码是否正确,这样我就可以在模板中显示错误消息我访问我的模板中的错误消息,就像一样
<div class="field-wrapper">
{% render_field form.password.errors %}
{% render_field form.password.label_tag %}
{% render_field form.password placeholder='password...' type='password'%}
</div>
但是错误消息没有显示!这是登录表单的视图
def user_login(request):
if request.method == 'POST':
form = PersonLoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
messages.success(request, 'Successfully logged in!')
return redirect('all_users')
print(form.errors)
form = PersonLoginForm()
context = {
'form': form,
'title': 'Login',
}
return render(request, 'index/login.html', context)
我在form.is_valid()
评估为False
后打印它
<ul class="errorlist"><li>password<ul class="errorlist"><li>That password is incorrect!</li></ul></li></ul>
它甚至没有显示在模板中
当您的请求方法是GET以保持空表单时,您可以将这个新表单form=PersonLoginForm((添加到else语句中。通过添加else语句,您可以避免表单的新分配;在验证过程之后,它将跳转到呈现(请求,……(,表单实例包含所有验证错误
def user_login(request):
if request.method == 'POST':
form = PersonLoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
messages.success(request, 'Successfully logged in!')
return redirect('all_users')
print(form.errors)
else:
form = PersonLoginForm()
context = {
'form': form,
'title': 'Login',
}
return render(request, 'index/login.html', context)