Search code examples
djangodjango-permissions

Django custom permission not being assigned to newly created User


This seems pretty trivial but I can't figure out what I'm doing wrong. I've checked several SO posts that sounded similar but the issue apparently lies elsewhere.

I have a custom permission on my model, can_key, and this is registered properly. When I try to add this permission to a newly created user, it's not added.

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

def create_dummy_user(self, username):

  username = 'dummy_user'

  user = get_user_model().objects.create(username=username, password='asdf4321')
  user.save()

  user = get_user_model().objects.get(username=username)
  permission = Permission.objects.get(codename="can_key")

  print(permission)
  
  user.user_permissions.add(permission)

  user = get_user_model().objects.get(username=username)
  print(f"{user.username} is_active - {user.is_active}")
  print(f"{user.username} has perm {permission.codename} - {user.has_perm(permission)}")

  return user

This is the print outputs

test_web | main_app | record case | Can key record case
test_web | dummy_user is_active - True
test_web | dummy_user has perm can_key - False

So the user was created and the permission exists / is retrieved, but the permission isn't being added. Why?


Solution

  • You should change the parameter of has_perm() function with string. It's format is "app_name.codename". So you change the code like below

    ...
    print(f"{user.username} has perm {permission.codename} - {user.has_perm('main_app.can_key')}")
    ...
    

    You should review Django's permission caching documentation. click to answer of your question