django写用户登录判定并跳转制定页面的实例
人气:31. 首先看要设置登陆的界面 book/view.py
@user_util.my_login #相当于 select_all=my_login(select_all) def select_all(request): # 查询所有的书 book_list = BookInfo.objects.all() # 返回 return render(request, 'book/book_list.html', {'book_list': book_list}) @user_util.my_login #相当于 select_by_id=my_login(select_by_id) def select_by_id(request,book_id): bookinfo=BookInfo.objects.get(id=book_id) return render(request,'book/book_detail.html',{'bookinfo':bookinfo})
@user_util.my_login 是在utils/user_utils.py里面写的装饰器
使用session判定是否登录:login_user_id = args[0].session.get(‘login_user_id')
#登陆用的装饰器 def my_login(func): def inner(*args,**kwargs): login_user_id = args[0].session.get('login_user_id') if login_user_id: return func(*args,**kwargs) else: return redirect(reverse('user:login')) return inner
2. 设置登录模块的界面
设置session键值对进行存储: request.session[‘login_user_id']=user[0].id
def login(request): #获取cookie remember_user_name=request.COOKIES.get('remember_user_name','') return render(request, "user/login.html",{'remember_user_name':remember_user_name}) def login_handler(request): # 判断请求方式 if request.method == "GET": request_info = request.GET else: request_info = request.POST # 获取属性 user_name = request_info.get("user_name",'').strip() user_pwd = request_info.get("user_pwd",'').strip() remember = request_info.get("remember") user_pwd = my_md5(user_pwd) user=User.objects.filter(name=user_name, pwd=user_pwd) #print(user[0].id) # 查询 if len(user) != 0: #将登陆信息保存到session request.session['login_user_id']=user[0].id resp=HttpResponseRedirect(reverse("book:index")) #记住用户名 if remember=='1': resp.set_cookie('remember_user_name',user_name,3600*24*7) else: resp.set_cookie('remember_user_name',user_name,0) return resp # 转发 #return book_views.index(request) # 重定向 #return HttpResponseRedirect(reverse("book:index")) else: return HttpResponseRedirect(reverse("user:login"))
以上这篇django写用户登录判定并跳转制定页面的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
您可能感兴趣的文章:
加载全部内容