Django render ajax function

Django -- Posted on Dec. 23, 2021

This code is a Django view function that handles AJAX requests and returns a JSON response containing an HTML template rendered with the given context if the request is an XMLHttpRequest (AJAX) request. Otherwise, it renders the template normally with the context and returns the result.

                from django.shortcuts import render
from django.http import JsonResponse
from django.template.loader import render_to_string
def render_ajax(request, template, context):
    is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
    if is_ajax:
        ajax_template = render_to_string(template, context)
        return JsonResponse({'template':ajax_template})
    return render(request, template,context)

Related Posts