[Fixed]-HttpResponse vs. Render

21👍

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.

7👍

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.

👤Abid A

2👍

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

Leave a comment