Django why is a permissions code name different from checking if it has a permission?

Viewed 1387

When adding a permission to a group I use:

managers.permissions.add(
            Permission.objects.get(codename='add_user')
        )

Using the codename add_user

Now when checking if a user has a particular permission, I use users.add_user ie. the app_name prepended

self.assertTrue(self.user.has_perm('users.add_user'))

Why is that. Is it possible to get the permission with users.add_user.

When I try it I get:

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

Model names aren't unique. You could have another User model in a different app. Permission.objects.get(codename='add_user') would fail with a MultipleObjectsReturned in that case. It is therefore safer to use sth like:

Permission.objects.get(codename='add_user', content_type__app_label='users', content_type__model='user')
Related