如何在Django

时间:2017-07-05 20:34:11

标签: python django authentication authorization

我正在尝试使用@login_reuqired装饰器。对于正常的功能它工作正常,但是当我尝试在我的UpdateView中使用它时,我收到此错误"AttributeError: 'function' object has no attribute 'as_view'"

这是我的view.py

@login_required
class RoomUpdate(UpdateView):
    model = Room
    fields = ['Name', 'RoomTypeID']
    template_name='WebApp/room_form.html'`

这是我的urls.py

 url(r'^roomList/updateRoom/(?P<pk>[0-9]+)/$', views.RoomUpdate.as_view(), name='room_update'),

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您需要修饰dispatch方法:

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

class RoomUpdate(UpdateView):
    model = Room
    fields = ['Name', 'RoomTypeID']
    template_name='WebApp/room_form.html'

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

或者您可以login_required使用urls.py作为此功能:

from django.contrib.auth.decorators import login_required

url(r'^roomList/updateRoom/(?P<pk>[0-9]+)/$', login_required(views.RoomUpdate.as_view()), name='room_update'),

从Django 1.9+开始,你也可以使用mixin:

from django.contrib.auth.mixins import LoginRequiredMixin

class RoomUpdate(LoginRequiredMixin, UpdateView):
    fields = ['Name', 'RoomTypeID']
    template_name='WebApp/room_form.html'

答案 1 :(得分:1)

对于Django 1.9+,您可以使用mixin:

from django.contrib.auth.mixins import LoginRequiredMixin

class RoomUpdate(LoginRequiredMixin, UpdateView):
    fields = ['Name', 'RoomTypeID']
    template_name='WebApp/room_form.html'`