Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.2K
Views
Download a file with Django

This might perhaps be a simple question, but I somehow just can not find the solution. Django offers a lot about uploading file, but how do I do to download a file.

Let's assume we have a button on HTML on uploads/something.txt as a file.

I tried with django.views.static.serve, however what this did it would open a file on webpage.

My question is simple: What is the best and most pythonic way for user of our website to download a file?

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

  • You need to read that file.
  • Serve it using HttpResponse along with proper content type.

Here's some sample code:

content = open("uploads/something.txt").read()
return HttpResponse(content, content_type='text/plain')

This should serve a text file.

But as you described, on some browser, it will not ask to download the file, rather, it would show it in the browser. If you want to show a download prompt, use this:

response = HttpResponse(open("uploads/something.txt", 'rb').read())
response['Content-Type'] = 'text/plain'
response['Content-Disposition'] = 'attachment; filename=DownloadedText.txt'
return response

However, please note that it might be a better idea to serve static contents or uploaded files via nginx or the reverse proxy of your choice. Sending large files through Django might not be the most optimum way of doing that.

about 4 years ago · Santiago Trujillo Report

0

import os
from django.conf import settings
from django.http import HttpResponse, Http404

def download(request, path):
    file_path = os.path.join(settings.MEDIA_ROOT, path)
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
            response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
            return response
    raise Http404
about 4 years ago · Santiago Trujillo Report

0

Maybe a little late but here is my solution:

def render(self, value):
        return format_html('<a href="/media/{0}" download>{0}</a>', value)
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!