Skip to content
Advertisement

Check file extension in Django FileField

I need to run a different code depending on the extension of the file.

This is a simplified version of the model:

class SuplierList(models.Model):
    file = models.FileField(upload_to='fornecedores/')

This is the part of the view that I have the problem:

table = request.GET.get("table")
ft = FornecedorTabela.objects.filter(id=table)[0]
file = ft.file
if re.match('.pdf$', ft.file.name):

I don’t know how I should write this last condition above. With this version above, I get the error: The ‘python’ engine cannot iterate through this file buffer.

How show I write this condition?

Advertisement

Answer

Use str.endswith

Ex:

table = request.GET.get("table")
ft = FornecedorTabela.objects.filter(id=table)[0]
file = ft.file
if ft.file.name.endswith('.pdf'):
    ...
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement