Display a message to your users while waiting for a file download with jQuery File Download
Our Shopify app, EZ Exporter, provides an option for users to download reports on demand from the app's main page. Since it could take some time to generate the report in the background depending on the data, we needed a way to let the user know that the task is currently in progress so they don't reload the page or do something else thinking that nothing is happening. We also wanted to block the UI so the users don't accidentally click on other links/buttons while the task is running. The jQuery File Download plugin can take care of this.
Here are the steps to do it in Django.
Download the jQuery File Download library
Download the .js file and save it in the static folder of your Django project.
Reference jQuery File Download in your base template
For example:
<body> ... <script src="{% static 'vendor/jquery/jquery.js' %}"></script> <script src="{% static 'vendor/bootstrap/js/bootstrap.js' %}"></script> <script src="{% static 'vendor/jquery-ui/jquery-ui.js' %}"></script> <script src="{% static 'vendor/jquery-filedownload/jquery.fileDownload.js' %}"></script> </body>
Write a cookie in the response HTTP header
For example:
def download_file(self): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="{}"'\ .format(self.filename) response['Set-Cookie'] = 'fileDownload=true; Path=/' ... return response
Add the Javascript code
For example:
<script type="text/javascript"> $("a[id^='download-']").click(function() { $.fileDownload($(this).attr('href'), { preparingMessageHtml: "The file download will begin shortly, please wait...", failMessageHtml: "There was a problem generating your report, please try again." }); return false; //this is critical to stop the click event which will trigger a normal file download! }); </script>
That's pretty much it. Once the file is ready to be downloaded, the modal will close automatically and download will start. If there's a failure, the value of failMessageHtml will be displayed.
You can also do some customization such as changing the look of the message and modal. You can see examples here.
Tags: howto, python, django, tech, software development, javascript