Django的ListView添加login_required修饰符

在Django里,提供了ListView、DetailView内置类方便的编写视图函数,在我的项目中,有一个展示列表的函数,必须要登录后才能操作,即要添加login_required

原始代码

1
2
3
4
5
6
from django.contrib.auth.decorators import login_required

@login_required
def management(request):
"""Privilege management url"""
return render(request, 'management.html')

采用login_required修饰过页面,必须要登录后才可访问。

由于该页面展示的是某个model的list,所以采用DetailView才是更专业的做法。但是login_required明显不能对类进行修饰。

对类进行修饰

使用from django.utils.decorators import method_decorator可对类进行修饰。

有两种修饰方法:

其一:对类中的方法进行修饰:

1
2
3
4
5
6
7
8
9
10
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView

class ProtectedView(TemplateView):
template_name = 'secret.html'

@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)

其二:对整个类进行修饰:

1
2
3
@method_decorator(login_required, name='dispatch')
class ProtectedView(TemplateView):
template_name = 'secret.html'

修改后的代码如下

1
2
3
4
5
6
7
8
9
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views import generic

@method_decorator(login_required, name='dispatch')
class ProtectedView(generic.ListView)

def dispatch(self, request, *args, **kwargs):
return super(PrivilegeManagement, self).dispatch(request, *args, **kwargs)

参考资料

0%