42

Django 1.5, python 2.6

The model automatically creates a user under certain conditions:

User.objects.get_or_create(username=new_user_name, is_staff=True) 
u = User.objects.get(username=new_user_name)
u.set_password('temporary')

In addition to setting the username, password, and is_staff status, I would like to set the user's permissions - something like:

u.user_permissions('Can view poll')

or

u.set_permissions('Can change poll')

Is this possible? Thank you!

3 Answers 3

77

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)
1
  • 3
    Better to use codename than name to get the Permission Jan 29, 2022 at 10:07
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)
1
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"))

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.