Include tag Django: Pass template name as variable from AJAX response

This is the template code in Django, where "condition_template.html" should be replaced with template name variable

{% include "condition_template.html" %}

I want to pass the condition_template_name which returned from AJAX API call response below:

$.ajax({
      url: get_template_data_url,
      type: "GET",
      dataType: 'json',
      success: function (data) {
           var condition_template_name = data['condition_template_name']
      }
    });

You can't really do this with Django by itself without reloading the page. Template includes are handled in the backend when the server is building the page. Ajax is done after the browser has received the page. To communicated an ajax value to django to use in an include, you'd need to send it as part of a POST or GET request (respectively, using javascript to add a hidden form field for a form or a querystring value to a url, eg, href="url?name=value", and then reload the page/view to send the value to the template via the context.

There are some third party solutions that might work without pageload. HTMX, for example, abstracts an ajax request that you can send to a django view, then receive the HTML that Django generates and place it into your currently loaded page. You could use ajax to get the appropriate view name, then javascript to alter the hx-get value with the appropriate include and trigger the exchange.

Back to Top