如何在视图中引用用户模型

时间:2015-07-13 09:56:36

标签: python django django-models django-views

我根据文档扩展了Django用户模型:https://docs.djangoproject.com/en/1.8/topics/auth/customizing/

models.py:

from django.db import models
from django.contrib.auth.models import User
class Onboarding(models.Model):
    user = models.OneToOneField(User)
    onboarding_status = models.SmallIntegerField(max_length=1, default=1)

views.py:

from django.shortcuts import render
from django.contrib.auth.models import User
from .models import Onboarding

def home(request):
    current_user = request.user
    u = User.objects.get(id=current_user.id)
    onboarding_status = u.onboarding.onboarding_status

    context = {
    }

    if onboarding_status == 1:
        return render(request, "onboarding/step_1.html", context)
    else:
        return render(request, "onboarding/step_2.html", context)

但是,我收到错误RelatedObjectDoesNotExist at /onboarding/User has no onboarding.

如何从视图中准确引用我与用户关联的onboarding_status整数?

2 个答案:

答案 0 :(得分:2)

首先,向用户查询request.user ID是没有意义的。 request.user 已经用户:u的值与您开始使用的current_user值完全相同。

其次,错误告诉您此特定用户没有相关的Onboarding实例。您可能需要创建一个,可能是在您创建用户时。

答案 1 :(得分:0)

您已分配onboarding_status = u.onboarding.onboarding_status,但您的context = {}为空。试试context={'onboarding_status': onboarding_status}。然后在模板文件step_1.htmlstep_2.html中,使用{{ onboarding_status }}来调用变量。