2017-02-17 24 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