Reputation: 2794
I am trying to load templates in django using ajax.
I don't want to extend the base template in all other templates as it takes huge processing time.
Hence I am finding a way to load base.html only once and the later requests will just include thier response templates within the base i.e without rendering the base.html again(the header & footer and css stuff).
Is there any way to load other templates within base template using ajax, so that the entire page is not rendered always.
Upvotes: 0
Views: 894
Reputation: 2454
Yes, there are ways: you have to avoid using {% extends "base.html" %}
in your templates and render them using render_to_string
; after you returned the rendered HTML from your Django view you can insert it where you prefer in the DOM using javascript.
A small snippet example of such an action would be
def element_form_ajax(request):
form = PageForm()
html = render_to_string('pages/element_form.html',
{'form': form},
RequestContext(request))
data = {'form': html}
return JsonResponse(data)
Now your Ajax call from the webpage gets returned a JSON object with a form
key containing an HTML form ready to be displayed where you prefer.
Refer to the docs as to how to handle CSFR tokens for AJAX calls.
Upvotes: 1