【问题标题】:Transform Function in Class Based View with decorator in Django在 Django 中使用装饰器在基于类的视图中转换函数
【发布时间】:2016-11-09 21:58:43
【问题描述】:

我有这个代码:

#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

我不知道如何实现上面提到的装饰器。

【问题讨论】:

标签: django login decorator mixins


【解决方案1】:

Engraçado, só funcionou desse jeito。

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

【讨论】:

    猜你喜欢
    • 2017-03-08
    • 1970-01-01
    • 2023-02-07
    • 2023-03-14
    • 1970-01-01
    • 2012-06-11
    • 2015-03-07
    • 2021-05-28
    • 2020-07-07
    相关资源
    最近更新 更多