get_object_or_404()的第一个参数必须是Model,Manager或QuerySet,而不是“ function”

时间:2019-06-08 12:16:45

标签: python django

我试图基于数据库中的user_id显示一些数据,但是它一直在显示此ValueError。谁能帮助我找出我做错了什么?

这是我的views.py

from django.shortcuts import render, get_object_or_404
from .models import user

def index(request):
    return render(request, 'pages/index.html')

def user(request, user_id):
    profile = get_object_or_404(user, pk=user_id)
    context = {
        'profile' : profile
    }
    return render(request, 'user/user.html', context)

1 个答案:

答案 0 :(得分:1)

由于您定义了名为<?php $string = "https://bitebtc.com/api/v1/market"; $decoded = file_get_contents($string); $percent = $decoded->percent; echo $percent; As you can see in the link, the expected output would be something like 1.3 or at least a floating number between 0 and 10, but I got nothing, or a php notice: Trying to get property of non-object; since it is not an error I guess the problem doesn't come from the non-object property thing... 的函数,因此此处覆盖了对user模型的引用。

您可以在导入中使用别名,例如:

user

话虽如此,根据PEP-8 style guidelines,类的名称应写在from django.shortcuts import render, get_object_or_404 from .models import user as UserModel def index(request): return render(request, 'pages/index.html') def user(request, user_id): profile = get_object_or_404(UserModel, pk=user_id) context = { 'profile' : profile } return render(request, 'user/user.html', context)中,函数的名称应写在CamelCase中。因此,如果符合这些准则,则应将lowercase_separated_by_underscores模型重命名为user

由于Django已经有一个名为User [Django-doc]的模型(在User中),因此您可能想要重命名为django.contrib.auth