def check_login(func): # 自定义登录验证装饰器
def warpper(request, *args, **kwargs):
is_login = request.session.get('is_login', False)
if is_login:
func(request, *args, **kwargs)
else:
return redirect("/login")
return warpper
def login_user(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
all_data = form.clean() #获取post数据,例如 {'username': u'yang1', 'password': 111}
exist = User.objects.filter(username = all_data['Form_username'],password = all_data['Form_password']).first()
if exist:
request.session['is_login'] = True #设置session的随机字段值
request.session['username'] = exist.username #设置uname字段为登录用户
return redirect('/home')
else:
return HttpResponse("账户或密码错误")
else:
form = LoginForm()
return render(request, 'login.html', {'form': form})
@Check_Login
def home(request):
username = request.session.get('uname', False) #获取登录用户名
return render(request, home.html', {'username': username}) #用户名渲染到前端页面
原文地址:https://www.cnblogs.com/midworld/p/10992000.html
时间: 2024-10-08 23:52:12