【问题标题】:Django - Custom Filter to check if File existsDjango - 自定义过滤器以检查文件是否存在
【发布时间】:2013-08-24 05:53:18
【问题描述】:

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

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

但它不起作用。我也不知道为什么。

【问题讨论】:

  • “不起作用”是什么意思?它返回什么?
  • 我在图片的网址中得到http://localhost:8000/static/images/ios.png|file_exists

标签: django django-models django-templates django-template-filters


【解决方案1】:

您没有应用过滤器,因为|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">

【讨论】:

  • 我希望过滤器获得{{ STATIC_URL }}images/{{ book.imageurl }}。而不仅仅是{{book.imageurl}}。这可能吗?
  • 我尝试了您的第一种方法并将过滤器更改为 .exists('appname/static/images/'+DataIReceived).exists('static/images/'+DataIReceived) 但在这两种情况下 django 都找不到文件并且我得到了“image.png”。相对路径应该是什么?
  • 另外,我认为您应该将绝对路径传递给exists,尝试从os.path.join(&lt;project root&gt;, &lt;image path&gt;) 构造它。
  • 谢谢它的工作!我使用了一种肮脏的方法来获取绝对路径,我很快就会修复(os.path.join 给我带来了问题,所以我直接使用了+)。但就目前而言,我很高兴它终于奏效了:)
  • @Sourabh 很高兴听到!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-15
  • 2010-10-14
  • 2013-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多