django @login_required登录限制(2)-返回登陆成功后的页面
本次要实现的功能是,访问未登录的视图函数,需要先跳转到登录页面,登陆成功在跳转回来。
之前在网上找了很多资料,都没有找到解决方案。
跳转到登录页面很好弄,就是登陆成功跳转回来出了问题,原因是登录后的post请求里拿不到之前url中next的值,所以只需要在发起get请求时,将next的值传递到模板的input标签里,type为hidden,之后再用post请求拿回来,就可以了!
只需要在url中拿到next的值,登陆成功后重定向到该值就可以实现了。
具体代码如下:
urls.py urlpatterns = [ url(r'^01-temp/$',views.temp_views), url(r'^form/$',views.fun,name='form'), url(r'^loginv/',views.loginl,name="login"), url(r'^createuser/$',views.create_user), url(r'^auth/$',views.auth), url(r'^logoutv/$',views.logoutl), ]
views.py def loginl(request): if request.method=="GET": nexturl = request.GET.get("next", "") print(request.user.is_authenticated) if request.user.is_authenticated: if nexturl: # login(request,request.user) return redirect(nexturl) else: return HttpResponse("登陆成功") else:# 判断用户是否登录成功 return render(request,'login.html',{'nexturl':nexturl}) elif request.method == "POST": nexturl=request.POST.get("nexturl","") uname=request.POST.get("uname","") upwd = request.POST.get("upwd", "") print(uname, upwd,nexturl,request.get_full_path) print(request.POST.get("next")) user=authenticate(request,username=uname,password=upwd) if user is not None: if user.is_active: # res = HttpResponse("sucess") # res.set_cookie(key='uname',value=uname,max_age=20000) # res.set_cookie(key='upwd', value=upwd,max_age=20000) login(request,user) if nexturl:#登陆成功后需要返回 print(uname, upwd, nexturl, request.get_full_path(), nexturl) return redirect(nexturl) else:#没有nexturl,返回主页即可 return HttpResponse("sucess") else: return HttpResponse("账户不存在") def logoutl(request): logout(request) return HttpResponse("成功退出") @login_required(login_url="/loginv/") def temp_views(request): return HttpResponse("ok")
login.html <form action="{% url 'login' %}" method="POST"> {% csrf_token %} 姓名<input type="text" name="uname"> <br> 密码<input type="password" name="upwd"> <br> <input type="hidden" name="nexturl" value="{{ nexturl }}"> <input type="submit" value="提交"> </form>
登出
访问01-temp,需要登录
登陆成功,访问01-temp的视图函数