Put a Rendered Django Template in Json along with some other items
Let's say there is a view it has a template linked to it and view passes some context date i.e. objects to template and template renders it and i got a rendered html in browser, just typical view,
# views.py
def view_name(request, params):
objects = Object.objects.all()
somevar = "something"
request_id = 123456
# Context to be passed on to template
context = {'objects':objects}
return render(request, 'appname/template.html', context)
But i don't just want rendered html i want the output in JSON
as following format
{"somevar":"something","html":"rendered html coming from template.html ","request_id":"123456"}
so i can easily differentiate the html and other values if calling a view as AJAX
Please ask any questions if i can make it more clear!
Answer
Use render_to_string()
shortcut and JsonResponse
:
from django.http import JsonResponse
from django.template.loader import render_to_string
def view_name(request, params):
objects = Object.objects.all()
somevar = "something"
request_id = 123456
# Context to be passed on to template
context = {'objects':objects}
rendered_html = render_to_string('appname/template.html', context)
return JsonResponse({
"somevar": somevar,
"html": rendered_html,
"request_id": request_id
})
source: stackoverflow.com