In Django, when I call User.objects.create_user(username, email, password) - why does post_save get called twice?

倖福魔咒の 提交于 2019-12-06 11:42:22

It is possible that your models.py file is being imported, and run, twice. In this case, the same signal handler would be attached twice, and would fire twice when a model instance is saved.

This can easily happen if you import it once as

import myapp.models

and again as

import myproject.myapp.models

Printing something to the console at the top of the file might give you an idea whether that is what is happening or not.

Regardless, you can prevent a signal handler from being registered multiple times by giving it a unique dispatch_uid. Django will check on Signal.connect to see if a handler has already been registered for the same sender with the same UID, and will not re-register it if it has.

Change your signal connecting code to something like

post_save.connect(create_user_profile, sender=User, dispatch_uid='create_user_profile')

and see if that helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!