Getting File Extension In Django Template
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.FileFi
Solution 1:
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:
classFile(models.Model):
name = models.CharField(max_length=45)
description = models.CharField(max_length=100, blank=True)
file = models.FileField(upload_to='files')
defextension(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:
classFile(models.Model):
...
defcss_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 %}
Solution 2:
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/
Post a Comment for "Getting File Extension In Django Template"