Give users permissions through ForeignKey to a models.Model.

I have the following models, with individual permissions:

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):

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}"

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.

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.

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

First, the permissions are normally defined on the objects being referenced, not on the objects to which they are assigned. (Yes, there are valid cases for defining permissions on those models, so your case may be an exception to this.)

These permissions you are defining are entries in the Permission model.

By default, permissions are assigned to a User or Group, by mean of a ManyToMany relationship between those models and the Permission model.

If you want to assign permissions to Department, then you need to create that ManyToMany relationship with Permission. Each instance of Department can then have some number of Permission associated with it.

When you want to check permissions for a user, you’ll then check to see if the necessary permission is assigned to the User or to the Department to which they are assigned.

While I understand that you can’t use the Group model for this, it would be instructive for you to read the UserManager code in django.contrib.auth.models to understand how Django checks permissions on a user.