[Django]-Refresh a django subtemplate with javascript – reload only part of the page

7👍

With the help of a friend, I solved this.

I’m going to answer my question with some detail, because I am 100% sure someone is going to need to figure out how to do this later. Happy to save you the trouble.

I had to change my mental model about how this works.

I still send a request to the server with javascript, and the view returns the templated HTML.

However, and this is the important part, what I do is take the rendered HTML (from the response, what is returned with return render(response, "your_template.html", context)) and replace that part of my page with that HTML.

Here’s the Javascript.

function getQuery(item) {
  // Sends a request to the API endpoint to fetch data

  let request = new XMLHttpRequest();
  let method = 'GET';
  let query = // omitted

  let url = '/ajax/?' + query;
  request.open(method, url);
  request.onload = function () {
    // the response is the rendered HTML
    // which django sends as return render(response, "your_template.html", context)
    let myHTML = request.response;
    // This is the important part
    // Set that HTML to the new, templated HTML returned by the server
    document.getElementById('flex-container-A').innerHTML = myHTML;
  };
  request.send();
}

and for completeness, here’s the view:
views.py

def ajax_view(request):
    """
    Server API endpoint for fetching data
    """

    context = {}
    queryset = Form.objects

    if request.method == 'GET':
        query = request.GET.get('q')

        # do some stuff and get some data
    
        context['data'] = data

        return render(request, "my_template.html", context)

Hope this helps you! This is a common pattern but not often mentioned so explicitly.

Leave a comment