python - 如果 Django form_template 中的密码和用户名不正确,则显示错误消息
问题描述
当用户使用form_template
. 到目前为止,我尝试了以下方法,但它不起作用。
表格.py:
class UserForm(forms.Form):
username=forms.CharField(max_length=50)
password=forms.CharField(widget=forms.PasswordInput)
model=User
fields=['username', 'password']
视图.py:
class loginform(View):
template_name='essay/Login.html'
form_class=UserForm
def get(self,request): # if the request is get then only view the function
form=self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self,request):
form=self.form_class(request.POST)
if form.is_valid():
#user = form.save(commit=False) # it doesnot save in database, it is used to et clean the values
# clean data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
# authenticate user:
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
if(request.user.is_prof==True):
return redirect('essay:file', )
else:
return redirect('essay:stdprofile')
else:
return render(request,self.template_name, {
'error_message': ' Login Failed! Enter the username and password correctly', })
else:
msg = 'Errors: %s' % form.errors.as_text()
return HttpResponse(msg, status=400)
return render(request, self.template_name, {'form': form})
表单模板:
{% for field in form %}
<div class="form-group">
<label class="control-label col-sm-2">{{ field.label_tag }}</label>
<div class="col-sm-10">{{ field }}</div> <!-- inputs on the rigth -->
</div>
{% endfor %}
登录.html:
<body>
<div class="login-card">
<h1>Log-in</h1><br>
<form class="form-horizontal" action="" method="POST" enctype="multiport/form-data">
{% csrf_token %}
{% include 'essay/form_template.html' %}
<input type="submit" name="login" class="login login-submit" value="login">
</form>
{% error_message %}
</div>
</body>
我输入无效凭据时遇到的问题,用户名和密码字段消失了,它也没有显示错误消息。
解决方案
在表单页面的字段中添加,
{{field.errors}}
或在 csrf 标签下添加,
{{form.errors}}
这将显示您所有的字段错误,对于非字段错误添加,
{{form.non_field_errors}}
此外,您还可以使用 Django 内置消息来显示您的自定义消息。
推荐阅读
- python - 如何在python列表数组中找到大值的位置
- c# - 在 oneClick 发布的项目中找不到 rdlc
- javascript - 使用材料 ui 弹出框反应错误边界意外行为
- python - 将数据框与公共列连接起来
- electron - desktopCapturer.getSources 和 getUserMedia 不起作用
- xamarin - Xamarin iOS 部署到苹果商店但缺少图标错误
- python - _tkinter.TclError: 错误# args: 应该是“.!entry2 插入索引文本”
- c++ - C++ 理解缓冲区和 std::endl
- ssl - 带有 SSL 的 Kafka 在生产者中失败
- python - 使用“onclick”抓取 Javascript