django return rendered html in json from view

0 votes
asked Nov 1, 2017 by django_learner (116 points)

I want to return rendered django template from django function based view safely. How can i achieve that.

I am using JsonResponse object with render_to_string function and i am getting weird encoding.

html = render_to_string(....)
return_data = {"response" : html}
return JsonResponse(return_data)

1 Answer

0 votes
answered Nov 1, 2017 by django_learner (116 points)

I think you are using django < 1.8 version, this is what i am doing to get rendered html from ajax call.

Instead of using JsonReponse i have used HttpResponse object along with json.dumps

html = render_to_string(....)
data = {'data': html}
response = HttpResponse("%s" % (json.dumps(data)))
response["Content-type"] = "application/json; charset=utf-8"
return response