yoarch
yoarch

Reputation: 29

Django HttpResponse in JsonResponse

In my django project in order to avoid another request I would like to return a JsonResponse with a HttpResponse in there like this:

JsonResponse({"known": True, "space": render(request, 'space.html')}, status=200)

Django process returns the normal internal error Object of type HttpResponse is not JSON serializable

I tried all the web solutions (serializer, etc.) and can not find a way to return a json format (necessary for my javascript) with dictionary entries with one of them being an entire html page that I can use with then with $("body").html(response["space"]).

Am I missing something?

Thanks for your time.

Upvotes: 1

Views: 895

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

The render function returns a HttpResponse, and indeed, the json serializer does not know how to handle this.

You can instead use render_to_string [Django-doc] to render it to a string instead:

from django.template.loader import render_to_string

…

JsonResponse({
    'known': True,
    'space': render_to_string('space.html', request=request)
})

Upvotes: 5

Related Questions