如何在django中对类视图进行身份验证

时间:2013-01-14 07:06:26

标签: python django

在Django文档中,他们说https://docs.djangoproject.com/en/dev/topics/auth/default/#user-objects

from django.contrib.auth.decorators import login_required

@login_required(login_url='/accounts/login/')
def my_view(request):

但是如何在基于类的视图

上使用login_required
@login_required
classMyCreateView(CreateView):

这会产生错误

'function' object has no attribute 'as_view'

2 个答案:

答案 0 :(得分:12)

您可以通过多种方式执行此操作,例如

https://docs.djangoproject.com/en/dev/topics/class-based-views/#decorating-class-based-views

  1. 这个
  2.  urlpatterns = patterns('',
            (r'^about/', login_required(TemplateView.as_view(template_name="secret.html"))),
            (r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())),
        )
    
    1. 或者这个
    2.   

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

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

答案 1 :(得分:0)

对于Django 1.9或更高版本;基于类的视图(CBV)可以使用auth包中的mixin。只需使用以下声明导入 -

from django.contrib.auth.mixins import LoginRequiredMixin
  

mixin是一种特殊的多重继承。使用mixins有两种主要情况:

     
      
  1. 您希望为课程提供许多可选功能。
  2.   
  3. 您想在许多不同的类中使用一个特定功能。
  4.         

    了解详情:What is a mixin, and why are they useful?

CBV使用login_required装饰器

<强> urls.py

from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from .views import ListSecretCodes

urlpatterns = [
    url(r'^secret/$', login_required(ListSecretCodes.as_view()), name='secret'),
]

<强> views.py

from vanilla import ListView

class ListSecretCodes(LoginRequiredMixin, ListView):
    model = SecretCode

CBV使用LoginRequiredMixin

<强> urls.py

from django.conf.urls import url
from .views import ListSecretCodes

urlpatterns = [
    url(r'^secret/$', ListSecretCodes.as_view(), name='secret'),
]

<强> views.py

from django.contrib.auth.mixins import LoginRequiredMixin
from vanilla import ListView

class ListSecretCodes(LoginRequiredMixin, ListView):
    model = SecretCode
  

注意

     

上面的示例代码使用django-vanilla轻松创建基于类的视图(CBV)。使用Django的内置CBV和一些额外的代码行也可以实现同样的目的。