我制作了这个自定义过滤器来检查图像是否存在:
from django import template
from django.core.files.storage import default_storage
register = template.Library()
@register.filter(name='file_exists')
def file_exists(filepath):
if default_storage.exists(filepath):
return filepath
else:
index = filepath.rfind('/')
new_filepath = filepath[:index] + '/image.png'
return new_filepath
我在模板中使用了它,如下所示:
<img src="{{ STATIC_URL }}images/{{ book.imageurl }}|file_exists" alt="{{book.title}} Cover Photo">
但这不起作用。我不知道为什么。
您没有应用过滤器,因为|file_exists
是在外面{{}}
。尝试这个:
<img src="{{ STATIC_URL }}images/{{ book.imageurl|file_exists }}" alt="{{book.title}} Cover Photo">
或者,如果您想申请file_exists
对于整个图像网址,请尝试以下操作:
<img src="{{ STATIC_URL|add:'images/'|add:book.imageurl|file_exists }}" alt="{{book.title}} Cover Photo">
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)