stratis
stratis

Reputation: 8042

Django mixins that wrap as_view()

In Django docs Class based views - Mixins I found the following snippet regarding the use of mixins that wrap as_view() method to provide extra functionality:

from django.contrib.auth.decorators import login_required

class LoginRequiredMixin(object):
    @classmethod
    def as_view(cls, **initkwargs):
        view = super(LoginRequiredMixin, cls).as_view(**initkwargs)
        return login_required(view)

class MyView(LoginRequiredMixin, ...):
    # this is a generic view
...

In the above example the author wraps the standard as_view() method in a mixin so that each view that inherits from LoginRequiredMixin passes through the login_required decorator.

My question is this: For this line to work

view = super(LoginRequiredMixin, cls).as_view(**initkwargs), 

shouldn't MyView inherit from View as well? Otherwise I believe that the call to super would fail for the reason that object doesn't have an as_view() method.

Thanks in advance.

Upvotes: 0

Views: 745

Answers (1)

knbk
knbk

Reputation: 53679

You should inherit from any generic class-based view. All generic views as defined by Django inherit from the base View class. The three dots (...) are a placeholder for any generic view class, they are not to be taken literal (and doing so would be a syntax error).

By the way, the most common way to decorate class-based views is to wrap the dispatch method in a decorator using the method_decorator from django.utils.decorators. Also check out decorating class-based views.

Upvotes: 2

Related Questions