Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

django

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.

like image 525
John C Avatar asked Mar 07 '26 05:03

John C


1 Answers

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.

like image 142
Torsten Engelbrecht Avatar answered Mar 08 '26 18:03

Torsten Engelbrecht



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!