场景:
Django开发中,如果我们使用了类视图,如:ListView、DetailView、UpdateView
等,这时我们又想要对这个视图添加一个装饰器,来实现某种功能,这时候该怎么处理呢?
环境:
python 3.6
Django 1.11
错误用法
错误实现方式:
def is_login(func):
def wrapper(request,*args,**kwargs):
# 若检测不到用户就跳转登录页面
if not request.session.get("user"):
return redirect(reverse('login'))
return func(request,*args, **kwargs)
return wrapper
@is_login
class myinfor(generic.ListView):
pass
报错信息:
AttributeError: 'function' object has no attribute 'as_view'
正确用法
实现方式一:
from django.utils.decorators import method_decorator
def is_login(func):
def wrapper(request,*args,**kwargs):
# 若检测不到用户就跳转登录页面
if not request.session.get("user"):
return redirect(reverse('login'))
return func(request,*args, **kwargs)
return wrapper
# 使用method_decorator将装饰器包裹起来,同时,name参数是必须的,dispatch支持所有请求类型,包含get、post等,如果指定某种请求方式改为:name='get'. 教程源站(bigyoung.cn)
@method_decorator(is_login, name='dispatch')
class myinfor(generic.ListView):
pass
实现方式二:
通过路由配置实现:(不推荐)
'''教程源站:BigYoung.cn'''
from django.utils.decorators import never_cache
urlpatterns += [
path('myinfo/', never_cache(myinfor.as_view()), name='myinfo'),
]
进阶用法:
如果你有多个装饰器需要装饰,该如何操作呢?
欢迎大家访问BigYoung小站(http://www.bigyoung.cn)查看完整版。
本文首发于BigYoung小站
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦