Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Custom Filter to check if File exists

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.

like image 378
Sourabh Avatar asked Aug 21 '13 18:08

Sourabh


1 Answers

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">
like image 195
alecxe Avatar answered Nov 04 '22 01:11

alecxe