django HttpResponse

快捷函数

  一般而言我们可以将渲染后的字符串作为   HttpResponse的第一个参数,作为构建响应报文的主体。

  由于这个动作实在太常有了:加载--渲染--返回;所以django提供了两个快捷函数来处理这些事务。

  这两个位于 django.shortcuts 模块中,在使用前记得先导入。

 render(request, template_name[, context][, context_instance][, content_type][, status][, current_app][, dirs][, using])

  这个函数实现查找,加载,渲染,构建 HttpResponse 对象一整套流程,所以我们可以使用它来节省许多功夫。

  request:用于生成 response 对象的 request 对象。

  template_name:模板名称,或者是包含许多模板名称的列表。

  context:渲染使用的python字典。

  context_instance:1.8版本起废弃,这里不再讨论。

  content_type:指定 MIME 类型,默认为 DEFAULT_CONTENT_TYPE  的值。

  status:响应的状态码,默认为200.

  current_app:指示哪个应用包含当前的视图。1.8版本后废弃,现在要设置 request.current_app 进行代替。

  using:用于加载模板使用的模板引擎的名称。

例子:

from django.shortcuts import render

def my_view(request):
    # View code here...
    return render(request, 'myapp/index.html', {"foo": "bar"},
        content_type="application/xhtml+xml")
这个示例等同于:

from django.http import HttpResponse
from django.template import RequestContext, loader

def my_view(request):
    # View code here...
    t = loader.get_template('myapp/index.html')
    c = RequestContext(request, {'foo': 'bar'})
    return HttpResponse(t.render(c),
        content_type="application/xhtml+xml")

2. render_to_response(template_name[, context][, context_instance][, content_type][, status][, dirs][, using])

  参数和上面的一样,就是少了 request 参数。

例子:

from django.shortcuts import render_to_response

def my_view(request):
    # View code here...
    return render_to_response('myapp/index.html', {"foo": "bar"},
        content_type="application/xhtml+xml")

这个示例等同于:
from django.http import HttpResponse
from django.template import Context, loader

def my_view(request):
    # View code here...
    t = loader.get_template('myapp/index.html')
    c = Context({'foo': 'bar'})
    return HttpResponse(t.render(c),
        content_type="application/xhtml+xml")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值