[Django]-Django: get_perm(permision_string)

10👍

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)

3👍

There is a third party app which supplies a method which perm_to_permission(perm):

http://django-permission.readthedocs.io/en/latest/_modules/permission/utils/permissions.html

def perm_to_permission(perm):
    """
    Convert a identifier string permission format in 'app_label.codename'
    (teremd as *perm*) to a django permission instance.

    Examples
    --------
    >>> permission = perm_to_permission('auth.add_user')
    >>> permission.content_type.app_label == 'auth'
    True
    >>> permission.codename == 'add_user'
    True
    """
    try:
        app_label, codename = perm.split('.', 1)
    except IndexError:
        raise AttributeError(
                "The format of identifier string permission (perm) is wrong. "
                "It should be in 'app_label.codename'."
            )
    else:
        permission = Permission.objects.get(
                content_type__app_label=app_label,
                codename=codename
            )
        return permission

Leave a comment