在Django turtoring的书第三章中,有{%if-latest_-question_-list%},但我没有
在我的index.html页面中,我添加了书中所说的代码。但是在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
{% 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
- 您还可以在
视图中打印列表,以确保您的索引
不为空最新问题列表
- 因此,正如您所发现的,您在模板中使用的
键名必须与您在视图中创建的键名相同上下文
问题
我已经检查了管理员,其中有一些项目,我确保它不是空的很多!现在它起作用了,我的错误是我认为在这句话中{上下文:'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')