【问题标题】:Iterate and format dictionary returned by template filter迭代并格式化模板过滤器返回的字典
【发布时间】:2019-09-06 23:51:42
【问题描述】:

我正在尝试在我的 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>

有没有一种方法可以格式化过滤器返回的字典或遍历它,以便格式化每个键和值对?

【问题讨论】:

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


    【解决方案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 %}
    

    【讨论】:

    • 这听起来是个好主意。不幸的是,我遇到了语法错误:return [[t_key: t_value] for t_key, t_value in tmp_dict.items]: ^ SyntaxError: invalid syntax(箭头指向t_key: 中的冒号)
    • 谢谢!现在它说丢失的冒号有语法错误——tmp_dict.items]:。试过但得到了'builtin_function_or_method' object is not iterable
    • @Bird 我在写这篇文章时做得很草率。抱歉,既然我再次编辑了答案,请再试一次。
    • 感谢您的更新和帮助!仍然收到'builtin_function_or_method' object is not iterable 错误。我想它来自for t_key, t_value in tmp_dict.items。只试过return temp_dict.items 和同样的错误。知道为什么会这样吗?
    • 我想我找到了 - 将 tmp_dict.items 更改为 tmp_dict.items() 似乎可以正常工作。
    猜你喜欢
    • 2014-02-15
    • 2013-08-07
    • 1970-01-01
    • 2018-07-30
    • 2022-11-05
    • 2012-07-27
    • 2012-06-19
    • 2020-08-27
    • 1970-01-01
    相关资源
    最近更新 更多