How properly assign permissions when to user when saving model?

I want to assign Permissions to a user when I Change Group inside the Django admin.

I'm adding this permission inside the custom User model in the save method.

When I Save changes in the admin panel, no errors are raised, but permissions are not created in my local DB

Here is how my model looks like

class UserProfile(AbstractUser, PermissionsMixin):
    name = models.CharField(max_length=255, unique=False, default=None)
    email = models.EmailField(max_length=50, unique=True)
    email_verified = models.BooleanField(default=False)
    date_joined = models.DateTimeField(default=timezone.now)
    password = models.CharField(max_length=100, null=False)

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["name"]

    objects = CustomAccountManager()

    def is_member(self, group_name: Roles):
        return self.groups.filter(name=group_name.value).exists()
    
    def save(self, *args, **kwargs):
        if self.is_member(Roles.STAFF):
            permissions = Permission.objects.filter(codename__in=settings.STAFF_PERMISSIONS)
            self.user_permissions.add(*permissions)
            logger.info(f"Permissions {list(permissions)} added for user {self.email}")

        super().save(*args, **kwargs)

For some reason, I can add permissions from CLI when creating a User instance, but not in the save method, what might be wrong here?

Back to Top