Django: How to Render Template in JSON Response

In this tutorial, we will learn how to render a template in a JSON response in a Django class-based view. This is useful if you need to send some data back to the user with HTML formatting inside your JSON after an AJAX request.

 

Imports Django get_template Function

The first step is to import the Django JsonResponse class and get_template function at the top of your view file like this:

 

my_app/views.py
from django.http import JsonResponse
from django.template.loader import get_template

 

Create JSONResponseMixin Class

Now create a class JSONResponseMixin class to handle returning JSON responses.

 

my_app/views.py
class JSONResponseMixin:
  """
  A mixin that can be used to render a JSON response.
  """
  def render_to_json_response(self, context, **response_kwargs):

    return JsonResponse(self.get_data(context), **response_kwargs)

  def get_data(self, context):

    return context

 

Class to Return JSON with Rendered Template Content

Here is an example of a stripped-down Django view class that will return JSON data with a rendered template in one of the keys on a POST request:

 

class ExampleView(JSONResponseMixin, View):
  template_name = 'thing.html'
  output_template = get_template('partials/output/output.html')

  def get(self, request, *args, **kwargs):
    obj = self.get_object()
    return render(request, self.template_name, {'object': obj})

  def post(self, request, *args, **kwargs,):
    form = ExampleForm(request.POST)
    output = list(range(10))
    
    if form.is_valid():
      return self.render_to_json_response({'type': 'success', 'output': self.output_template.render({'output': output})})

 

In the above example we set an output template to use with get_template, then render it in the JSON response using self.output_template.render().

django