我正在尝试向内置身份验证用户添加新字段。这是我的代码
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth import get_user_model
from django.contrib.postgres.fields import ArrayField
class Profile(models.Model):
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
newField = ArrayField(models.CharField(max_length=16))
@receiver(post_save, sender=get_user_model())
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=get_user_model())
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
在我看来,我有以下内容:
current_user = User.objects.get(username=request.user)
current_user.save()
我得到了错误
Exception Type: RelatedObjectDoesNotExist
Exception Value: User has no profile.
我做错了吗?我在数据库中创建了一个配置文件表,但这似乎不是问题
答案 0 :(得分:1)
可能是因为您正在创建用户并一次触发两个信号功能。所以也许您可以尝试这样:
@receiver(post_save, sender=get_user_model())
def save_user_profile(sender, instance, created, **kwargs):
if not created:
instance.profile.save()
或者更好,将两个信号合并为一个:
@receiver(post_save, sender=get_user_model())
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
else:
instance.profile.save()
答案 1 :(得分:0)
原因是您正在与一个发送方定义两个信号。因此,当用户被保存时,两个信号都将被触发,但是第二个信号更快,并且将立即执行。并且因为没有为该用户创建profile
,所以会引发错误。因为尚未创建该用户的profile
对象(第一个信号)。
@receiver(post_save, sender=get_user_model())
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
注意,无需在此处执行instance.profile.save()
。