Check file extension in template - Django

6

I have a Django application where in the template I need to validate the extension of a file coming from filefield.

<div class="row">
  <p class="anexos">
    {% trans 'Anexos' %}
  </p>
  #if .jpg .png
  <div class="col-sm-3 col-md-2">
    <img class="img-thumbnail" src="{[{ anexo.trajeto }]}"/>
  </div>
  #elif .mp4 .avi
  <div class="col-sm-3 col-md-2">
    <img class="video-thumbnail" src="{[{ anexo.trajeto }]}"/>
  </div>
  #elif .zip
  <a href="{[{ anexo.trajeto }]}">Arquivo Compactado</a>
  #endif
</div>

How do I solve this problem?

    
asked by anonymous 04.08.2015 / 20:42

2 answers

2

You can use slice filter , it works in the same way as Python's array slicing . That is, if you want the extension, just look at the last 4 characters of the file name (assuming a 3-letter extension, but you can adapt it to other .jpeg extensions).

Example (note: I did not test, I have little experience with template tags, I'm not sure if it's possible to compare elements like this)

#if .jpg .png
{% if anexo.trajeto|slice:"-4:" == ".jpg" or
      anexo.trajeto|slice:"-4:" == ".png" %}
<div class="col-sm-3 col-md-2">
<img class="img-thumbnail" src="{{ anexo.trajeto }}"/>
</div>
#elif .mp4 .avi
{% elif anexo.trajeto|slice:"-4:" == ".mp4" or
        anexo.trajeto|slice:"-4:" == ".avi" %}
...

Source: this answer in SOen . Anyway, I would suggest doing this in view instead of the template, if possible (already delivering the pro template file extension in the form of a simple variable).

    
04.08.2015 / 20:53
3

In addition to the mgibsonbr solution, I would prefer to make a template tag so that you can reuse the logic in other templates.

seupport / yourapp / templatetags / extensao.py

from django import template
register = template.Library()

@register.filter()
def extensao(value):
    # retorna a extensao:
    return value[-4:] 

@register.filter()
def class_da_extensao(value):
    # retorna a class dependendo da extensao:
    ext = value[-4:]
    if ext in ['.jpg', '.png']:
        return 'img-thumbnail'
    elif ext in ['.mp4', '.avi']:
        return 'video-thumbnail'

template.html (in this case I only used the class_da_extensao tag)

{% load extensao %}
<div class="col-sm-3 col-md-2">
   <img class="{{ arquivo|class_da_extensao }}" src="{[{ anexo.trajeto }]}"/>
</div>

Using extension only:

{% load extensao %}
<div class="col-sm-3 col-md-2">
   {% if arquivo|extensao in ".jpg .png" %}
       <img class="img-thumbnail" src="{[{ anexo.trajeto }]}"/>
   {% endif %}
</div>

You can learn more about creating your template tags at this link:

    
05.08.2015 / 02:30