如何使用django login_required方法

时间:2017-10-15 19:37:57

标签: django django-views django-validation

class HomePage(TemplateView):

    template_name = 'obs/homepage.html'

我想让只有登录用户才能访问此视图。我怎样才能做到这一点?我见过django文档但是它用于函数。

1 个答案:

答案 0 :(得分:0)

我倾向于设置一个mixin在视图中使用,类似这样;

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView

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

class HomePage(LoginRequiredMixin,TemplateView):
    template_name = 'obs/homepage.html'