Home > Enterprise >  Create a model object when creating a user in Django, UNIQUE constraint failed
Create a model object when creating a user in Django, UNIQUE constraint failed

Time:04-28

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:

  1. I am getting an django.db.utils.IntegrityError: UNIQUE constraint failed: family_tree_family.name error, how to resolve it?
  2. How to use the **kwargs in user_created function. I create users using curl.

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.

  • Related