I was looking over some code and came to this question -- Django: What is the difference b/w HttpResponse vs HttpResponseRedirect vs render_to_response -- which discusses the di
render
is used to for what the name already indicate: to render a template file (mostly html, but could be any format). render
is basically a simple wrapper around a HttpResponse
which renders a template, though as said in the previous answer you can use HttpResponse
to return others things as well in the response, not just rendering templates.
This is arguments for render. It takes the template(template_name) and combines with a given context dictionary and returns an HttpResponse object with that rendered text.
render(request, template_name, context=None, content_type=None, status=None, using=None)
Even render return HttpResponse but it can render the template with the context(If a value in the dictionary is callable, the view will call it just before rendering the template.)
#With render
def view_page(request):
# View code here...
return render(request, 'app/index.html', {
'value': 'data',
}, content_type='application/xhtml+xml')
#with HttpResponse
def view_page(request):
# View code here...
t = loader.get_template('app/index.html')
c = {'value': 'data'}
return HttpResponse(t.render(c, request), content_type='application/xhtml+xml')
In below HttpResponse first we load the template and then render it with context and send the response. So it is quite easy with render because it takes arguments as template_name and context and combines them internally. render is imported by django.shortcuts
Sure, say you're making an AJAX call and want to return a JSON object:
return HttpResponse(jsonObj, mimetype='application/json')
The accepted answer in the original question alluded to this method.