使用点运算符访问字典时条件语句在 Django 模板中不起作用

Conditional Statement not working in Django template while accessing a dictionary with dot operator

如果文件 daily-yyyy-mm.csv 退出,但它始终显示 Not Avaialable,我正在尝试提供下载选项 即使文件存在。

我在 views.py 中创建了一个字典 (file_list),如果文件存在,它会为该索引保存 True。我已经检查了在 os.path.join 处生成的路径,它是正确的,而且字典对于存在的文件也有 True 。我认为问题是在访问模板中的字典时使用了 2 个嵌套的点运算符。

模板

        {% for upload in upload_list %}
        <tr>
            {%if file_list.upload.upload_report_date %}
            <td><a href="{%static 'media/daily-{{ upload.upload_report_date|date:"Y-m" }}.csv" download >Download</a></td>

            {% else %}
            <td>Not Available</td>
            {% endif %}
        </tr>
        {% endfor %}

Views.py

    upload_list = Upload.objects.all().order_by('-upload_at')
    file_list={}
    for upload in upload_list:
        try:
            if os.path.exists(os.path.join(settings.MEDIA_ROOT,'daily-%s.csv' % (upload.upload_report_date).strftime("%Y-%m"))):
                file_list[upload.upload_report_date]=True
        except:
            pass

我正在使用 python 2.7 和 django 1.6.7。

您当前尝试从您的模板中访问字典 file_listfile_list.uplad.upload_report_date

有了它,您将始终登陆 else,因为您无法通过这种方式访问​​它。 您的代码尝试获取 file_list 的 属性 upload,因为它不存在,所以它总是 return None

您可以做的是创建一个可用文件列表(因为您已经调用了变量 _list):

file_list = []
for upload in upload_list:
    try:
        if os.path.exists(...):
            file_list.append(upload.upload_report_date)
    except:
        pass

然后在您的模板中:

{% if upload.upload_report_date in file_list %}
...