Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting file extension in Django template

Tags:

python

django

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...

like image 697
David Silva Avatar asked Nov 19 '12 13:11

David Silva


People also ask

Which of the following is the file extension for a Django template file?

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.

What does {% %} mean in Django?

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

Do Django templates have multiple extends?

Yes you can extend different or same templates.


1 Answers

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 %}
like image 80
Reinout van Rees Avatar answered Sep 17 '22 03:09

Reinout van Rees