gpt4 book ai didi

Django - 自定义过滤器来检查文件是否存在

转载 作者:行者123 更新时间:2023-12-04 14:59:52 25 4
gpt4 key购买 nike

我制作了这个自定义过滤器来检查图像是否存在:

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">

关于Django - 自定义过滤器来检查文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18364547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com