Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - set user permissions when user is automatically created using get_or_create

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!

like image 667
billrichards Avatar asked Dec 03 '13 20:12

billrichards


People also ask

How do I give permission to user in Django?

If you have a set number of user types, you can create each user type as a group and give the necessary permissions to the group. Then, for every user that is added into the system and into the required group, the permissions are automatically granted to each user.

Which is Django's inbuilt user authentication application?

'django. contrib. auth' contains the core of the authentication framework, and its default models.

What is user Is_active in Django?

If is_active is True (default), returns only active users, or if False , returns only inactive users. Use None to return all users irrespective of active state.


2 Answers

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) 
like image 187
alko Avatar answered Oct 16 '22 09:10

alko


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().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) 
like image 43
juanmhidalgo Avatar answered Oct 16 '22 10:10

juanmhidalgo