Search code examples
djangodjango-modelsdjango-auth-models

How to extend Django auth model User with UserProfile, avoiding RelatedObjectDoesNotExist error?


I am trying to create UserProfile modal by extending default django User. Additional value cannot be saved because User has no user profile:RelatedObjectDoesNotExist:

    user = User.objects.create_user(username=username, password=password)
    user.save()
    print(fb_id)
    user.userprofile.fb_id = fb_id
    user.userprofile.save()

modal :

class UserProfile(models.Model):
   user = models.OneToOneField(User)
   fb_id = models.BigIntegerField(null=True, blank=True, default=0)
   follows = models.ManyToManyField('self', related_name='followed_by', symmetrical=False)

Can't understand why it's wrong and how to do in the right way? Django 1.8


Solution

  • You can't access user.user_profile until you have created it. You could do:

    user = User.objects.create_user(username=username, password=password)
    userprofile = UserProfile.objects.create(user=user, fb_id=fb_id)