2

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

ivanleoncz
  • 9,070
  • 7
  • 57
  • 49

1 Answers1

2

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)
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • I've seen alot of bad answers all over the internet and this one, for me, actually answers the question and resolves the problem. I think the extending the user model needs to be a part of the django standard tutorial because it is allegedly so easy but I know I've sunk about 2 days into it, I have some working code, but I don't really understand what's going on. –  Aug 16 '17 at 04:26