1

I am currently try to add users automatically to a particular group using signals. It works when I edit the user fields but not when I add a group to it.

@receiver(pre_save, sender=User)
def addToPiloteGroup(sender, instance, *args, **kwargs):
    group = Group.objects.get(name='Pro')
    instance.groups.add(group)          # => doesn't work
    instance.last_name = 'some name'    # => works
    print('user has been group : ' + group.name)
Antoine Grenard
  • 1,712
  • 3
  • 21
  • 41
  • check if it helps https://stackoverflow.com/questions/23795811/django-accessing-manytomany-fields-from-post-save-signal – Vivek Singh Jul 02 '22 at 18:16

1 Answers1

1

I struggled for hours and finally found a solution thanks to this post

def on_transaction_commit(func):
    def inner(*args, **kwargs):
        transaction.on_commit(lambda: func(*args, **kwargs))

    return inner

@receiver(pre_save, sender=User)
@on_transaction_commit
def addToPiloteGroup(sender, instance, *args, **kwargs):
    group = Group.objects.get(name='Pro')
    instance.last_name = 'some name'    # => works now :) !
    print('user has been group : ' + group.name)
Antoine Grenard
  • 1,712
  • 3
  • 21
  • 41