最近用 Python django做 web 开发的时候发现 RequestContext 并不能跟看到的一些资料一样通过 Template 的 render方法调用,事实上有一些资料中已经指出来了,不仅仅是 RequestContext,其实Context也不可以,直接代码通常如下:
t = loader.get_template('context_request.html')
c = RequestContext(request, {'private1': 'self info'}, processors=[custom_proc])
return HttpResponse(t.render(c))
或者使用render_to_response
context = Context({'private1': 'self info'})
return render_to_response('context_request.html', context)
测试就会发现上述两种写法都会抱错,针对第二种,只需要将context用字典代替即可,这个报错时已经说明了解决方案。
但是针对第一种写法,我们需要使用RequestContext来传递重复的参数,因此这个地方不能使用dict,否则就需要传递大量的重复参数,修改方法也很简单,不要调用 Template 的 render 方法,而用原生的读文件的方法,代码如下:
with open(os.path.join(BASE_DIR, 'company/templates/context_request.html'), 'r') as fr:
template_string = fr.read()
# t = loader.get_template('context_request.html') # 不能用loader.get_template方法,必须用原生的read方法
t = Template(template_string)
c = RequestContext(request, {'private1': 'self info'}, processors=[custom_proc])
# c = {'private1': 'self info'}
return HttpResponse(t.render(c))
# return render_to_response('context_request.html', {'private1': 'self info'},
# context_instance=RequestContext(request, processors=[custom_proc]))
那么这个时候就是可以使用的。
根本原因:loader.get_template(template_name)返回的对象并不是 django.template.Template 对象。