2017-02-17 76 views

回答

2

使用@login_required使用基于函数的观点:

@login_required  
def my_view(request): 
    return HttpResponse('hello') 

您可以使用@method_decorator(login_required)与基于类的意见,

@method_decorator(login_required, name='dispatch') 
class MyView(TemplateView): 
    template_name = 'hello.html' 

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

但它可能是简单的使用LoginRequiredMixin代替:

from django.contrib.auth.mixins import LoginRequiredMixin 

class MyView(LoginRequiredMixin, TemplateView): 
    template_name = 'hello.html' 
2

method_decorator装饰器将函数装饰器转换为方法装饰器,以便它可以用于实例方法。

login_decorator是一个函数装饰器,因此它只能用在视图函数中。

来源:django documentation

相关问题