Search code examples
pythondjangohttpencodingrendering

How to get a string from HttpResponse or render to a string in Python/Django?


Currently, I have the following code:

from django.shortcuts import render
# ...
def prerender(js: json) -> str:
    # ...
    response = render(None, 'partial/name.html', context)
    return response.content.decode()

Is there a way in Django to render to a string rather than to the bytes of HttpResponse? Otherwise, how to get HttpResponse content as a string properly?


Solution

  • The answer is almost in your question:

    from django.template.loader import render_to_string
    
    return render_to_string("partial/home.html", context)
    

    You can use this to render all kinds of templates, for emails and so on.