簡體   English   中英

用戶注冊完成后,如何使用Django Signals運行功能?

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

我正在使用django_registration_redux軟件包來處理注冊新用戶。 然后,我有一組類別,默認情況下,我希望每個新用戶都遵循這些類別。 因此,創建用戶對象后,我必須立即運行以下代碼:

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

閱讀django Docs之后,我猜想向UserProfile模型添加以下方法會起作用:

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)

但是似乎我無法將保存用戶信號連接到該功能。

將您的連接指令放在信號方法之外。

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)

請記住, follow_def_cat不是模型方法,您應該在與模型類相同的級別上創建它:

class UserProfile(models.Model):

    ...

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

post_save.connect(follow_def_cat, sender=User)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM