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...
html. djt). Without a differentiated extension, you need to open a file in order to know it's a django template and not a regular (e.g. HTML) file.
{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
Yes you can extend different or same templates.
You're missing a .get_extension
on your model? That's easy, just add it :-) You can have all sorts of methods on a model. So something 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')
def extension(self):
name, extension = os.path.splitext(self.file.name)
return extension
(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:
class File(models.Model):
...
def css_class(self):
name, extension = os.path.splitext(self.file.name)
if extension == 'pdf':
return 'pdf'
if extension == 'doc':
return 'word'
return 'other'
The template is simpler this way:
{% for file in files %}
<a class="{{ file.css_class }}">link</a>
{% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With