[Answer]-DJANGO Load/include templates inside base template using ajax

1👍

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.

👤mccc

Leave a comment