I have a django view with this function to get the data for a template:
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_dat
Anybody interested in asynchronous updating a template using AJAX can use django-async-include (GitHub repository).
This project makes it easy changing an static block inclusion to a asynchronous one. That's perfect for inclusion of computational-heavy template block.
Disclaimer: I'm the developer of this project.
If you plan in going ahead with celery, you will need 2 views:
1.viewA
that loads the main page (without the extra_data
- maybe a spinning gif animation in it's place in the HTML, to convey to the user that there is still data to be loaded in the page). This view will also start the celery task (but will not wait for it to complete). It would look similar to:
def viewA(request):
task = a_long_running_function.delay()
return render_to_response('viewA.html', {'task_id': task.id})
2.viewB
that will be accessed via AJAX after the user's browser loads viewA
(it's purpose will be to provide the extra_data
which was not loaded by viewA
). It would look similar to:
def viewB(request, task_id):
extra_data = a_long_running_function.AsyncResult(task_id)
if extra_data.ready():
return render_to_response('viewB.html', {'extra_data': extra_data.get()})
return HttpResponse('')
Once the user's browser finishes loading viewA
, you will need a bit of javascript to start running AJAX requests every X seconds/minutes to viewB
to attempt to retrieve the celery task result (based on the celery task id that is available). Once the AJAX request successfully retrieves the task result from viewB
, it can make it visible to the user.