[英]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. 我正在使用django_registration_redux软件包来处理注册新用户。 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: 阅读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)
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: 请记住, 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.