Implementing the Login View function
1. Get form Request data
from django.shortcuts import renderfrom django.http import HttpResponsefrom django.shortcuts import redirect #导入重定向# Create your views here.from app_login.models import Userdef index(request): return render(request, 'login/index.html')def login(request): if request.method=="POST": #提交表单后,满足请求为post就执行下面的内容 username = request.POST.get('username') #获取表单中输入的用户名和密码 password = request.POST.get('password') print(username,password) #用于查看输入的信息 # user = User(username, password) #添加到User表中 # user.save() #存储到数据库中 return redirect('/index/') #重定向url到index return render(request,'login/login.html')#需要注意,由于页面跳转属于跨域请求,安全起见,是不允许了,想要访问协议在form表单中加入{% csrf_token %},以解决该问题
2. Account Verification
获取表单数据后1.判断账号密码是否为空if username and password: 如果不为空, 2.去除输入框中前后的空格(防止误输入) username=username.strip()3.验证账号密码1)查看数据库中是否存在,不存在就无法登陆,存在就匹配密码学习,匹配成功就登陆,失败就无法登陆#查询数据库中是否存在该用户名和密码t_username=User.objects.filter(name=username) t_password=User.objects.filter(password=password)if t_username and t_password: return redirect('/index/')elif not t_username: return HttpResponse('用户名不存在')elif not t_password: return HttpResponse('密码不存在')
3. Add alert information
DEF login (Request): Message= ' All fields must be filled in ' if request.method== ' post: #提交表单后, fulfill the request as POST to execute the following content username = requ Est. Post.get (' username ') #获取表单中输入的用户名和密码 password = Request. Post.get (' password ') print (Username,password) if username and password: #用户名和密码都不为空 username= Username.strip () #清除用户名前后的空格 # user = User (username, password) #添加到User表中 # user.save () #存储到数据库中 #查询数据库中是否存在该用户名和密码 T_username=user.objects.filter (name=username) T_password=user.objects.filter (Password=password) if T_username and T_password:return Redirec T ('/index/') elif not t_username: # return HttpResponse (' username not present ') message= ' user name does not exist ' Elif not t_password: # return HttpResponse (' Password not present ') message= ' password does not exist ' return R Ender (Request, ' login/login.html ', {"message": Message}) #将message信息通过模板传递to a Web page
html页面<form class='form-login' action="/login/" method="POST"> {% if message %} <!--类似if语句--> <div class="alert alert-warning">{{ message }}</div> <!--使用bootstrap的警示传递message信息--> {% endif %}
Implementing the Login View function