I have a function to receive a signal when users change their group.
@receiver(signal=m2m_changed, sender=User.groups.through) def save_profile(instance, action, reverse, model, pk_set, using, *args, **kwargs): print(model, instance)
When I change the group of the user with username "test" using the superadmin interface it outputs
<class 'django.contrib.auth.models.Group'> test. But when I do it using following code,
group = Group.objects.get(name='Customer') group.user_set.add(user) user.save()
<class 'django.contrib.auth.models.User'> Customer.
Because of the above issue I cant use
if instance.groups.filter(name='Customer').exists(): #Do something
save_profile funtion. When I change groups using second method it gives
AttributeError at /register/ 'Group' object has no attribute 'groups' error. How can I avoid getting this error?
I couldn't come up with a reason why this happens but I found a solution for it. I added the following lines to identify which situation it is.
if model != Group: userObj = User.objects.filter(id = list(pk_set)).first() else: userObj = instance
Then I used the required logic as
if userObj.groups.filter(name='Customer').exists(): #Do something