How do I implement the @user_passes_test(lambda u: u.is_superuser)
decorator for class based views? I have used this before for function based views, and I have a workaround but it feels unnaturally.
Shouldn't this be covered by the dispatch method?
from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid ...
Decorators are a way to restrict access to views based on the request method or control caching behaviour. This is particularly useful when you want to separate logged-in users from unauthenticated users or create an admin page that only privileged users can access.
In order to use the built-in Django check_password() function, we need to import it, which is shown in the first line of code. So the current password of the user is, request. user. password, which we store in the currentpassword variable.
Check the Logged in User in Views in Django We can use request. user. is_authenticated to check if the user is logged in or not. If the user is logged in, it will return True .
You use @method_decorator
on the dispatch
method of the class:
from django.views.generic import View from django.utils.decorators import method_decorator from django.contrib.auth.decorators import user_passes_test class MyView(View): @method_decorator(user_passes_test(lambda u: u.is_superuser)) def dispatch(self, *args, **kwargs): return super(MyView, self).dispatch(*args, **kwargs)
Building on @Chris Pratt's answer, you'll probably want to do this in multiple view classes so it makes sense to turn it into a mixin.
class SuperuserRequiredMixin(object): @method_decorator(user_passes_test(lambda u: u.is_superuser)) def dispatch(self, *args, **kwargs): return super(SuperuserRequiredMixin, self).dispatch(*args, **kwargs)
Usage
class MyView(SuperuserRequiredMixin, View): def get(self, request): ...
To prevent unexpected MRO bugs, ensure the mixin is the first inherited class.
You can implement a LoginRequiredMixin
, or any other common tests you use in your app, in the same way.
Edit: Django 1.9 adds AccessMixin, LoginRequiredMixin, PermissionRequiredMixin, and UserPassesTestMixin
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With