【问题标题】:How to extend Django auth model User with UserProfile, avoiding RelatedObjectDoesNotExist error?如何使用 UserProfile 扩展 Django 身份验证模型用户,避免 RelatedObjectDoesNotExist 错误?
【发布时间】:2017-06-04 03:22:33
【问题描述】:

我正在尝试通过扩展默认 django 用户来创建 UserProfile 模式。无法保存附加值,因为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()

模态:

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)

无法理解为什么会出错以及如何以正确的方式进行操作? Django 1.8

【问题讨论】:

标签: django django-models django-auth-models


【解决方案1】:

在创建 user.user_profile 之前,您无法访问它。你可以这样做:

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

【讨论】:

  • 我在互联网上看到了很多不好的答案,对我来说,这个答案实际上回答了问题并解决了问题。我认为扩展用户模型需要成为 django 标准教程的一部分,因为据称它很容易,但我知道我已经投入了大约 2 天,我有一些工作代码,但我真的不明白什么是继续。
猜你喜欢
  • 2020-07-16
  • 2012-01-26
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
  • 2016-07-30
  • 2014-10-16
相关资源
最近更新 更多