• 装饰器login_required


    装饰器login_required将游客身份引导至登录页面,登录成功后跳转到目的页面

    url.py

    path('login/',views.login),
    path('home/',views.home),
    

    views.py

    from django.contrb.auth.decorators import login_required
    @login_required
    def home(request):
        return render(request,'home.html')
    

    装饰器@login_required,会跳转到django设置的默认路径:‘/accounts/login/’,在setting.py中进行修改,跳转到登录页的路由

    setting.py

    LOGIN_URL ='/login/'
    

    第一次请求:http://127.0.0.1:8999/home/

    转到'http://127.0.0.1:8999/login/?next=home'

    登录成功,转到'http://127.0.0.1:8999/home/'

    如果是ajax请求如何实现登录成功后自动跳回第一次请求的路径:

    success:function(response){
        if(resonse.user){
            if(location.search){
                //间接进入login时,转回
                location.href=location.search.slice(6)
                //直接进入login时,转到首页
            else{location.href='/home/'}
            }
        }
    }
    // search 属性是一个可读可写的字符串,可设置或返回当前 URL 的查询部分(问号 ? 之后的部分)。
    // 假设当前的URL就是http://www.runoob.com/submit.htm?email=someone@ example.com
    //  location.search:?email=someone@example.com
    

    类视图中如何使用login_required

    from django.views import View
    from django.contrib.auth.decorators import login_required
    from django.utils.decorators import method_decorator
    class Myview(View):
    	@method_decorator(login_required)
        def dispatch(self, request, *args, **kwargs):
            if request.method.lower() in self.http_method_names:
                handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed
            return handler(request, *args, **kwargs)
    
  • 相关阅读:
    Elasticsearch 入门教程
    Spring Boot集成JasperReports生成PDF文档
    Java程序员须知的七个日志管理工具
    vue 2 使用Bus.js进行兄弟(非父子)组件通信 简单案例
    spring boot项目在外部tomcat环境下部署
    linux 如何正确的关闭mongodb
    Centos7下yum安装配置nginx与php
    Centos7 搭建lnmp环境 (centos7+nginx+MySQL5.7.9+PHP7)
    CentOS7安装MySQL
    搭建MySQL高可用负载均衡集群(转)
  • 原文地址:https://www.cnblogs.com/notfind/p/11962041.html
Copyright © 2020-2023  润新知