Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django permission_required error message?

Tags:

django

I've added this decorator to one of my views

@permission_required('codename')

When a user visits that page and doesn't have the required permissions, he is redirected the login page, but it doesn't really tell him why he's been redirected there. Worse yet, if he logs in, and still doesn't have the permissions, he's going to be completely clueless as to why he can't access that page!

Isn't there a way I can tap into the messages framework and post an error at the same time?

like image 401
mpen Avatar asked Aug 10 '10 16:08

mpen


4 Answers

Not sure what version of Django you are using, but in Django 1.4 and higher you can use:

from django.contrib.auth.decorators import permission_required

@permission_required('app.permission',raise_exception=True)
def myView(request):
    #your view code

This will raise a 403 exception and if you have a 403.html page at the base of your template folder it will server this out.

If you are using class based views:

from django.views.generic.base import View
from django.contrib.auth.decorators import permission_required
from django.utils.decorators import method_decorator

class MyView(View):

    @method_decorator(permission_required('app.permission',raise_exception=True)
    def get(self, request):
        #your GET view

Hope this helps.

like image 190
Sanjeev Avatar answered Oct 22 '22 07:10

Sanjeev


You can tap into the messages framework and provide an error message. See my answer to an identical question.

like image 24
Manoj Govindan Avatar answered Oct 22 '22 07:10

Manoj Govindan


You could use login_url parameter in this decorator to redirect to some other page, rather than login page. Or you can simply write your own decorator based on the code from django:

def permission_required(perm, login_url=None):
    """
    Decorator for views that checks whether a user has a particular permission
    enabled, redirecting to the log-in page if necessary.
    """
    return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url)

Simply change login_url to some redirect_to and it won't cause any confusion.

like image 40
gruszczy Avatar answered Oct 22 '22 06:10

gruszczy


Use @permission_required_or_403('codename')

This will redirect the users to a 403 'permission denied' error page.

like image 1
theycallmemorty Avatar answered Oct 22 '22 06:10

theycallmemorty