找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 4453|回复: 0

Django 简化view函数的编写

4

主题

7

帖子

63

积分

新手

积分
63
python2013 发表于 2013-1-26 09:36:39 | 显示全部楼层 |阅读模式
[code brush:python;toolbar:false;]1.定义包装函数

from django.shortcuts import render_to_response
from django.template.context import RequestContext

def template_name(func):
  def view(request,template_name,*args,**keys):

      result=func(request,*args,**keys)

      if type(result)!=dict:
          return result

      return render_to_response(
      template_name,
      result,
      context_instance=RequestContext(request, result)
      )

  return view

2.使用

@template_name
def video(request,id):
  return  {
      'video':Video.objects.get(id=id)
  }

3.urls.py传入参数

   (r'^channel/(?Pid[0-9]+)/page/(?Ppage[0-9]+)',channel_list,
   {'template_name': 'videos/channel.html'},"videos_channel"),[/code]
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表