django permissions add code example
Example 1: django group with permission
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from api.models import Project
new_group, created = Group.objects.get_or_create(name='new_group')
ct = ContentType.objects.get_for_model(Project)
permission = Permission.objects.create(codename='can_add_project',
name='Can add project',
content_type=ct)
new_group.permissions.add(permission)
Example 2: django user permission check
...
class BlogPost(models.Model):
...
class Meta:
permissions = [('can_write_blog', 'Can Write Blog')]
if request.user.has_perm('app_name.can_write_blog'):
else: