离上次更新文章已经好几个月了,请原谅小编我的懒惰,坚持其实并不是一件容易的事,大家学习Django千万别像我啊。今天我要写篇关于Django快捷函数(shortcut function)的用法总结,希望对大家学习和开发有所帮助。
前言
django.shortcuts包里提供了4个常用的快捷函数, 它们分别是 render(), redirect(),get_objects_or_404()和get_list_or_404()。当你在渲染模板,进行跳转或获取单个对象或对象清单时使用它们非常方便。
render()
render函数的作用是将给定的模板与给定的上下文字典组合起来,并返回指定内容类型的HttpResponse对象。通过它,你可以快速指定模板名称, 上下文字典(context),内容类型(content_type)和返回状态码(默认200)。该函数标准用法如下,其中request和template_name参数为必选,其它为可选参数。
render(request, template_name, context=None, content_type=None, status=None, using=None)
下面是个使用例子,返回xhtml+xml类型。
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')