【发布时间】: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