django - 如何使用 UserProfile 扩展 Django 身份验证模型 User,避免相关ObjectDoesNotExist 错误?

标签 django django-models django-auth-models

我正在尝试通过扩展默认的 django 用户来创建 UserProfile 模式。无法保存附加值,因为用户没有用户配置文件: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

最佳答案

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

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

关于django - 如何使用 UserProfile 扩展 Django 身份验证模型 User,避免相关ObjectDoesNotExist 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41741597/

相关文章:

python - makemigrations 没有检测到新模型

Django 授权 : How are many-to-many relationship models created?

Django 1.8 : When items are related via two separate relationships, 如何指定要使用的关系?

python - Django 教程 pub_date__year 过滤器有效,而 pub_date__second 过滤器无效

python - Celery v4 没有按预期路由任务

django - 在 django 中安装 pandas

python - 如何在 Django 中拥有多个 AUTH_USER_MODEL

Django 用户模型覆盖

python - django 1.3 - 无法注册我的自定义 UserAdmin

python - 如何在 Django 中使用内联表单集删除模型对象