django 用装饰器判断用户是否登录

前言:

如今在网站的编写中无不和用户息息相关,用户登录后的页面是没有登录是进不来的。在 Django 中也考虑到了这一点特制了 login_required 这个装饰器来完成

开始:

  1. 首先现在 setting.py 文件中添加这个全局配置
LOGIN_URL = '/xadmin/'
# 登录页面的路径
  1. 在需要的 def 函数上使用这个装饰器
@login_required
def test2(request):
   return render(request, 'index.html')

View 创建的 class 中使用:

@method_decorator(login_required, name='dispatch')
class Index(View):

    def get(self, request):
        return render(request, 'index.html')

    def post(self, request):
        return render(request, 'index.html')

如果你只想指定的一种提交方式才验证也可以

@method_decorator(login_required, name='get')
class Index(View):

    def get(self, request):
    	"""
    	这里一旦请求就会被验证
    	"""
        return render(request, 'index.html')

    def post(self, request):
        return render(request, 'index.html')

@method_decorator(login_required, name='post')
class Index(View):

    def get(self, request):
        return render(request, 'index.html')

    def post(self, request):
    	"""
    	这里一旦请求就会被验证
    	"""
        return render(request, 'index.html')

所有的方法本质上都是通过 dispatch 这个函数反射执行,如果想要在执行 get 或 post 方法前执行其他步骤,可以重写 dispatch。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值