如何在信号内的模型中传递实例?

时间:2019-05-15 16:36:17

标签: python django signals

我有以下模型:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    education = models.CharField(blank=True, null=True, max_length=255)
    country = models.CharField(blank=True, null=True, max_length=255)
    facebook = models.CharField(blank=True, null=True, max_length=255)
    whatsapp = models.CharField(blank=True, null=True, max_length=255)
    description = models.TextField(blank=True)

我正在创建一个信号,保存用户后,它会创建一个与此相关的配置文件,以下代码是我的信号。我不知道如何在instance中传递Profile.objects.create。我想像instance.educationinstance.country ...这样的传递实例是错误的,或者此信号中还有其他错误,因为我收到了此错误User has no profile。请帮我解决它,谢谢

signals.py

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    print("INSTANCE BELOW:")
    print(instance)
    if created:
        Profile.objects.create(user=instance, education=instance.education,
                               country=instance.country, facebook=instance.facebook,
                               whatsapp=instance.whatsapp, description=instance.description)

0 个答案:

没有答案