Why user.has_perm print always True?

Viewed 49

A user is assigned to a student group and from the group remove delete_permission, but the below code returns true.

student_group  = Group.objects.get(name='student')

content_type = ContentType.objects.get_for_model(Department)
department_permission = Permission.objects.filter(content_type=content_type)
user = User.objects.get(email='test@gmail.com')
student_group.user_set.add(user)
for perm in department_permission:
    if perm.codename == "delete_department":
        student_group.permissions.remove(perm)
print(user.has_perm("quiz.delete_department"), "Quiz Permission after")
1 Answers

Permissions are cached on the user object see Django documentation. Also refresh_from_db() won't work you need to fetch the user again see this issue.

In your case:

student_group  = Group.objects.get(name='student')

content_type = ContentType.objects.get_for_model(Department)
department_permission = Permission.objects.filter(content_type=content_type)
user = User.objects.get(email='test@gmail.com')
student_group.user_set.add(user)
for perm in department_permission:
    if perm.codename == "delete_department":
        student_group.permissions.remove(perm)

# re-fetch the user from the database after permission change
user = User.objects.get(email='test@gmail.com')

print(user.has_perm("quiz.delete_department"), "Quiz Permission after")
Related