用户注册完成后如何使用 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 文档后,我猜想将以下方法添加到 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:

相同的级别创建它
class UserProfile(models.Model):

    ...

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

post_save.connect(follow_def_cat, sender=User)