10

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.

cezar
  • 11,616
  • 6
  • 48
  • 84
Sourabh
  • 8,243
  • 10
  • 52
  • 98

1 Answers1

8

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

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">
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • I want the filter to get `{{ STATIC_URL }}images/{{ book.imageurl }}`. and not just `{{book.imageurl}}`.Is it possible? – Sourabh Aug 21 '13 at 18:03
  • I tried your first method and changed filter to `.exists('appname/static/images/'+DataIReceived)` and `.exists('static/images/'+DataIReceived)` but in both cases django can't find file and I get 'image.png' back. What should be the relative path? – Sourabh Aug 21 '13 at 18:20
  • Also, I think, that you should pass an absolute path to `exists`, try constructing it from the `os.path.join(, )`. – alecxe Aug 21 '13 at 18:26
  • Thanks it worked! I used a dirty method to get absolute path and I will have to fix is soon (`os.path.join` was giving me problem so I used `+` directly). But for now, I am happy that it finally worked :) – Sourabh Aug 21 '13 at 18:47
  • @Sourabh glad to hear! – alecxe Aug 21 '13 at 18:48