我有一个与django.contrib.auth.models auth具有OnetoOne关系的模型。
当我创建一个用户模型时,我向与该用户相关的配置文件模型发送信号。然后创建了配置文件对象,但我无法弄清楚如何填充配置文件对象的其他字段。例如
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
有人可以帮助我吗?我如何在表格上填写这些生物,地点和birth_date?
感谢。
编辑..
我找到了一个解决方案..不知道它是否是最好的praticies ..在forms.py中覆盖save()
def save(self, commit=True):
# Save the provided password in hashed format
user = super(RegisterForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.save()
user.profile.location= self.cleaned_data["location"]
user.profile.save()
return user