HttpResponse vs. Render

后端 未结 3 1055
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 15:22

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

3条回答
  •  你的背包
    2021-02-05 15:31

    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

提交回复
热议问题