我有一个用户个人资料模型(与User
一对一),如下所示:
class Profile(models.Model):
user = OneToOneField(User, on_delete=models.CASCADE)
facebook_id = CharField(max_length=20, blank=True)
google_id = CharField(max_length=20, blank=True)
def __str__(self):
return self.user.email
# creates a corresponding profile for the newly created user
@receiver(post_save, sender=User)
def user_save(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
,并且我想在创建新用户时设置用户的个人资料,所以类似这样:
user = User(
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
username=validated_data['username'])
user.profile['facebook_id'] = social_id
但这似乎不起作用。正确的方法是什么?
答案 0 :(得分:1)
您正在创建用户模型的未保存实例,因此不会发送post_save
信号。使用:
user = User.objects.create(
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
username=validated_data['username']
)
或:
user = User(
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
username=validated_data['username'])
user.save()
创建User对象后,信号处理程序将创建配置文件,因此您可以设置属性:
user.profile.facebook_id = social_id
user.profile.save()