Django - Custom Filter to check if File exists
Asked Answered
T

1

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.

Transcendence answered 21/8, 2013 at 18:0 Comment(2)
What do you mean it "doesn't work"? What does it return?Kirmess
I get http://localhost:8000/static/images/ios.png|file_exists in url of imageTranscendence
H
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">
Hanaper answered 21/8, 2013 at 18:1 Comment(5)
I want the filter to get {{ STATIC_URL }}images/{{ book.imageurl }}. and not just {{book.imageurl}}.Is it possible?Transcendence
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?Transcendence
Also, I think, that you should pass an absolute path to exists, try constructing it from the os.path.join(<project root>, <image path>).Hanaper
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 :)Transcendence
@Transcendence glad to hear!Hanaper

© 2022 - 2024 — McMap. All rights reserved.