【问题标题】:Even though its a class why is AttributeError: 'function' object has no attribute 'as_view'即使它是一个类,为什么是 AttributeError: 'function' object has no attribute 'as_view'
【发布时间】:2021-12-31 09:19:56
【问题描述】:

即使它是基于 calss 的函数,为什么当我使用 login_required 时会弹出此属性错误

错误信息

path('active/<int:pk>', UpdateActiveStatus.as_view(), name="activeStatus"),
AttributeError: 'function' object has no attribute 'as_view'

views.py

@login_required(login_url='/admin/')
class UpdateActiveStatus(UpdateView):
    model = Timeline
    form_class = UpdateActiveStatus
    template_name = 'timeline.html'
    success_url = reverse_lazy('timeline')

【问题讨论】:

  • 您的问题已经得到解答,请看这个链接:‌stackoverflow.com/questions/60871630/…
  • 你不能在类中使用继承LoginRequiredMixin的装饰器
  • @AashishKumar:有一些装饰器可以装饰一个类,@login_required 根本不是其中之一:它假定给它一个函数并返回一个函数。
  • @WillemVanOnsem 好的,谢谢我知道了

标签: django django-views


【解决方案1】:

你不能使用@login_required decorator [Django-doc]:这个装饰器返回一个函数,但即使使用这个函数也不起作用:装饰器根本无法处理一个类。

对于基于类的视图,您使用LoginRequiredMixin [Django-doc]

from django.contrib.auth.mixins import LoginRequiredMixin

class UpdateActiveStatus(LoginRequiredMixin, UpdateView):
    model = FutsalTimeline
    form_class = UpdateActiveStatus
    template_name = 'timeline.html'
    success_url = reverse_lazy('timeline')
    login_url = '/admin/'

【讨论】:

    【解决方案2】:

    我认为问题是由 decorator 产生的。改变它就像 ->

    @method_decorator(login_required, name='dispatch')
    class UpdateActiveStatus(UpdateView):
        model = FutsalTimeline
        form_class = UpdateActiveStatus
        template_name = 'timeline.html'
        success_url = reverse_lazy('timeline')
    

    您可以找到文档here

    • 但您应该使用 Mixin 类。使用 Mixin 类 会是这样的

        from django.contrib.auth.mixins import LoginRequiredMixin
        class UpdateActiveStatus(LoginRequiredMixin, UpdateView):
            model = FutsalTimeline
            form_class = UpdateActiveStatus
            template_name = 'timeline.html'
            success_url = reverse_lazy('timeline')
      

    您可以找到文档here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-15
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 2022-01-10
      • 2021-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多