使用 Django 中的装饰器在基于 Class 的视图中转换函数
Transform Function in Class Based View with decorator in Django
我有这个代码:
#decorators.py
from django.contrib.auth.decorators import user_passes_test
def superuser_required(func):
return user_passes_test(
lambda u: u.is_authenticated() and u.is_superuser)(func)
# views.py
@superuser_required
def dashboard_candidates(request):
persons = Person.objects.all()
return render(request, 'my_template.html', {'persons': persons})
如何在适配装饰器的ListView中改造这个函数?
我试试:
PersonList(LoginRequiredMixin, ListView)
model = Person
paginate_by = 10
我不知道如何实现上面提到的装饰器。
有趣,只有那样才有效。
from django.utils.decorators import method_decorator
class SuperuserRequiredMixin(object):
@method_decorator(user_passes_test(lambda u: u.is_authenticated() and u.is_superuser))
def dispatch(self, *args, **kwargs):
return super(SuperuserRequiredMixin, self).dispatch(*args, **kwargs)
class PersonList(SuperuserRequiredMixin, ListView):
model = Person
paginate_by = 20
我有这个代码:
#decorators.py
from django.contrib.auth.decorators import user_passes_test
def superuser_required(func):
return user_passes_test(
lambda u: u.is_authenticated() and u.is_superuser)(func)
# views.py
@superuser_required
def dashboard_candidates(request):
persons = Person.objects.all()
return render(request, 'my_template.html', {'persons': persons})
如何在适配装饰器的ListView中改造这个函数?
我试试:
PersonList(LoginRequiredMixin, ListView)
model = Person
paginate_by = 10
我不知道如何实现上面提到的装饰器。
有趣,只有那样才有效。
from django.utils.decorators import method_decorator
class SuperuserRequiredMixin(object):
@method_decorator(user_passes_test(lambda u: u.is_authenticated() and u.is_superuser))
def dispatch(self, *args, **kwargs):
return super(SuperuserRequiredMixin, self).dispatch(*args, **kwargs)
class PersonList(SuperuserRequiredMixin, ListView):
model = Person
paginate_by = 20