首页 > 解决方案 > 如何在信号中的模型中传递实例?

问题描述

我有以下模型:

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)

标签: pythondjangosignals

解决方案


推荐阅读