0

I have a User model with role field. I want each user to be in one Group that corresponds to their role.

So I try to set their group everytime user is saved. The problem is that user is not in any group after save.

The important part of User model

...
role = models.CharField('Rola', max_length=32, choices=RoleChoices.choices, null=True, blank=True
                        )

def save(self, *args, **kwargs):
    self._set_role_stuff()
    super().save()
    self._set_group()
    pass

def _set_role_stuff(self):
    if self.role and not self.role == RoleChoices.CLIENT:
        self.is_staff = True
    else:
        self.is_staff = False

def _set_group(self):
    self.groups.clear()

    group = Group.objects.get(name='Fotograf')
    self.groups.add(group)

How can I make it work?

Milano
  • 18,048
  • 37
  • 153
  • 353
  • What is `getattr(GroupManager, self.role)` supposed to do? How does that work? – Willem Van Onsem Jan 22 '22 at 19:50
  • That's a singleton class that helps me to manipulate with pre-defined groups. For example, I can get a group by a role name. It's tested - I see that the group exists at the time in the debugger so the problem is probably somewhere else. – Milano Jan 22 '22 at 19:51
  • are you sure `self.role` has truthiness `True` (is not `None`/`NULL` and not the empty string)? – Willem Van Onsem Jan 22 '22 at 19:52
  • I'm sure. But to make it simpler, I've changed now the method (see the code please) and saved user... no group in groups... – Milano Jan 22 '22 at 19:55
  • @WillemVanOnsem Ok, so it works if User is saved programmatically but it doesn't work when saving client in Admin change page. – Milano Jan 22 '22 at 20:17
  • well some ways to update a record circumvent the `.save()` method, for example `User.objects.filter(pk=some_pk).update(role='other role')`, will never trigger the `.save()` method for the record(s) that are updated. – Willem Van Onsem Jan 22 '22 at 20:18

1 Answers1

0

The problem you are having is that you are adding the group to the user, instead of doing it the other way around (add the user to the group).

This was solved by @juankysmith like so:

from django.contrib.auth.models import Group
group = Group.objects.get(name='Fotograf') 
group.user_set.add(self.user)

see the original answer here:

https://stackoverflow.com/a/6288863/6417220