form验证可以减少查询数据库,所以代码先预先验证,有问题可以返回给前端显示
1.在users文件夹下新建forms.py文件,用来验证用户名和密码是否为空,密码长度是否大于6
# -*- coding: utf-8 -*-
# 作者:神秘藏宝室
# 日期:2018/12/30 21:56
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(required=True)
password = forms.CharField(required=True, min_length=6)
2.修改views.py下的LoginView的逻辑,当form出问题返回给前端login_form内容
class LoginView(View):
def get(self, request):
return render(request, 'login.html', {})
def post(self, request):
login_form = LoginForm(request.POST)
if login_form.is_valid():
user_name = request.POST.get("username", "")
pass_word = request.POST.get("password", "")
user = authenticate(username=user_name, password=pass_word)
if user is not None:
login(request, user)
return render(request, "index.html")
else:
return render(request, "login.html", {"msg": u"用户名或者密码错误!"})
else:
return render(request, "login.html", {"login_form": login_form})
3.前端显示错误,显示出错误内容
<div class="form-group marb20 {% if login_form.errors.username %}errorput{% endif %}">
<label>用 户 名</label>
<input name="username" id="account_l" type="text" placeholder="手机号/邮箱" />
</div>
<div class="form-group marb8 {% if login_form.errors.password %}errorput{% endif %}">
<label>密 码</label>
<input name="password" id="password_l" type="password" placeholder="请输入您的密码" />
</div>
<div class="error btns login-form-tips" id="jsLoginTips">{% for key,error in login_form.errors.items %} {{ error }} {% endfor %}{{ msg }}</div>
以上代码可以实现,错误选项的红框标记,错误问题显示
输入为空
密码长度小于6
正常的用户名密码错误,查询数据库后错误显示
原文地址:https://www.cnblogs.com/Mysterious/p/10200994.html
时间: 2024-11-10 07:51:47