【发布时间】:2013-02-17 22:35:12
【问题描述】:
我浏览了不同的教程和 Stack Overflow 问题,但我不确定为什么我仍然遇到这个问题:
我在将模型数据显示到我的模板时遇到了问题,我可以看到 python 代码正在执行,但无论我尝试了什么,我都无法让我的数据通过我的相关代码sn-ps 如下:
models.py
class GoogleData(models.Model):
placeID = models.CharField(max_length=999)
name = models.CharField(max_length=200)
phoneNumber = models.CharField(max_length=800)
busAddress = models.CharField(max_length=2000)
openinghours = models.CharField(max_length=9999)
Views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response, render, get_object_or_404
from django.template import Context, loader
from hoursofDEV.models import GoogleData
def home(request):
entries = GoogleData.objects.all()[:5]
return render_to_response('index.html', {'entries': entries,})
index.html
{% if entries %}
<ul>
{% for GoogleData in entries %}
<li><a href="/GoogleData/{{ GoogleData.name }}/">{{ GoogleData.name }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>Where's the Data?.</p>
{% endif %}
使用我显示的代码,我经常看到我的其他“数据在哪里?”,我在 GoogleData 中有数百行,但我无法让它们中的任何一行显示在 html 页面上
任何指导或指出我的新手错误都会非常有帮助。
谢谢!
【问题讨论】:
-
你能把你的
urls.py也包括进来吗?您应该尝试打印entries变量,看看您是否确实有一个有效的查询集被传递给模板。您还应该安装 django-debug-toolbar 因为您可以检查传递给模板的变量 -
您是否尝试过例如模板中的 {{entries|length}} ?它返回什么?如果为零,则您的模型无效。
-
试试 -> return render(request, 'index.html', {'entries' : entries},) -> 而不是 render_to_response
标签: django django-models django-templates django-views