Django - show loading message during long processing

Evan Davey picture Evan Davey · Nov 29, 2011 · Viewed 22k times · Source

How can I show a please wait loading message from a django view?

I have a Django view that takes significant time to perform calculations on a large dataset.

While the process loads, I would like to present the user with a feedback message e.g.: spinning loading animated gif or similar.

Answer

Evan Davey picture Evan Davey · Nov 30, 2011

After trying the two different approaches suggested by Brandon and Murat, Brandon's suggestion proved the most successful.

  1. Create a wrapper template that includes the javascript from http://djangosnippets.org/snippets/679/. The javascript has been modified: (i) to work without a form (ii) to hide the progress bar / display results when a 'done' flag is returned (iii) with the JSON update url pointing to the view described below

  2. Move the slow loading function to a thread. This thread will be passed a cache key and will be responsible for updating the cache with progress status and then its results. The thread renders the original template as a string and saves it to the cache.

  3. Create a view based on upload_progress from http://djangosnippets.org/snippets/678/ modified to (i) instead render the original wrapper template if progress_id='' (ii) generate the cache_key, check if a cache already exists and if not start a new thread (iii) monitor the progress of the thread and when done, pass the results to the wrapper template

  4. The wrapper template displays the results via document.getElementById('main').innerHTML=data.result

(* looking at whether step 4 might be better implemented via a redirect as the rendered template contains javascript that is not currently run by document.getElementById('main').innerHTML=data.result)