'Check if user has a permission with specific codename in django

I am trying to check if a user has a permission, which I have defined in the class Meta of the model, with a specific codename. At the moment I have:

if request.user.has_perm('app_label.code_name'):
    do something

What I am trying to avoid is using the app_label, however using has_perm('code_name') does not seem to work.



Solution 1:[1]

The way this function works is that you need to pass the app_label, so not much you can do there.

One workaround can be to write your own wrapper function, something like:

def _has_perm(user, code_name, app_label="app_label"):
    return user.has_perm(app_label + "." + code_name)

Solution 2:[2]

The reason you need to provide the app label is that permissions are application specific. That means if you have two apps, app_a and app_b, both with a model named Farm, they could both have a permission called can_create_new_chickens. It is very important to understand that there are two separate permissions here:

  • app_a.farm.can_create_new_chickens
  • app_b.farm.can_create_new_chickens

These are independent permissions, and a user can have neither, both or one or the other. This means it would be insecure to validate permissions without referring to the application name. Permissions given to a user in one application could affect their permissions in another application.

Back to your question, the answer is no, you cannot check permissions without the application name for the reasons given above.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NS0
Solution 2 JGC