实现登陆视图功能

it2022-05-28  74

实现登陆视图功能

1.获取表单请求数据

from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import redirect #导入重定向 # Create your views here. from app_login.models import User def 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.账号验证

获取表单数据后 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.添加警示信息

def login(request): message='所有字段都必须填写' if request.method=="POST": #提交表单后,满足请求为post就执行下面的内容 username = request.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 redirect('/index/') elif not t_username: # return HttpResponse('用户名不存在') message='用户名不存在' elif not t_password: # return HttpResponse('密码不存在') message='密码不存在' return render(request,'login/login.html',{"message":message}) #将message信息通过模板传递到网页 html页面 <form class='form-login' action="/login/" method="POST"> {% if message %} <!--类似if语句--> <div class="alert alert-warning">{{ message }}</div> <!--使用bootstrap的警示传递message信息--> {% endif %}

转载于:https://www.cnblogs.com/endmoon/p/9744738.html


最新回复(0)