[Fixed]-Django – Non-class-based views authorization

1👍

You use the login_required decorator https://docs.djangoproject.com/en/1.8/topics/auth/default/#the-login-required-decorator.

You can’t decorate a class, because a decorator is a function that takes a function x as an argument, does something with this function x and returns it afterwards. This is why you need the rather “useless” dispatch method here, that just calls it’s parent without doing anything, because a class is not a function.


Edit: A note for later – If you’d like to skip the “useless” dispatch method you could write a Mixin (a small little class that just overrides a particular function) that just adds @method_decorator(login_required)todispatchand use it with allView`s.

You actually don’t need to do that really. There’s django braces out there that does this for you. Then you can just do:

class AdminView(braces.views.LoginRequiredMixin, View):
    def get(request, *args, **kwargs):
        pass  # Do some logged-in user stuff here

Leave a comment