Django 1.5 custom user model - signals limitation

末鹿安然 提交于 2019-12-02 09:27:44

That should work. I think they mean to use the same function as sender

in doc:

as the sender or target of a signal handler. Instead, you must register the handler with the resulting User model

It's because the object hasn't been "installed" when the signal is being created so get_user_model() can't find the object that it needs to attach the signal handler.

See this bug for the details on how it was found and what the problem is.

Your example wouldn't work because the get_user_model() call would fail for this reason. For now the only way to make a signal handler work with a custom User class is to name it directly without using get_user_model(), eg

@receiver(post_save, sender=myapp.MyUserModel) # can't use get_user_model() here
def user_saved(sender=None, instance=None, **kwargs):
    # something

Your coding style could also do with some work: when you run User = get_user_model(), that creates a variable called User with its value set to the results of the get_user_model() function call. Python convention (and that of most other languages) is for normal variables to start with a lower-case letter and for classes to start with an upper case letter.

So user = get_user_model() and then using the user variable later on would make much more sense to anyone reading your code and would help to avoid confusion in the future.

You can simply use the setting AUTH_USER_MODEL or any model as a string, e.g. 'users.MyCustomUser':

def user_post_save_handler(**kwargs):
    # do something
post_save.connect(user_post_save_handler, sender=settings.AUTH_USER_MODEL)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!