78👍
✅
Use add
and remove
methods:
from django.contrib.auth.models import Permission
permission = Permission.objects.get(name='Can view poll')
u.user_permissions.add(permission)
👤alko
27👍
Andrew M. Farrell’s answer is correct. I only add the use of get_user_model() and a full example.
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
u = get_user_model().objects.get(username=new_user_name)
To get the permission you can use
permission = Permission.objects.get(name='Can view poll')
or
permission = Permission.objects.get(codename='can_view_poll')
then add it to the user permissions set
u.user_permissions.add(permission)
- [Django]-Django query filter combining AND and OR with Q objects don't return the expected results
- [Django]-Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object
- [Django]-How can I use Bootstrap with Django?
0👍
Using codename filed:-
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permissio
user = get_user_model().objects.get(name="test")
permission = Permission.objects.get(codename='view_poll')
user.user_permissions.add(permission)
#chack permission
print(user.has_perm("<app_name).view_poll"))
- [Django]-What's the best Django search app?
- [Django]-Query datetime by today's date in Django
- [Django]-Celery: When should you choose Redis as a message broker over RabbitMQ?
Source:stackexchange.com