问题
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?
回答1:
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
.
来源:https://stackoverflow.com/questions/38838601/django-templateresponse-vs-render