3

I am making a website using Django, and every time user clicks on the download button, I want download dialog box to appear in browser. I am using the following code for file download -

urllib.urlretrieve(filename)

In this case, although file is getting downloaded, but the process happens in background. Moreover, file gets downloaded where the Django project is staged, hence no control over where to save the file. How to make the download dialog box appear as soon as user clicks the download button, rather than download process getting started in background stealthily?

theharshest
  • 7,767
  • 11
  • 41
  • 51

1 Answers1

4

Using django to return an attachment should serve this purpose. Here is an example of returning a csv file to the user. In the example at the top of the page here : https://docs.djangoproject.com/en/dev/howto/outputting-csv/?from=olddocs, You can see that by setting

response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=somefilename.csv'

you can specify the file type and set it as an attachment.

If you want to implement this on a push button, I would actually have a separate view to return this file response. Then, you can specify in your template to call that view when the button is pushed (make sure to link to the view in your urls.py file). It would look something like this:

<li  class = 'button'>
  <a  href = "{% url app.views.function %}"> 
       Download
  </a>
</li>

I actually had a similar issue to this not too long ago - here are a couple of similar questions you can look here, at my question(I know it's lame to link to my own question, but I think it may help you), and here too.

Let me know if you have any questions.

Community
  • 1
  • 1
mshell_lauren
  • 5,171
  • 4
  • 28
  • 36