Reputation: 110267
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 different types of request responses.
Is there ever a reason to use HttpResponse
over render
? If so, what would be the use case and advantage of doing so? Thank you.
Upvotes: 18
Views: 26523
Reputation: 13496
render
is used to for what the name already indicates: 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 other things as well in the response, not just rendering templates.
Upvotes: 22
Reputation: 21
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
Upvotes: 2
Reputation: 7858
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.
Upvotes: 7