Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django user_passes_test decorator

Tags:

python

django

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?

like image 350
Hedde van der Heide Avatar asked Nov 10 '11 16:11

Hedde van der Heide


People also ask

How do I authenticate a user in Django?

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 ...

What is decorator in Django?

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.

How can I see my password in Django?

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.

How do you check if a user is logged in Django?

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 .


2 Answers

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) 
like image 69
Chris Pratt Avatar answered Sep 18 '22 23:09

Chris Pratt


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

like image 40
cerberos Avatar answered Sep 16 '22 23:09

cerberos