I have this model:
class Family(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=255, unique=False)
def __str__(self):
return self.name
class Meta:
ordering = ['name']
And I am also using this function to create a family object when a user is created:
@receiver(models.signals.post_save, sender=User)
def user_created(sender, instance, created, **kwargs):
if created:
Family.objects.create(user=instance)
I have a couple questions:
- I am getting an
django.db.utils.IntegrityError: UNIQUE constraint failed: family_tree_family.name
error, how to resolve it? - How to use the
**kwargs
inuser_created
function. I create users usingcurl
.
CodePudding user response:
In user_created try adding instance.family.save() after Family.objects.create(user=instance)
@receiver(models.signals.post_save, sender=User)
def user_created(sender, instance, created, **kwargs):
if created:
Family.objects.create(user=instance)
instance.family.save()
and try changing user field in family class if that does not work.
user = models.OneToOneField(User, on_delete=models.CASCADE)
Hopefully that helps.
CodePudding user response:
First, thanks to everyone who helped out.
I managed to figure the problem, and it was that the field name
in family
model must also be unique. Even if unique=False
attribute was used. Therefore, the answer is to automatically create a unique name
that does not exist before. Hence, I used instance.username
since this value must always be unique:
@receiver(models.signals.post_save, sender=User)
def user_created(sender, instance, created, **kwargs):
if created:
Family.objects.create(user=instance, name=instance.username)
I would like to have a better alternative other than instance.username
. Maybe if I could use **kwargs
somehow.