【问题标题】:Django Template not displaying model dataDjango模板不显示模型数据
【发布时间】: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


【解决方案1】:

你没有添加RequestContext,你的return语句应该看起来像>>

return render_to_response('index.html', {'entries': entries}, RequestContext(request))

别忘了导入 RequestContext >> from django.template import RequestContext

【讨论】:

    猜你喜欢
    • 2016-10-15
    • 2017-02-15
    • 1970-01-01
    • 2013-08-22
    • 2018-08-29
    • 2021-02-14
    • 2016-05-06
    • 1970-01-01
    相关资源
    最近更新 更多