简体   繁体   English

在Django模板中访问字典值

[英]Accessing dictionary values in django template

I'm trying to access key value pairs from a dictionary in a Django template, but am facing some issues. 我正在尝试从Django模板中的字典访问键值对,但遇到了一些问题。

The dictionary looks something like this: 字典看起来像这样:

{datetime.datetime(2014, 10, 31, 0, 0, tzinfo=<UTC>): [<Item: do something1>],
datetime.datetime(2014, 10, 24, 0, 0, tzinfo=<UTC>): [<Item: dosomething2>,<Item: dosomething3>]}

Django template: Django模板:

{% if item_list %}
    <ul>
        {{item_list}}
        {% for key, value in item_list %}
            <h3>{{key}}</h3>
            {% for item in value %}
                <input type="checkbox" value="{{item.title}}">{{item.title}}<br>
            {% endfor %}
        {% endfor %}
    </ul>
{% else %}
    <p>No items are available.</p>
{% endif %}

Views.py Views.py

def index(request):
    try:
        item_list = sort_items_by_date()
    except Item.DoesNotExist:
        raise Http404
    return render(request, 'index.html', {'item_list':item_list, 'new_item_form':ItemForm()})

When the template is rendered, none of the items from the dictionary show up. 渲染模板后,词典中的所有项目都不会显示。 I looked up other similar questions here and tried their solutions (eg using item_list.date) but it didn't work. 我在这里查找了其他类似的问题,并尝试了他们的解决方案(例如,使用item_list.date),但没有成功。 I'd really appreciate it if someone could point out what I'm doing wrong here 如果有人可以指出我在做什么错,我将不胜感激

 {% for key, value in item_list %} 

遍历字典会产生密钥。

 {% for key, value in item_list.iteritems %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM