我查看了一些代码,并提出了这个问题-- Django: What is the difference b/w HttpResponse vs HttpResponseRedirect vs render_to_response --它讨论了不同类型的请求响应。
有没有理由使用HttpResponse而不是render?如果是这样,这样做的用例和优势是什么?谢谢。
发布于 2011-09-05 09:20:37
正如其名称所示,render用于呈现模板文件(主要是html,但也可以是任何格式)。render基本上是一个简单的HttpResponse包装器,它呈现一个模板,但正如在前面的回答中所说,您可以使用HttpResponse在响应中返回其他内容,而不仅仅是呈现模板。
发布于 2011-09-05 05:13:21
当然,假设您正在进行AJAX调用,并希望返回一个JSON对象:
return HttpResponse(jsonObj, mimetype='application/json')原始问题中的公认答案提到了这种方法。
发布于 2019-10-26 01:25:47
这是render的参数。它获取模板(Template_name)并与给定的上下文字典组合,并返回一个带有该呈现文本的HttpResponse对象。
render(request, template_name, context=None, content_type=None, status=None, using=None)甚至render返回HttpResponse,但它可以使用上下文呈现模板(如果字典中的值是可调用的,视图将在呈现模板之前调用它)。
#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')在下面的HttpResponse中,我们首先加载模板,然后用上下文呈现它并发送响应。所以使用render非常容易,因为它将参数作为template_name和context,并在内部将它们组合在一起。渲染由django.shortcuts导入
https://stackoverflow.com/questions/7301985
复制相似问题