Marek M.
Marek M.

Reputation: 3951

Adding permissions when user is saved in Django Rest Framework

I'm creating an instance of a User object. The creation itself is a standard User.objects.create_user call and that works ok - user is created. After that, I'm trying to add a few permissions to him or her:

for name in ('view_restaurant', 'change_restaurant', 'delete_restaurant',
             'view_meal', 'add_meal', 'change_meal', 'delete_meal',
             'view_order', 'delete_order',
             'view_historicalorder', 'add_historicalorder', 'change_historicalorder', 
             'view_orderitem',
             'view_historicalorderitem', 
             'view_restaurantemployee', 'add_restaurantemployee', 'change_restaurantemployee', 'delete_restaurantemployee'):
    permission = Permission.objects.get(codename=name)
    print(permission is None)
    user.user_permissions.add(permission)
    user.save()
    print(user.has_perm(permission))

As you can see, in the last line I'm checking whether the user was assigned with an appropriate permission, and few lines above I'm checking if permission is None. The result is that the permission object is never none, but user.has_perm call always returns false. What am I doing wrong here?

Upvotes: 1

Views: 502

Answers (1)

wim
wim

Reputation: 363043

You're calling has_perm incorrectly. It expects a string in this format

"<app label>.<permission codename>"

As an aside, may I recommend to simplify your code like so:

codenames = 'view_restaurant', 'change_restaurant', ...
perms = Permission.objects.filter(codename__in=codenames)
user.user_permissions.add(*perms)

Upvotes: 2

Related Questions