开发者

HttpResponse vs. Render

I was looki开发者_如何学编程ng 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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜