• django2给其它页面加上登陆校验


    1、

    参考地址:https://blog.csdn.net/Pansc2004/article/details/80494793

    (1)https://blog.csdn.net/weixin_42134789/article/details/81700922?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.control&dist_request_id=1328592.8898.16147388268452879&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.control

    (2)

    https://www.cnblogs.com/ellisonzhang/p/11417162.html

    清除浏览器缓存,直接访问 http://localhost/event_manage/,发现无需登陆,也可以直接访问该网页。

        Django中解决该问题的方法是,给对应的views.py中的方法加上装饰器 @login_required。

    step1: 在views.py中加入如下代码

      

    1. from django.shortcuts import render
    2. from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
    3. from django.contrib import auth
    4. from django.contrib.auth.decorators import login_required
    5.  
    6.  
    7. # Create your views here.
    8.  
    9. # def index(request):
    10. # return HttpResponse("欢迎!")
    11.  
    12. def index(request):
    13. return render(request, "index.html")
    14.  
    15.  
    16. def login_action(request):
    17. # request = HttpRequest(request)
    18. username = request.POST.get('username', '')
    19. password = request.POST.get('password', '')
    20. user = auth.authenticate(username=username, password=password)
    21. if user is not None:
    22. request.session['user'] = username # 将session信息记录到浏览器
    23. request.session['psw'] = password
    24. # Correct password, and the user is marked "active"
    25. auth.login(request, user)
    26. return HttpResponseRedirect('/event_manage/')
    27. else:
    28. return render(request, 'index.html', {'wronglyInput': '用户名或密码输入错误!'})
    29.  
    30. @login_required
    31. def event_manage(request):
    32. username = request.session.get('user', '') # 读取cookie
    33. password = request.session.get('psw', '')
    34. return render(request, "event_manage.html", {'user': username, 'psw': password})

    step2: 重新尝试访问 http://localhost/event_manage/ ,已经不能登陆了

    step3: 虽然访问被成功限制了,但我们希望是自动跳转到index页面,让用户输入账号和密码。 注意上面的路径,@login_required会将其设置到 /account/login/的路径上去,那么只要我们在urls.py中做相应的路径设置,让其跳转到index页面即可。

    1. urlpatterns = [
    2. url(r'^$', views.index),
    3. url(r'^index/$', views.index),
    4. url(r'^admin/', admin.site.urls),
    5. url(r'^login_action/', views.login_action),
    6. url(r'^event_manage/', views.event_manage),
    7. url(r'^accounts/login/$', views.index),
    8. ]

      step4: 再次运行,访问event_manage,跳转成功



  • 相关阅读:
    【背包九讲专题】完全背包
    【指数降幂】费马小定理降幂&欧拉降幂
    【背包九讲专题】01背包
    2016ACM-ICPC亚洲区域赛(大连)
    Codeforces Round #697 (Div. 3)题解报告(A-G)
    pywifi 网卡反复断开连接
    webdriver xpath frame alert window
    windows pexpect ssh
    python3 串口读写 pyserial
    python3 unittest addTest 与addtests
  • 原文地址:https://www.cnblogs.com/yaok430/p/14420410.html
Copyright © 2020-2023  润新知