[Fixed]-Getting file extension in Django template

53👍

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 %}

7👍

I don’t know if there is a nifty built in django function to do this, but you can get the extension from your filefield

fileName, fileExtension = os.path.splitext(file.name)

If you’re set on doing this in your template you can create a custom tag which wraps this

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

Leave a comment