I have model like this:
class File(models.Model):
name = models.CharField(max_length=45)
description = models.CharField(max_length=100, blank=True)
file = models.FileField(upload_to='files')
I get all File objects in my view and according to the type of file, I would like to print appropriate a class:
<a class="pdf">link</a>
or
<a class="word">link</a>
or
<a class="other">link<a/>
in my template.
How can I get file extension in Django template?
I would like to do somethink like this:
{% for file in files %}
{% if file.get_extension == 'pdf' %}
<a class="pdf">link</a>
{% elif file.get_extension = '.doc' %}
<a class="word">link</a>
{% else %}
<a class="other">link<a/>
{% endif %}
{% endfor %}
Of course, ‘file.get_extension’ doesn’t exist…
You’re missing a
.get_extensionon your model? That’s easy, just add it 🙂 You can have all sorts of methods on a model. So something like this:(The name
.extension()is more pythonic than.get_extension(), btw).You can go even further. Isn’t that if/else structure a bit tedious in your template? It is less of a hassle in Python code:
The template is simpler this way: