避免在Django中每次渲染时传递RequestContext
我现在正在开发一个网站,用户登录后,页面顶部会一直显示一个搜索框。我在想,如何在Django中设计这个功能是最好的。目前,我在我的文件结构中有一个单独的文件叫做forms.py,它和settings.py在同一级别。在几乎每一个视图中,我都需要添加:
from forms.py import SearchForm
然后在每一次渲染页面的时候,我都得传递:
form = SearchForm()
return render('somepage.html',{"search_form" : form},c=RequestContext())
我查找了一下有没有更好的方法,但找不到什么有用的东西。我觉得我现在的设计不是最理想的,因为我几乎在每个视图中都需要导入和传递这个参数。
这个表单是在一个叫做base.html
的文件中定义的,所以我在使用模板继承,但根据我所了解的,我仍然需要把表单对象传递给每次渲染。
2 个回答
0
在Django 1.3之前,你可以使用一个装饰器来处理HTML的渲染:
def search_render(function):
# return a decorated function which will take template from the args
# take output of the inner function (this should be a dictionary e.g. data = ..
# instantiate SearchForm
# add SearchForm instance to the data dictionary
# and return render(template, data, RequestContext(request))
@search_render(tamplate='somepage.html')
def my_other_view(request):
return {'data':'value'}
而在Django 1.3及之后的版本,你可以使用基于类的视图,方法也差不多。
3
使用上下文处理器
通过使用 RequestContext
,将你的搜索表单添加到所有视图的上下文中,而你现在使用的新 render
方法会自动做到这一点。
def FormContextProcessor(request):
if request.user.is_authenticated():
return {'form': SearchForm() }
return {}
你提到它几乎在所有视图中都使用,而且创建一个表单并不是一个耗费资源的操作,所以我会选择这个解决方案。