【问题标题】:Django template not showing database contentsDjango模板不显示数据库内容
【发布时间】:2012-04-17 14:04:52
【问题描述】:

这肯定是一个新手错误,我已经用谷歌搜索了很多小时,但没有找到可行的解决方案。我假设部分原因是不确定要准确搜索什么。

我正在开发一个小型博客应用程序,我有用户、帖子、博客评论的模型,仅此而已。

我为 blogIndex 和 blogPost 编写了视图,即所有帖子的列表和特定帖子的列表。

blogIndex 在它所属的视图中工作,它显示 {{ post.content }} {{ post.author.firstname }} 等没有问题。

但是 blogPost 不是。视图如下所示:

def blogPost(request, postID):
    blogPost = post.objects.get(id=postID)
    return render_to_response("blog_post.html", {"post":post})

blog_post.html 如下所示:

title: {{ post.title }}</br>
content: {{ post.content }}</br>
datetime: {{ post.datetime }}</br>
author: {{ post.author.first_name }} {{ post.author.last_name }}</br></br>

{% for comment in post.blogcomment_set.all %}
   Comment.firstName: {{comment.firstName}}</br>
   {{comment.lastName}}</br>
   {{comment.email}}</br>
   {{comment.datetime}}</br>
   {{comment.content}}</br>
{% endfor %}

使用 blog_index.html 中的相同代码,我得到了标题、内容等的正确列表。

这是来自 urls.py:

url(r'^blog/$', blogIndex),
url(r'^blog/(?P<postID>\d+)$', blogPost),

我怀疑正则表达式有问题? 我怀疑视图更可能有问题?

这是 blogIndex 的视图,它正在工作,但可能有助于回答:

def blogIndex(request):
    posts = post.objects.all()
    return render_to_response("blog_index.html", {"posts":posts})

这是 blog_index.html 中的代码:

{% for post in posts %}
<h3><a href="/blog/{{ post.id }}">{{ post.title }}</a></h3>
{{ post.content }}
<p>Posted by: {{ post.author.first_name }} {{ post.author.last_name }}<br /> At:    
{{ post.datetime }}</p>     

<p><strong>Comments: </strong><br />
    {% for comment in post.blogcomment_set.all %}
    By: {{ comment.firstname }}<br />
    Title: {{ comment.title }},<br />
    Content: {{ comment.content }}<br />
    Date: {{ comment.datetime }}</p>
    {% endfor %}  
{% endfor %}

链接到可能的解决方案或指出我的目光狭隘都是受欢迎的输入。

【问题讨论】:

    标签: django django-models django-templates django-views django-urls


    【解决方案1】:
    def blogPost(request, postID):
        blogPost = post.objects.get(id=postID)
        return render_to_response("blog_post.html", {"post":post})
    

    应该是:

    def blogPost(request, postID):
        blogPost = post.objects.get(id=postID)
        return render_to_response("blog_post.html", {"post":blogPost})
    

    【讨论】:

    • 作为一般帮助,您可以使用 pprint 过滤器检查传递给模板的数据是否与您认为的相同。例如。 &lt;p&gt;{{post|pprint}}&lt;/p&gt; 在您破解模板和视图时。
    • 谢谢,我知道这很明显。这是一个非常漂亮的技巧!再次感谢。
    • 不要把这种错误放在心上,相信我每个人都会遇到。新鲜的眼睛通常是最好的解决方案,休息后是你的或其他人的。
    • 这就是为什么最好遵循 PEP8 并使用 InitialCaps 作为模型名称,但使用小写作为实例。
    猜你喜欢
    • 2022-11-15
    • 1970-01-01
    • 2015-11-09
    • 2021-03-24
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    相关资源
    最近更新 更多