论坛首页 编程语言技术论坛

django 简化 view 函数的编写

浏览 5271 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-08-22  
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/(?P<id>[0-9]+)/page/(?P<page>[0-9]+)',channel_list,
   {'template_name': 'videos/channel.html'},"videos_channel"),
   发表时间:2007-08-23  
其实这么简化我感觉没什么意义~
可能看起来更难懂
0 请登录后投票
   发表时间:2007-08-23  
可以不用写      context_instance=RequestContext(request, result)
0 请登录后投票
   发表时间:2007-08-24  
有些代码不管写在哪里都得写。
这样做将模板的配置放到url里,我觉得不是很符合开发习惯。
context_instance=RequestContext(request, result)
这句通常情况下也是不需要加的。
0 请登录后投票
   发表时间:2007-08-24  
如果涉及到用户,每一页几乎都要context_instance=RequestContext(request, result)
或者,你自定义了一个TEMPLATE_CONTEXT_PROCESSORS,用来给模板传一个参数media_root
也需要context_instance

将模板的配置放到url里,我个人倒是更喜欢,原因如下:
1.generic view就是这么干的
2.view我更喜欢写成generic的:)
不过,可以考虑加一个默认值
0 请登录后投票
   发表时间:2008-06-25  
zuroc 写道
可以不用写      context_instance=RequestContext(request, result)



我试过,不行的,必须这样写才行:
return render_to_response('xxx.html',{'xx':'xx'},RequestContext(request))

请问 张 教 主,还有啥更好的办法?
0 请登录后投票
   发表时间:2008-06-25  
你的代码是怎么写的?
不过好久没有碰django,也忘得差不多了.
但按道理是可以的,
就是一个嵌套函数.
0 请登录后投票
   发表时间:2008-06-27  
render_to_response 里封装的应该是 Context 而不是 RequestContext,所以应该是不行的。
0 请登录后投票
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics