![](/img/trans.png)
[英]can't access dictionary item using integer keys in django templates
[英]How to access the dictionary keys and values in django templates
我創建了一個動態更新的消息發送者字典。 If I print the dictionary keys in the python console window, I am getting the expected output but when I try to access the values in the Django template, I am getting nothing here is my python code;
視圖.py
def home(request):
senders = {}
chatting =Message.objects.filter(seen=False)
for msg in chatting:
user = User.objects.get(id=msg.sender.id)
if user != request.user and user not in senders.values():
senders.update({user.id : user})
return render(request, 'home.html', senders)
模板首頁.html
<div>
{% for key, val in senders %}
<div>
<a href="#">{{val}}</a>
</div>
{% endfor %}
</div>
首先,你確定你真的需要一個字典嗎? 通常 Django 有一個字典列表。 所以,你只循環列出,就像這里: https://github.com/ansys/aedt-testing/blob/cefebb91675dd54391d6324cd78e7bc97d9a8f6b/aedttest/static/templates/project-report.html#L220
但是,回答一個直接的問題:
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
在 django 的模板中使用以下指令:
{{ 核心價值 }}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.