0

我使用django_registration_redux包來處理註冊新用戶。然後我有一組類別,我希望每個新用戶默認都遵循這些類別。所以,我必須運行一個用戶對象創建後立即下面的代碼:如何使用Django Signals在用戶註冊完成後運行一個函數?

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

閱讀Django文檔後,我猜,添加下面的方法到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) 

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

+1

那是你的實際縮進:

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不是模型方法,你應該在同一水平,模型類中創建呢? – Alasdair

+1

post_save.connect中的拼寫錯誤 –

+0

我已更正了錯字,但由縮進導致的問題。 – sheshkovsky

回答

1

將您的連接指令置於信號方法之外。

class UserProfile(models.Model): 

    ... 

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

post_save.connect(follow_def_cat, sender=User) 
相關問題