Search code examples
pythondjangodjango-class-based-views

AttributeError - CBV 'function' object has no attribute 'as_view'


I'm using a regular CBV in comination with a decorator and I always get this error:

AttributeError: 'function' object has no attribute 'as_view'

Here is my code:

@my_decorator
class MyView(View):
    template_name = 'package/index.html'

    def get(self, request, *args, **kwargs):
        ...

Any ideas what I might be doing wrong?


Solution

  • The problem is that CBVs work differently with decorators as FBVs.

    Here's the way to go with it:

    @method_decorator(my_decorator)
    def dispatch(self, *args, **kwargs):
        return super(MyView, self).dispatch(*args, **kwargs)
    

    Here is a link to the documentation.