2013-05-01 77 views
0

我的應用中有很多基於類的視圖。他們中的大多數只能由經過認證的工作人員訪問。如何輕鬆地添加用戶檢查大量的基於類的視圖?django爲基於類的視圖添加用戶認證檢查

對於非標準功能的觀點我加裝飾是這樣的:

def only_staff_allowed(fn): 
    '''decorator''' 
    def wrapped(request, *args, **kwargs): 
     if request.user.is_staff: 
      return fn(request, *args, **kwargs) 
     else: 
      return HttpResponseRedirect(reverse('moderator:login')) 
    return wrapped 

@only_staff_allowed 
def dashboard(request): 
    ''' now accessible only by staff users ''' 
    return render(request, 'moderator/dashboard.html', {}) 

我該怎麼辦類似這樣的基於類的意見財產以後?

class AddressesAddList(ListView): 
    template_name = 'moderator/addresses/add_list.html' 
    queryset = Address.objects.filter(need_moderating=True) 
    paginate_by = 100 

我應該添加一些mixin還是重寫一些方法?或者我可以裝飾一些東西?

回答

4

您應該修飾基於類的視圖的分派方法。見下文。

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

class ProtectedView(TemplateView): 
    template_name = 'secret.html' 

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

查看文檔here

4

實際上,至少有三種方法可以避免裝飾您想要登錄的每個視圖類的dispatch方法。

如果只有幾個這樣的觀點,您可以使用URL配置那個裝飾,就像這樣:

url(r"^protected/$", login_required(ProtectedView.as_view()), name="protected_view"), 

或者,更好的,如果你要保護多一點意見,就是用在LoginRequiredMixindjango-braces

from braces.views import LoginRequiredMixin 

class ProtectedView(LoginRequiredMixin, TemplateView): 
    template_name = 'secret.html' 

而且,如果你有很多的意見,以保護,你應該使用一箇中間件來覆蓋在一個一堆意見,一舉;沿線的東西:

class RequireLoginMiddleware(object): 
    """Requires login for URLs defined in REQUIRED_URLS setting.""" 
    def __init__(self): 
     self.urls = tuple([re.compile(url) for url in REQUIRED_URLS]) 
     self.require_login_path = getattr(settings, 'LOGIN_URL', '/accounts/login/') 
    def process_request(self, request): 
     if not request.user.is_authenticated() and request.path != self.require_login_path: 
      for url in self.urls: 
       if url.match(request.path): 
        return HttpResponseRedirect(u"{0}?next={1}".format(self.require_login_path, request.path)) 
2

您可以使用LoginRequiredMixin。這會將未經身份驗證的用戶重定向到頁面集。

from braces.views import LoginRequiredMixin 

class DashboardIndex(LoginRequiredMixin, TemplateView): 

template_name = 'dashboard/index.html' 
login_url = 'action:login' #Where you must set the page else will use default. 
raise_exception = False 

https://django-braces.readthedocs.org/en/latest/access.html#loginrequiredmixin