Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Django turtoring的书第三章中,有{%if-latest_-question_-list%},但我没有_Django - Fatal编程技术网

在Django turtoring的书第三章中,有{%if-latest_-question_-list%},但我没有

在Django turtoring的书第三章中,有{%if-latest_-question_-list%},但我没有,django,Django,在我的index.html页面中,我添加了书中所说的代码。但是最新的问题列表显示为无,我没有看到类似的显示。有人能帮我解决这个问题吗 编辑 index.html {% if latest_question_list %} models.py from django.http import HttpResponse from django.template import loader from .models import Question def index(request): la

在我的index.html页面中,我添加了书中所说的代码。但是
最新的问题列表
显示为无,我没有看到类似的显示。有人能帮我解决这个问题吗

编辑

index.html

{% if latest_question_list %}
models.py

from django.http import HttpResponse
from django.template import loader

from .models import Question


def index(request):
  latest_question_list = Question.objects.order_by('-pub_date')[:5]
  template = loader.get_template('polls/index.html')
  context = {
    'latest_question_list': latest_question_list,
    }
  return HttpResponse(template.render(context, request))
  • 签出模板路径,可能是将数据发送到错误的模板。正如上面所说:

    首先,在polls目录中创建一个名为templates的目录。Django将在那里寻找模板

    项目的模板设置描述Django将如何加载和呈现模板。默认设置文件配置其APP_DIRS选项设置为True的DjangoTemplates后端。按照惯例,DjangoTemplates在每个已安装的应用程序中查找“templates”子目录

    在刚刚创建的templates目录中,创建另一个名为polls的目录,并在其中创建一个名为index.html的文件。换句话说,您的模板应该位于polls/templates/polls/index.html。由于app_目录模板加载器的工作方式如上所述,因此您可以在Django中将此模板简单地称为polls/index.html

  • 您还可以在
    索引
    视图中打印列表,以确保您的
    最新问题列表
    不为空

编辑

  • 因此,正如您所发现的,您在模板中使用的
    上下文
    键名必须与您在视图中创建的键名相同

您是否通过视图传递了它?是的,我将它从视图传递到模板。您是否在本教程的第2部分中创建了问题?您可以尝试通过管理员门户添加它,就像您的代码看起来一切正常一样,在您的管理员中检查确实有一些
问题
我已经检查了管理员,其中有一些项目,我确保它不是空的很多!现在它起作用了,我的错误是我认为在这句话中{上下文:'latest_question_list',latest_question_list}这个名字不重要,所以我改了另一个。结果证明它不起作用。我这样写道:“aaa”,最新的问题列表
from django.http import HttpResponse
from django.template import loader

from .models import Question


def index(request):
  latest_question_list = Question.objects.order_by('-pub_date')[:5]
  template = loader.get_template('polls/index.html')
  context = {
    'latest_question_list': latest_question_list,
    }
  return HttpResponse(template.render(context, request))
from django.db import models


class Question(models.Model):
  question_text = models.CharField(max_length=200)
  pub_date = models.DateTimeField('date published')