Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: get_perm(permision_string)

Since there is User.has_perm(permission_string) I think there should be a get_perm(permission_string) somewhere.

I could not find it in the docs.

How do I get the permission object from a permission string?

For me permission string is something like this: 'myapp.permmission_name'.

like image 810
guettli Avatar asked May 31 '26 01:05

guettli


1 Answers

All permissions are stored in Permissions model and can be gotten like this:

from myapp.models import BlogPost
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType

content_type = ContentType.objects.get_for_model(BlogPost)
permission = Permission.objects.get(codename='can_publish',
                                   content_type=content_type)

https://docs.djangoproject.com/en/1.7/topics/auth/default/#programmatically-creating-permissions

Or if you want get it from string:

from django.contrib.auth.models import Permission
app_label, codename = your_permisssion_string.split('.')
Permission.objects.get(content_type__app_label=app_label, codename=codename)
like image 132
Yevgeniy Shchemelev Avatar answered Jun 02 '26 03:06

Yevgeniy Shchemelev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!