2021年10月20日 18:31 by wst
django在网页开发中,有很多需要鉴权的页面:检测用户是否登录,如果未登录则跳转到登录页,登录成功后再跳回原来的界面。
1. 在需要鉴权的view中,检测是否登录,如未登录则绑定原始页面地址到next参数中。具体如下:
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render, redirect
# 对应的路径为/rights/
def index(request):
if not request.session.get('is_login', None):
return redirect('/authen/login?next={}'.format(request.path))
return render(request, "rights/nav.html")
2. 在登录页的get请求中,储存目标地址。
if request.method == 'GET':
request.session['login_from'] = request.GET.get('next')
return render(request, 'authen/login.html', {"message": "如果登录缓慢请刷新!"})
3. 在登录的post请求中,如果登录成功则跳转回原始地址。
if request.method == "POST":
username = request.POST.get('username', None)
password = request.POST.get('password', None)
print("request:",request.POST)
message = "所有字段都必须填写!"
if username and password: # 确保用户名和密码都不为空
username = username.strip()
# 用户名字符合法性验证
# 密码长度验证
# 更多的其它验证.....
try:
logger.info("start get user...")
user = User.objects.get(email=username)
logger.info("have got user.")
if user.password == password:
request.session['is_login'] = True
request.session['user_id'] = user.id
request.session['user_name'] = user.name
logger.info("start redirect...")
return redirect(request.session['login_from'])
登录view的完整代码如下:
def login(request):
logger.info("login start...")
if request.method == 'GET':
request.session['login_from'] = request.GET.get('next')
return render(request, 'authen/login.html', {"message": "如果登录缓慢请刷新!"})
elif request.method == "POST":
username = request.POST.get('username', None)
password = request.POST.get('password', None)
print("request:",request.POST)
message = "所有字段都必须填写!"
if username and password: # 确保用户名和密码都不为空
username = username.strip()
# 用户名字符合法性验证
# 密码长度验证
# 更多的其它验证.....
try:
logger.info("start get user...")
user = User.objects.get(email=username)
logger.info("have got user.")
if user.password == password:
request.session['is_login'] = True
request.session['user_id'] = user.id
request.session['user_name'] = user.name
logger.info("start redirect...")
return redirect(request.session['login_from'])
else:
message = "密码不正确!"
except:
message = "用户名不存在!"
logger.info("start view page.")
return render(request, 'authen/login.html', {"message": message})
return render(request, 'authen/login.html', {"message": "如果登录缓慢请刷新!"})
在此做个记录,希望能帮助到其他人。
如有问题,请在下方留言!