在模板中调用request的时候发现值为空,可是有时候须要在模板中调用该值来实现一些功能,为了不重复劳动咱们但愿视图函数在返回是默认返回request python
解决方案: django
在settings.py中 函数
根据Django文档,默认状况下, TEMPLATE_CONTEXT_PROCESSORS 设置以下: spa
TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', )
查看settings.py发现如今默认是没有TEMPLATE_CONTEXT_PROCESSORS的,本身动手作以下添加 debug
#其他部分省略 TEMPLATE_CONTEXT_PROCESSORS=( 'django.core.context_processors.request', )接着
在视图函数中调用 code
#其中,第一个参数为模板,第二个参数为字典 return render_to_response(template_name,{},context_instance=RequestContext(request))这个方法看起来仍是很麻烦,由于要补充一长串代码
咱们能够对render_to_response进行封装 对象
在 utils.py中 文档
from django.shortcuts import render_to_response,RequestContext #自定义render_to_response,将request封装到response返回到模板 def myrender_to_response(request,template,data={}): return render_to_response(template,data,context_instance=RequestContext(request))这样,在视图函数中使用
#第一个参数为request,第二个参数为模板,第三个参数为字典 return myrender_to_response(request,template_name,{})
在模板中例如{{request.user}}便可正常现实,还有些有时间再补充 模板
转载请注明出处,谢谢! class