- django.shortcuts package提供提供帮助类和函数可以更便捷的操作MVC中的每一部分,包含:
- render(request, template_name,[dictionary],[context_instance],[content_type],[status],[current_app],[dirs]):使用给定的context填充模板,返回HttpResponse对象,该对象的content就是模板替换后的内容.render()函数同以context_instance(RequestContext)为参调用render_to_response功能相同
render#如下代码功能相同
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")
- render_to_response(template_name[, dictionary][, context_instance][, content_type][, dirs]):使用给定的context填充template,并返回HttpResponse object,
render_to_responsereturn render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(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")
- redirect(to, [permanent=False],*args, **kwargs):返回to对象的url对应的HttpResponseRedirect,默认是临时重定向,如果permanent=true则永久重定向,参数to可以是:
- a model:这个model的get_absolute_url()函数会被调用
- a view name:urlresolvers.reverse会被调用逆向解析view name得到url
- 一个绝对或者相对url
- get_object_or_404(klass, *args, **kwargs):使用给定的model manager调用get()函数,如果没得到就抛出Http404异常
- get_list_or_404(klass, *args, **kwargs):使用给定的model manager调用filter函数返回结果转换成list,如果list为空则抛出Http404异常
|