Home > Software design >  Even though its a class why is AttributeError: 'function' object has no attribute 'as
Even though its a class why is AttributeError: 'function' object has no attribute 'as

Time:12-31

even though its a calss based func why is this attribute error popping up when i use login_required

error Message

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 = FutsalTimeline
    form_class = UpdateActiveStatus
    template_name = 'timeline.html'
    success_url = reverse_lazy('timeline')

CodePudding user response:

You can not use the @login_required decorator [Django-doc]: this decorator returns a function, but even using the function will not work: the decorator simply can not handle a class.

For class-based views, you use the 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/'

CodePudding user response:

I think the issue is generated for the decorator. Just change it like ->

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

You can find the doc here

  • But you should use the Mixin classes. With Mixin class It will look like

      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')
    

You can find the doc here

  • Related