【问题标题】:django cannot view database items in templatedjango 无法查看模板中的数据库项目
【发布时间】:2020-05-02 00:57:20
【问题描述】:

我有数据插入到我的数据库中,但无法查看这些项目。我可以看到<ul> 索引,但没有数据。

$ python3 manage.py shell
Python 3.7.3 (default, Dec 20 2019, 18:57:59) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from userdash.models import AssetList
>>> ls = AssetList.objects.get(id=2)
>>> ls
<AssetList: Mike's List>
>>> ls.items_set.all()
<QuerySet [<Items: Batcoin>, <Items: Drum set>, <Items: Dildo>, <Items: Koodie>]>
>>> ls.items_set.create(user_asset="5th Item", sell_asset=False)

在 userdash/templates/userdash/list.html 中

{% extends 'userdash/base.html' %}

{% block title %}
<h1>List Page</h1>

{% endblock %}



{% block content %}

        <h2>{{ls.name}}</h2>


        <ul>
                {% for item in ls.items_set.all %}
                        <li>{{items.user_asset}}</li>
                {% endfor %}
        </ul>
{% endblock %}

在 exchange2/userdash/models.py 中

from django.db import models

# Create your models here.

class AssetList(models.Model):
        name = models.CharField(max_length=200)

        def __str__(self):
                return self.name

class Items(models.Model):
        currencylist = models.ForeignKey(AssetList, on_delete=models.CASCADE)
        user_asset = models.CharField(max_length=300)
        sell_asset = models.BooleanField()

        def __str__(self):
                return self.user_asset

输出:

html output

ul 输出表明数据存在,但没有显示。

如何在 django 模板中正确显示我的数据库查询?

【问题讨论】:

    标签: python django django-forms django-templates


    【解决方案1】:

    {% for item in ls.items_set.all %} 中,循环变量被命名为item,而不是items

    替换

    <li>{{items.user_asset}}</li>
    

    <li>{{item.user_asset}}</li>
    

    【讨论】:

      【解决方案2】:

      您使用变量item 循环遍历ls.items_set.all,但在下一行中您使用名称items(注意复数/单数)。

      尝试将您的代码更改为:

                  {% for item in ls.items_set.all %}
                          <li>{{item.user_asset}}</li>
                  {% endfor %}
      

      【讨论】:

        猜你喜欢
        • 2020-01-22
        • 2022-07-06
        • 2015-12-28
        • 1970-01-01
        • 2020-02-08
        • 2014-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多