【问题标题】:django loop static files directorydjango循环静态文件目录
【发布时间】:2020-12-11 05:13:54
【问题描述】:

我正在尝试遍历静态/文件夹中的图像。我可以遍历主“静态”文件夹中的图像,但是当我将它们放在“静态/文件夹”中时,我不确定如何在 html 中执行此操作。

我的 html 行(当 img 在主“静态”文件夹中时有效)

{% for file in files %}
    <img src=" {% static file %}" height="800">
    <p>File name:{{ file }}</p>
{% endfor %}

我的意见.py

def album1(request):
    images = '/home/michal/PycharmProjects/Family/gallery/static/'
    files = os.listdir(os.path.join(images))
    context = {'files': files}
    return render(request, 'gallery/album1/main.html', context)

如果我将视图更改为:

def album1(request):
    images = '/home/michal/PycharmProjects/Family/gallery/static/'
    files = os.listdir(os.path.join(images, 'folder'))
    context = {'files': files}
    return render(request, 'gallery/album1/main.html', context)

它按预期循环'static/folder/'中的文件名,但是我不知道如何在html中更改它,因为它将文件名添加到:/static/{{ file}}而不是/static/folder /{{ 文件 }}。 我认为我在这个特定页面上缺少某些东西或需要改变负载静态的东西?

{% load static %}                 # either here 
<img src=" {% static file %}">    # or here?

【问题讨论】:

    标签: python django


    【解决方案1】:

    您在文件名前加上文件夹名称:

    from os.path import join
    
    def album1(request):
        images = '/home/michal/PycharmProjects/Family/gallery/static/'
        files = os.listdir(join(images, 'folder'))
        context = {'files': [join(folder, file) for file in files]}
        return render(request, 'gallery/album1/main.html', context)

    您可以使用|slice template filter [Django-doc] 对模板进行切片:

    {% for file in files|slice:':21' %}
        <img src=" {% static file %}" height="800">
        <p>File name:{{ file }}</p>
    {% endfor %}

    但在视图中执行此操作更有效,因为您可以通过执行更少的join 调用来节省周期,而且模板的效率低于 Python 代码。

    【讨论】:

    • 它有效,但现在我在选择要显示的文件范围时遇到问题。在我能够做到之前:{% for file in files[0:21] %} 但现在我有:“无法解析剩余部分:来自 'files[0:21]' 的 '[0:21]'”。试图找到解决这个问题的方法:)
    • 暂时我通过执行 "{'files': [join(folder, file) for file in files[:21]]}" 对其进行排序,它不是很好,但会做暂且 。在 html 中声明 range 会好得多,因为它可以摆脱充满新功能的views.py。会继续努力
    • @Michal_S:这是合乎逻辑的,因为 Django 模板不允许切片。在视图中这样做也更好,因为它更有效。如果您真的想在模板中执行此操作,可以使用|slice: 模板过滤器。见编辑。
    猜你喜欢
    • 2015-02-05
    • 2013-01-10
    • 2015-08-28
    • 2013-10-22
    • 2018-04-14
    • 1970-01-01
    • 2012-06-05
    • 2016-07-12
    • 2015-10-06
    相关资源
    最近更新 更多