Alejandro Veintimilla
Alejandro Veintimilla

Reputation: 11523

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?

Upvotes: 26

Views: 10934

Answers (1)

knbk
knbk

Reputation: 53679

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.

Upvotes: 34

Related Questions