最近在实现 django 信号量实现保存用户时发生了错误
报错如下:
maximum recursion depth exceeded while calling a Python object
代码如下所示
user/signals.py
@receiver(post_save,sender=User)
def create_user(sender,instance=None,created=False,**kwargs):
if create_user:
password = instance.password
instance.set_password(password)
instance.save()
user/apps.py
class UsersConfig(AppConfig):
name = 'users'
verbose_name = "xx 信息管理"
def ready(self):
import users.signals
出现这个错误的原因是因为 instance.save()触发了信号,然后再次保存,然后一直无限循环下去 …..
解决办法:
@receiver(post_save,sender=User)
def create_user(sender,instance=None,created=False,**kwargs):
if create_user:
# 解决无限递归循环
post_save.disconnect(create_user, sender=sender)
password = instance.password
instance.set_password(password)
instance.save()
post_save.connect(create_user, sender=sender)
使用 post_save.disconnect 断开连接, 然后在 save() 保存后重新连接信号