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



如果文件daily-yyyy-mm.csv退出,我将尝试提供下载选项,但即使文件存在,它也始终显示不可用

我在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_list.uplad.upload_report_date中访问字典file_list

有了这个,你将永远降落在else中,因为你无法通过这种方式访问它。您的代码试图获得file_list的属性upload,该属性将始终返回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 %}
...

最新更新