Django-用于检查文件是否存在的自定义筛选器
我制作此自定义过滤器是为了检查图像是否存在:Django-用于检查文件是否存在的自定义筛选器,django,django-models,django-templates,django-template-filters,Django,Django Models,Django Templates,Django Template Filters,我制作此自定义过滤器是为了检查图像是否存在: 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):
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_存在
在{}
之外。试试这个:
<img src="{{ STATIC_URL }}images/{{ book.imageurl|file_exists }}" alt="{{book.title}} Cover Photo">
你说“不行”是什么意思?它返回什么?我得到
http://localhost:8000/static/images/ios.png|文件_存在于图像的url中
,我希望筛选器获取{{STATIC_url}}图像/{{book.imageurl}}
。不仅仅是{{book.imageurl}}
。可能吗?我尝试了您的第一种方法,并将过滤器更改为.exists('appname/static/images/'+DataIReceived)
和.exists('static/images/'+DataIReceived)
,但在这两种情况下,django都找不到文件,我得到了'image.png'。相对路径应该是什么?另外,我认为,您应该将绝对路径传递给exists
,尝试从os.path.join(,)
构建它。谢谢它的工作!我使用了一个脏方法来获取绝对路径,我将很快修复它(os.path.join
给了我问题,所以我直接使用了+
)。但现在,我很高兴它终于成功了:)@Sourabh很高兴听到这个消息!
<img src="{{ STATIC_URL|add:'images/'|add:book.imageurl|file_exists }}" alt="{{book.title}} Cover Photo">