Wessi Wessi - 3 months ago 7
HTML Question

Using django custom template tag to display photos

I have pictures of objects in my static files that I would like to display. However for some objects I don't have a picture and for those I would like to display an image saying "no pic available". I therefore have a field called pictures which is set to 1 for the object with a picture available and 0 for those with no picture available.
I have made a template tag that should be able to insert the correct picture but I'm facing a problem.

template tag file:

def static_picture(id_internal, picture):
if picture == 1:
return '"' + "{% static" + ' "' + 'img/pictures/' + id_internal + '.jpg' + '"' + ' %}' + '"'
else:
return '"' + "{% static" + ' "' + 'img/pictures/picture_missing.jpg' + '"' + " %}" + '"'


html:

<img src="{{ object.id_internal|static_picture:object.picture }}" class="img-responsive">


It outputs this but shows no picture:

<img src="{% static "img/pictures/339-10026.jpg" %}" class="img-responsive">


The path is correct and the picture exists. What am I doing wrong?

Answer

It does not work like that, after the {{}} are evaluated, there is no more evaluation. So you see string. You need to edit do code,

The Jinja (template translator create from {{}} html code) evaluate your template function and insert it to the place. After that django send this to browser:

<img src="{% static "img/pictures/339-10026.jpg" %}" class="img-responsive">

but browser does not understand this. So you have to return in your function full_path.

{% static ... %} just prefix your path with path to static folder. This path is available in settings. Settings are accessible in module settings in django.conf.

from django.conf import settings
def static_picture(id_internal, picture):
    if picture == 1:
        return '"{}/img/pictures/{}.jpg"'.format(settings.STATIC_URL, id_internal)
    else:
        return '"{}/img/pictures/picture_missing.jpg"'.format(settings.STATIC_URL)

This return full path to file

<img src="{{ object.id_internal|static_picture:object.picture }}" class="img-responsive">
<img src="path/to/static_folder/img/picturesXXX.jpg" class="img-responsive">