0

I need to get the file type of the uploaded file in django template. I have written a templatetag for getting file name but I need file type also.

I might be able to get the content-type of the file but I couldn't find it while debugging.

doc_list.html

{{ d.file|filename }}
{{ d.file|filetype }}

templatetags/helper.py

register = template.Library()

@register.filter
def filename(value):
    return os.path.basename(value.file.name)

@register.filter
def filetype(value):
    return ???
brsbilgic
  • 11,613
  • 16
  • 64
  • 94

2 Answers2

2

USE mimetypes module

import mimetypes    

>>> mimetypes.guess_type('a.py',strict = True)
('text/x-python', None)
shiva
  • 2,674
  • 4
  • 23
  • 37
0
mime = magic.Magic(mime=True)
mime.from_file("testdata/test.pdf")

returns:

'application/pdf'
Tisho
  • 8,320
  • 6
  • 44
  • 52
user1409289
  • 492
  • 5
  • 13