[Django]-How to send two variables with html as a JSON in Django?

6👍

Try Django’s render_to_string :

economy = render_to_string('dbmanager/classes.html', {"classes": economy_classes})
business = render_to_string('dbmanager/classes.html', {"classes": business_classes})

render_to_string() loads a template, renders it and then returns the resulting string. You can then send these resulting strings as JSON.

Your final code now becomes:

from django.template.loader import render_to_string

def getClasses(request):
   User = request.user 
   aircomcode = request.POST.get('aircompany_choice', False)

   working_row = Pr_Aircompany.objects.get(user=User, aircomcode=aircomcode)
   economy_classes = working_row.economy_class
   business_classes = working_row.business_class

   economy = render_to_string('dbmanager/classes.html', {"classes": economy_classes})
   business = render_to_string('dbmanager/classes.html', {"classes": business_classes})

   return JsonResponse({"economy": economy, 
                    "business": business})

2👍

render_to_response is, as the name implies, for rendering a response. You don’t want to do that; you want to render two templates, and put them into a JSON response. So use render_to_string.

0👍

You can send one in your context and one as where you want to render.

Leave a comment