Django - 自定义过滤器来检查文件是否存在 [英] Django - Custom Filter to check if File exists
本文介绍了Django - 自定义过滤器来检查文件是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我制作了这个自定义过滤器来检查图像是否存在:
I made this custom filter to check if an image exists or not:
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
我在模板中使用了这个:
And I used this in the template like this:
<img src="{{ STATIC_URL }}images/{{ book.imageurl }}|file_exists" alt="{{book.title}} Cover Photo">
但它不起作用.我不知道为什么.
But it doesn't work. And I have no idea why.
推荐答案
您没有应用过滤器,因为 |file_exists
在 {{}}
之外.试试这个:
You are not applying the filter because |file_exists
is outside of {{}}
. Try this:
<img src="{{ STATIC_URL }}images/{{ book.imageurl|file_exists }}" alt="{{book.title}} Cover Photo">
或者,如果你想将 file_exists
应用到整个图片 url,试试这个:
Or, if you want to apply file_exists
to the whole image url, try this:
<img src="{{ STATIC_URL|add:'images/'|add:book.imageurl|file_exists }}" alt="{{book.title}} Cover Photo">
这篇关于Django - 自定义过滤器来检查文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文