【问题标题】:Django: List items in database not displaying on the html templateDjango:列出数据库中的项目未显示在 html 模板上
【发布时间】:2019-04-25 09:33:11
【问题描述】:

作为 Django 项目的一部分,我有以下代码(html 模板)和 views.py 文件,但是当我运行服务器时,数据库中的项目没有显示在浏览器中。它只是显示一个包含 三个项目 的空列表。

我在数据库中肯定至少有三个项目,如下所示:

>>> from worldguestbook.models import GuestBookItem
>>> GuestBookItem.objects.all()
<QuerySet [<GuestBookItem: GuestBookItem object (1)>, <GuestBookItem: GuestBookItem object (2)>, <GuestBookItem: GuestBookItem object (3)>]>
>>>

html文件代码(这显示了html模板代码的底部。会不会是html排列方式的错误?)

       <div id="mce-responses" class="clear">
            <div class="response" id="mce-error-response" style="display:none"></div>
            <div class="response" id="mce-success-response" style="display:none"></div>
          </div>

          <div class="" style="position: absolute; left: -5000px;"><input type="text" name="b_410ed4e009d15301d90f6492b_753384883a" value=""></div>
        </form>
        <span class="form_nospam">Warning: The world will see your message</span>
      </div>
      <!--End mc_embed_signup-->
    </div>
  </div>
  <!-- /end of Row-->
</div>
<!-- End of container-->
<ul>
    {% for guestbookitem in all_items %}
        <li> {{ GuestBookItem.content }} </li>
    {% endfor %}
</ul>
</body>
</html>

views.py 代码

from django.shortcuts import render 

from django.http import HttpResponse
from .models import GuestBookItem


# Create your views here.
def worldguestbookView(request):
    allguestbookitems=GuestBookItem.objects.all()
    return render(request, 'worldguestbook\worldguestbook.html',{'all_items' : allguestbookitems})

def loginView(request):
    return render(request, 'worldguestbook\login.html')

models.py

from django.db import models

# Create your models here.

class GuestBookItem(models.Model):
    content=models.TextField()

注意:服务器在运行时不会抛出任何异常/错误,所以我发现很难解决。

【问题讨论】:

  • 试试{{ guestbookitem.content }}(Django 变量区分大小写)。
  • @EndreBoth - 成功了!谢谢!
  • 从它上面的行:for guestbookitem....
  • 不相关,但您应该在模板路径中使用正斜杠:'worldguestbook/worldguestbook.html'
  • @DanielRoseman - 你能解释一下原因吗?这似乎可行....如果我没记错的话,正斜杠会以某种方式导致错误。

标签: django database templates view rendering


【解决方案1】:

您应该将&lt;li&gt; {{ GuestBookItem.content }} &lt;/li&gt; 替换为&lt;li&gt; {{ guestbookitem.content }} &lt;/li&gt;

【讨论】:

    猜你喜欢
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 2021-04-21
    相关资源
    最近更新 更多