Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can dynamically create permission in django?

Tags:

python

django

Now I can create new groups using Django group module. from django.contrib.auth.models import Group I can assign permissions to group. For example I created a new group "HR"

by Group(name="HR") .

Now I want to create permissions like

  • can_create_hr
  • can_edit_hr

I should able to assign this permission to other groups.

How can I do it?

like image 927
open source guy Avatar asked Aug 23 '17 06:08

open source guy


People also ask

How do I add permissions to Django?

Add Permissions to Multiple User Types To handle permissions for these different users, you need to create a custom decorator of your own. Now, to use them in the views, all you need to do is call it as you did previously. It should look like this: # views.py from django.

How do I use custom permissions in Django?

Django Admin Panel : In Admin Panel you will see Group in bold letter, Click on that and make 3-different group named level0, level1, level3 . Also, define the custom permissions according to the need. By Programmatically creating a group with permissions: Open python shell using python manage.py shell.

How does permission work in Django?

By default, Django automatically gives add, change, and delete permissions to all models, which allow users with the permissions to perform the associated actions via the admin site. You can define your own permissions to models and grant them to specific users.


1 Answers

You can create and assign permission directly to groups as well. Just create the permission add the permission to group

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

content_type = ContentType.objects.get(app_label='app_name', model='model_name')
permission = Permission.objects.create(codename='can_create_hr',
                                       name='Can create HR',
                                       content_type=content_type) # creating permissions
group = Group.objects.get(name='HR')
group.permissions.add(permission)

If you want to assign this permission to another group then just get the permission object and assign in the same way.

permission = Permission.objects.get(codename='can_create_hr')
group= Group.objects.get(name='some_name')
group.permissions.add(permission)

You can read more about it in docs

like image 105
Arpit Solanki Avatar answered Oct 17 '22 08:10

Arpit Solanki