How to check current user's permissions from a Group in Django?
29,047
Try this:
if request.user.has_perm('app_name.can_add_cost_price'):
From the docs:
where each perm is in the format 'app_label.permission codename'
Related videos on Youtube
Author by
MiniGunnR
Updated on August 23, 2021Comments
-
MiniGunnR almost 3 years
I have a group
EuropartsBuyer
and model namedProduct
.The following code adds a permission to the Product model.
class Meta: permissions = ( ("can_add_cost_price", "Can add cost price"), )
In one of my views I have the following code to add this permission to that group.
europarts_buyer, created = Group.objects.get_or_create(name='EuropartsBuyer') add_cost_price = Permission.objects.get(codename='can_add_cost_price') europarts_buyer.permissions.add(add_cost_price)
With the help of Django Admin I have added a user to the group
EuropartsBuyer
.When I use the following code in another view
if request.user.has_perm('can_add_cost_price'): do something
the result is supposed to be
True
but it is showingFalse
. Thus, the code under the if clause doesn't run.I have imported the currently logged in user in Django shell and when I test the permission again it shows False.
What am I doing wrong here?
-
SomeTypeFoo over 7 yearsDid you check if the request.user is a AnonymousUser instance?
-
MiniGunnR over 7 years@ThulasiRam Yes. I have to log in to access that particular view.
-
SomeTypeFoo over 7 yearsThat i get but If you use DRF and removed authentication classes although you are logged in..in the request the user will be Anonymous. So can you try printing request.user first before checking for permissions that way you can be sure. @MiniGunnR
-
MiniGunnR over 7 yearsI did. The user is logged in.
-
MiniGunnR over 7 yearsI forgot to use the app label. Now it's working.
if request.user.has_perm('europarts.can_add_cost_price')
.
-
-
Anthony Petrillo about 2 yearsThe convention is now <app>.<action>_<modelname>. See realpython.com/manage-users-in-django-admin
-
NFSpeedy almost 2 yearsThe zero limits you to check only one group. Also, the calculations in the view have been performed and you are checking too late if the server should perform something. Permissions are a way to even limit the server's overhead.