在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'
答案 0 :(得分:12)
您可以通过多种方式执行此操作,例如
https://docs.djangoproject.com/en/dev/topics/class-based-views/#decorating-class-based-views
urlpatterns = patterns('', (r'^about/', login_required(TemplateView.as_view(template_name="secret.html"))), (r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())), )
类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有两种主要情况:
- 您希望为课程提供许多可选功能。
- 您想在许多不同的类中使用一个特定功能。
醇>
<强> 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
<强> 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和一些额外的代码行也可以实现同样的目的。