Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django TemplateResponse vs render

What is the difference between

return TemplateResponse(request, self.template_name, context=context)

and

return render(request, self.template_name, context=context)

Is there any scenario why I should use one of them and not the other?

like image 413
Alejandro Veintimilla Avatar asked Aug 08 '16 21:08

Alejandro Veintimilla


People also ask

What is difference between HttpResponse and render?

Abid covers it, render is usually used to load a template and a context, while HttpResponse is usually for data. As it's bad practice to "respond" with html. Render is essentially a shortuct for HttpResponse , It provides a more effective way to modify templates, and load data dynamically.

What is template response in Django?

TemplateResponse (source code) is a class provided by Django that retains context for the HTTP request that caused the view to generate the response. TemplateResponse is useful for modifying a response before it is rendered, which cannot be done with a traditional static HttpResponse object.

Why we use render in Django?

Django render() Function The purpose of render() is to return an HttpResponse whose content is filled with the result of calling render_to_string() with the passed arguments.


1 Answers

A TemplateResponse delays the rendering of the template until after the view is finished. This allows any template response middleware to run on the response, and potentially alter the template or the context data before the template is rendered. After the template response middleware has run, the template is rendered, and the normal response middleware is run on the rendered content before the response is returned to the client.

The render() shortcut immediately renders the template and returns a HttpResponse.

like image 127
knbk Avatar answered Sep 19 '22 14:09

knbk