Search code examples
djangodownloadfilefield

How to download a FileField in django


This is my model

class Informe(models.Model):
id_paciente = models.ForeignKey('Paciente')
id_medico = models.ForeignKey('Medico')
id_tecnico = models.ForeignKey('Tecnico')
contenido = models.FileField(upload_to='informes', verbose_name='informe')
def relative_path(self):
    os.path.realpath(self.path, settings.MEDIA_ROOT)

I'm supoussed to download the txt file saved in /files/informes. I can get without problems the url or the path in the template, but have no clue about how to being able to download it. How can I manage to, whenever the client clicks on the template's link, autodownload the file?

TIA!


Solution

  • I found this in the Django documentation:

    Telling the browser to treat the response as a file attachment

    To tell the browser to treat the response as a file attachment, use the content_type argument and set the Content-Disposition header. For example, this is how you might return a Microsoft Excel spreadsheet:

    response = HttpResponse(my_data, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="foo.xls"'

    https://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment