Set user permission via python

67 views
Skip to first unread message

ma...@anthemdisplays.com

unread,
Apr 9, 2019, 11:25:09 PM4/9/19
to Django users
Hi,

I'm trying to set a permission for a user that I'm creating with a python script. I've tested and found that the codename for the permission is "display_data.settings" using the following:

python manage.py shell
from django.contrib.auth.models import User
user_name = User.objects.get(username="user_name")
user_name.get_all_permissions()
set([u'display_data.settings']) 

I'm trying to set this permission for the user with the following:

from django.contrib.auth import get_user_model
from django.contrib.auth.models import User, Permission

User = get_user_model()

#check to see if user exists, create it if it doesn't
User.objects.filter(username="user_name").exists() or\
    User.objects.create_user(username='user_name', email='user...@example.com', password='blah')
 
#add permissions to user
u = User.objects.get(username="user_name")
permission = Permission.objects.get(name='display_data.settings')
u.user_permissions.add(permission)
 
When I run this, I get the following error:

django.contrib.auth.models.DoesNotExist: Permission matching query does not exist.

Can anybody tell me what I'm missing? 

Matt Collins

unread,
Apr 10, 2019, 10:41:49 AM4/10/19
to Django users
I've solved this. First of all, the codename for the permission should be called as a codename and second, I had to remove the app name (display_data) like this:

permission = Permission.objects.get(codename='settings')

Nelson Varela

unread,
Apr 11, 2019, 10:18:33 AM4/11/19
to Django users
Glad you've found the solution. 
One thing I wanted to advice you is to use the get_or_create method on User.
For more detail check the django documentation.
So:
u, created = User.objects.get_or_create(username="user_name", defaults={email='user...@example.com', password='blah'})

Nelson Varela

unread,
Apr 11, 2019, 10:21:03 AM4/11/19
to Django users
Correction:

u, created = User.objects.get_or_create(username="user_name", defaults={'email': 'user...@example.com', 'password': 'blah'})


Reply all
Reply to author
Forward
0 new messages