Notification texts go here Contact Us Buy Now!

How to send file to response in Django?

Certainly! Here's a comprehensive HTML code block demonstrating how to send a file in response using Django (with codes formatted and title excluded):

<p>Read file first and then send it in response.</p>

<code>
from django.http import HttpResponse, HttpResponseNotFound

def waprfile(request, date):
    ...

    file_location = '/path/to/file/foo.xls'

    try:    
        with open(file_location, 'r') as f:
           file_data = f.read()

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

    except IOError:
        # handle file not exist case here
        response = HttpResponseNotFound('<h1>File not exist</h1>')

    return response
</code>

<p>Read docs for more info: <a href="https://docs.djangoproject.com/en/2.0/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment" rel="noreferrer">telling browser to treat the response as a file attachment</a> and <a href="https://docs.djangoproject.com/en/dev/topics/http/views/#returning-errors" rel="noreferrer">returning errors</a></p>

This code includes error handling in case the file doesn't exist. For more information, refer to the Django documentation on telling the browser to treat the response as a file attachment and returning errors.

In case you want to return other types of files like PDFs:

<pre><code>
def index(request):
    data = dict()
    data["name"] = "https://www.pythoncircle.Com"
    data["DOB"] = "Jan 10, 2015"

    template = get_template('testapp/test.html')
    html = template.render(data)
    pdf = pdfkit.from_string(html, False)

    filename = "sample_pdf.pdf"

    response = HttpResponse(pdf, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="' + filename + '"'
    return response
</code></pre>

Or images:

<pre><code>
img = "Suppose I am a pil image"
fomatted_img = BytesIO()
img.save(fomatted_img, format="png")
response = HttpResponse(fomatted_img.getvalue(),content_type='image/png')
response['Content-Disposition'] = 'attachment; filename="output.png"'
return response
</code></pre>

<pre><code>
img = "Suppose I am a pil image"
response = HttpResponse(content_type='image/png')
response['Content-Disposition'] = 'attachment; filename="output.png"'
img.save(response,"PNG")
return response
</code></pre>

And even binary data using FileResponse:

<pre><code>
buffer = BytesIO(excel.blob)
response = FileResponse(buffer, as_attachment=True, filename=excel.name)
response["Content-Type"] = "application/vnd.ms-excel"
return response
</code></pre>

I hope this comprehensive response helps you send different file types in responses using Django.

And that's a better demonstration of the code with HTML formatting! 😊

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.