开发者

Django user-profile creation code is running twice - why?

开发者 https://www.devze.com 2023-02-25 03:57 出处:网络
Using Django 1.2, I\'m running the django-registration application, and creating a User Profile object after registration created the user - using code that came from some other Questions:

Using Django 1.2, I'm running the django-registration application, and creating a User Profile object after registration created the user - using code that came from some other Questions:

# models.py
def create_player_profile(sender, instance, created, **kwargs):
    signals.post_save.disconnect(create_player_profile, sender = User) # added.
    if created:
        print "creating profile."
        profile, created = PlayerProfile.objects.get_or_create(user = instance)
        print "profile %s created = %s" %开发者_运维技巧 (str(profile), str(created))
    else:
        print "problems creating profile."

signals.post_save.connect(create_player_profile, sender = User)

And it works fine :) The only problem is, I get two sets of output, indicating that the code is running twice. I suspect that for some reason, the signal is getting sent twice.

My first thought is that the file is getting imported twice, setting up two identical signals. Which makes me wonder if maybe django-registration is doing something automatically? Or something else I don't yet understand about Django. :)

So why is the code running twice? Are two signals being sent, and if so, why?

Update Just noticed this Answer explained how to avoid duplicate signals. And it worked, somewhat :) My output went from:

creating profile.

creating profile.

problems creating profile

problems creating profile

to:

creating profile.

problems creating profile

I don't know if that means my code was originally running four times? And dropped down to only two times? I'm so confused. :)

Update 2 - added the signals.disconnect line. I figured deleting the signal would prevent the function from executing twice. Alas, I was wrong - create-player-profile is still running twice... I have no clue why it would, if the signal was immediately deleted.


Update: removed this stuff about AUTH_PROFILE_MODULE

So why is the code running twice? Are two signals being sent, and if so, why?

I guess the problem is not that the signal is called twice, but your User.save() method is called twice somewhere (and therefore the signal as well). Maybe you should check this one first.


It can also happen if the module has bad indentation, if you might have mixed up space and tab indents in the create_player_profile function then also this can happen.

0

精彩评论

暂无评论...
验证码 换一张
取 消