How To Add Permissions In Django To Models And Test It Using The Shell
Solution 1:
In the example you gave, I would expect emp.has_perm('myappname.is_member') to indeed be False. Unless you explicitly give the new Employer object the is_member permission, it won't have it.
To programmatically give it the permission you need to get the actual permission object and add it to the Employer's user_permissions:
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get_for_model(Employer)
permission = Permission.objects.get(content_type=content_type, codename='is_member')
emp = Employer.objects.create(blablabla)
emp.save()
emp.user_permissions.add(permission)
To test it in the shell, you may need to delete the permission cache that is created for each user- otherwise has_perm may not reflect the actual permissions:
delattr(emp, '_perm_cache')
Responding to your questions:
If you want every single Employer to have the is_member permission there are a few options:
Override the
savemethod ofEmployerto check if there is noself.pk(which means it is a new object, and create the permission as I showed above after saving. Not very pretty, but it would work.Write your own authentication backend. If the permission code is
'is_member'and theUserhas anEmployerinstance, returnTrueDon't use permissions. The permission system is designed for you to be able to dynamically grant and revoke permissions. If you only care whether a
Useris anEmployer- then test for that. Don't complicate it by using permissions.
Post a Comment for "How To Add Permissions In Django To Models And Test It Using The Shell"