[Fixed]-Django: extend User model with profile onetoonefield errors

1👍

You haven’t allowed team to be null, so when you create a profile like so:

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        # Team isn't defined
        Profile.objects.create(user=instance)

You will get an error.

Allow team to be null (or set a default in the code above):

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    team = models.ForeignKey(Teams, on_delete=models.CASCADE, null=True)

    class Meta:
        app_label = 'my_app'

    def __str__(self):
        return self.name

0👍

When you run

User.objects.create_user(username='test', email='dummyemail@dum.com', password='test')

you get IntegrityError because of post_save signal. It tries to create a Profile instance but in Profile model team cannot be NULL. By default, model fields have null=False.

When you run

user = User.objects.create_user(username='test', email='dummyemail@dum.com', 
    password='test', team='developer')

you get error because team is a field in Profile model, not User model.

When you run

user = User.objects.create_user(username='test', email='dummyemail@dum.com', 
    password='test', profile.team='developer')

you get error because you cannot use . to refer attributes. You need to use __ to filter on foreign key properties. See this question for example. However, even if you use __, it will still give error because their is no field named profile in User model.

One more thing I would suggest is to combine both post_save signals into one because both have same sender.

0👍

See the documentation about ForeignKey.related_name. By default, OneToOneField have related name to join one model to an ohter, but ForeignKey don’t. Just have this option and you can do user.team to access to the model related.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    team = models.ForeignKey(Teams, 
                             on_delete=models.CASCADE,
                             related_name='team',
                             null=True)

Leave a comment