简体   繁体   中英

How to use Django Signals to run a function after user registration completed?

I'm using django_registration_redux package to handle registering new users. Then I have a set of categories, which I want each new user to follow them by default. So I have to run following code immediately after a user object created:

for category in categories:
    f = Follow(user=user.username, category=category)
    f.save()

After reading django Docs, I guessed that adding following method to the UserProfile model would work:

def follow_def_cat(sender, instance, created, **kwargs):
    if created:
        for category in categories:
            f = Follow(user=instance.username, category=category)
            f.save()
    post_save.connect(follow_def_cat, sender=User)

But it seems I couldn't connect saving user signal to the function.

Put your connect instruction out of the signal method.

def follow_def_cat(sender, instance, created, **kwargs):
    if created:
        for category in categories:
            f = Follow(user=instance.username, category=category)
            f.save()

post_save.connetc(follow_def_cat, sender=User)

And remember that follow_def_cat is not a model method, you should create it at the same level that the model class:

class UserProfile(models.Model):

    ...

def follow_def_cat(sender, ...):
    ...

post_save.connect(follow_def_cat, sender=User)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM