【问题标题】:Django - How do I display data from a dictionary from views to html fileDjango - 如何显示从视图到 html 文件的字典中的数据
【发布时间】:2021-08-04 14:49:17
【问题描述】:

我的 views.py 中有一本字典,其设置如下:

def dctFormat(request):
    dct = {}
    dct1 = {}
    for data in MapData.objects.all().iterator():
        dct[data.User_Number] = dct1
        dct1["First_Name"] = data.First_Name
        dct1["Account_or_Gift"] = data.Account_or_Gift
        dct1["Child_Name"] = data.Child_Name
    return render(request, 'datamap.html', context=dct)

在 model.py 中,MapData 模型如下所示:

class MapData(models.Model): # name of the table
    AccountType = models.TextChoices('AccountType', 'Account Gift')
    UserType = models.TextChoices('UserType', 'User Customer')

    User_Number = models.IntegerField()
    User_or_Customer = models.CharField(max_length=8, choices=UserType.choices)
    First_Name = models.CharField(max_length=30);
    Child_Relationship_With_Gift = models.CharField(max_length=20)
    Child_Name = models.CharField(max_length=20)
    Account_or_Gift = models.CharField(max_length=10, choices=AccountType.choices)
    Occasion_or_Purpose = models.TextField()
    City_State = models.CharField(max_length=30)

如何在我的 HTML 文件前端的 views.py 中显示字典?我看过一些论坛,但没有一个真正有帮助。基本上字典应该是这样的:

{'1': {'First_Name': 'Paula', 'Child_Name': 'Ari', 'Account_or_Gift': 'Gift'},
'2': {'First_Name': 'Jake', 'Child_Name': 'Luke', 'Account_or_Gift': 'Account'}...}

所以当我调用字典时,它会根据相应的数字显示数据。这是我尝试过的:

{% for mapdata in dct %}
  <p>{{ mapdata.User_Number}}</p>
{% endfor %}

【问题讨论】:

  • 您的视图应该以 HTML 中显示的方式准备数据。您会发现很难/不可能设置一些变量并使用它来查找您的字典。如果你想列出整个字典,你可以使用循环来做到这一点。 docs.djangoproject.com/en/3.2/ref/templates/builtins/#for
  • @redunderthebed 当我从终端中的 views.py 打印字典时,它准确地展示了我想要的内容,现在我只是如何在 HTML 文件中显示该数据。我不认为你提供的链接真的有帮助
  • 哦,我没有注意到你提供的模板代码,也不明白你在做什么,我的错。

标签: python django django-views django-templates


【解决方案1】:

在将dct 设为context 中的关键字之前,您不能对其进行迭代。

你可以解决这个问题

    context = {'dct': dct}
    return render(request, "datamap.html", context)

在你的模板中:

  {% for user_number, mapdata in dct.items %}
    {{ user_number }}
    {{ mapdata.First_Name }}
  {% endfor %}

【讨论】:

  • 是的,我刚刚想通了,数字是“User_Number”,mapdata 只会包含 First_Name、Account_or_Gift 和 Child_Name
猜你喜欢
  • 2011-05-17
  • 1970-01-01
  • 2019-04-07
  • 2022-11-02
  • 2019-03-12
  • 2012-07-31
  • 2019-11-28
  • 2020-02-04
  • 1970-01-01
相关资源
最近更新 更多