迭代并格式化模板过滤器返回的字典

时间:2019-04-16 19:45:00

标签: python django python-3.x django-templates

我正在尝试在Django应用中显示有关图像的元数据。从图像的exif标头读取元数据,并将图像作为键存储在字典中,然后使用过滤器返回到模板。在我的模板中,我显示图像,并希望显示该图像的格式化元数据。到目前为止,我只能得到它来显示该图像的字典(例如{'key1': 'value', 'key2', 'value'})。我希望它看起来像key1: value, key2: value

#template.html
{% block content %}
    {% for image in images %}
        {{ exif|get_item:image }}
            <p><img src="{{ image.image.url }}" width="500" style="padding-bottom:50px"/></p>
    {% endfor %}
{% endblock %}


#views.py
def image_display(request):
    images = image.objects.all()

    exif = {}
    for file in images:
        cmd = 'exiftool ' + str(file.image.url) + ' -DateTimeOriginal -Artist'
        exifResults = (subprocess.check_output(cmd)).decode('utf8').strip('\r\n')
        exif[file] = dict(map(str.strip, re.split(':\s+', i)) for i in exifResults.strip().splitlines() if i.startswith(''))

    context = {
        'images': images,
        'exif': exif,
    }

    @register.filter
    def get_item(dictionary, key):
        return dictionary.get(key)
    return render(request, 'image_display.html', context=context)

我以为我可以在模板中做{% for key, value in exif|get_item:image.items %},但这会返回错误:

VariableDoesNotExist at /reader/image_display
Failed lookup for key [items] in <image: image1>

有没有办法格式化过滤器返回的字典或对其进行迭代,以便可以格式化每个键和值对?

1 个答案:

答案 0 :(得分:1)

正如我所看到的,您正在使用此问题的自定义过滤器实现:Django template how to look up a dictionary value with a variable,但是您需要采取额外的步骤来格式化特定的键,因为它是字典。

为什么不创建另一个可以返回所需格式的字典的过滤器?
像这样:

@register.filter
def get_item_formatted(dictionary, key):
    tmp_dict = dictionary.get(key, None)
    if tmp_dict and isinstance(tmp_dict, dict):
        return [[t_key, t_value] for t_key, t_value in tmp_dict.items()]
    return None

这将返回[key, value]对或None对的列表。
您可以在模板中进行迭代:

{% block content %}
    {% for image in images %}
        {% for pair in exif|get_item_formatted:image %}
            // Do what you need with the pair.0 (key) and pair.1 (value) here. 
        {% endfor %}
    {% endfor %}
{% endblock %}