我目前正在尝试使用信号自动将用户添加到特定组。当我编辑用户字段时,它工作,但当我向它添加组时,它不起作用。
@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)
我挣扎了几个小时,终于找到了一个解决方案,感谢这篇文章
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)