I have the following models, with individual permissions:
model.py
class Department(models.Model):
name = models.CharField(max_length=50, blank=False)
class Meta:
permissions = ( ("COFFEEOK", "can use Cofee"),
("THEAOK", "can use Thea"),
("WATEROK", "can use Water"),
)
def __str__(self):
return self.name
class CustomUser(AbstractUser):
department = models.ForeignKey(Department, on_delete=models.CASCADE, blank=True, null=True)
class Meta:
permissions = ( ("MILKOK", "can use Milk"),
("SUGAROK", "can use Sugar"),
)
def __str__(self):
return f"{self.first_name} {self.last_name}"
admin.py
admin.site.register(CustomUser)
admin.site.register(Department)
When I login to the admin site I can add a Department but only the name, I can’t assign any permissions.
If I try to add an user I get a permissions selection box with:
User permissions (among others):
top | custom user | can use Milk
top | custom user | can use Sugar
top | department | can use Coffee
top | department | can use Thea
top | department | can use Water
But I don’t want to assign department permissions to individual users.
Question:
How can I assign permissions to a department and transfer that permission to an user if that user is a member of a department?
e.g. in a template
{{ perms.user_is_member_of_department_with_permission( 'can use Thea' ) }}
or through a decorator
@user_is_member_of_department_with_permission( 'can use Coffee', 'can use Water' )
The idea is that if an user switches department that user gets other permissions or if the department gets more permissions so will all users from that department.
Restriction:
I can’t use the groups
functionality as I’m using that for something else.
Below is a similar question but I don’t quite understand the answer:
Django version 4.2.4