By default each django model has 3 permissions (add, change, delete). In a model I can define my custom permission to adds more.
class Company(models.Model):
owner = models.ForeignKey(User)
name = models.CharField(max_length=64, unique=True)
description = models.TextField(max_length=512)
created_on = models.DateTimeField(auto_now_add=timezone.now)
class Meta:
permissions = (
("erp_view_company", "Can see the company information"),
("erp_edit_company", "Can edit the company information"),
("erp_delete_company", "Can delete the company"),
)
When you migrate, these permissions are automatically created at DB level. How can you retrieve all the permissions from a model?
# retrieves the permissions
permissions = Permission.objects.filter(get_all_permissions_of_model_Company)
# adds permissions to group
group = Group.objects.create(name='foo', permissions=permissions)
# adds user to group
user.groups.add(group)
Add Permissions to a Group If you are using AbstractUser in Django, you must add AUTH_USER_MODEL = 'YourAppName. YourClassName' . This way, you are telling Django to use our custom user model instead of the default one. The code below should go in your admin.py file so that you can see your user model.
through django-adminopen your django-admin page and head to Users section and select your desired user . NOTE: Permission assigning process is a one-time thing, so you dont have to update it every time unless you need to change/re-assign the permissions.
A Django superuser, is its name implies, means it's a user with 'super' permissions. By extension, this means a superuser has access to any page in the Django admin, as well as permissions to Create, Read, Update and Delete any type of model record available in the Django admin.
This view mixin can handle multiple permissions by setting the mandatory permissions attribute as a dict with the keys any and/or all to a list or tuple of permissions. The all key requires the request. user to have all of the specified permissions. The any key requires the request.
I would suggest you something like this:
all_permissions = Permission.objects.filter(content_type__app_label='app label', content_type__model='lower case model name')
Retrieving model's app_label
:
Company._meta.app_label
Retrieving model's lower case name:
Company._meta.model_name
Also, you can retrieve a ContentType
instance representing a model:
ContentType.objects.get_for_model(Company)
Since ContentType
uses a cache, it is quite acceptable. Thus, there is another way to achieve what you need:
content_type = ContentType.objects.get_for_model(Company)
all_permissions = Permission.objects.filter(content_type=content_type)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With