我的模板抱怨上下文变量request.META.REQUEST_METHOD缺失。可能的原因是什么?

时间:2012-03-16 10:25:23

标签: django

呈现的模板包含以下内容:

invalid context variable: 'request.META.REQUEST_METHOD'

我在视图中打印了locals(),我可以清楚地看到

META:{
    'REQUEST_METHOD': 'GET',
    ...
}

关于可能导致这种情况的任何想法?

2 个答案:

答案 0 :(得分:0)

您可能在不传递render_to_response()的情况下使用context_instance argument

使用render()代替您的问题。

答案 1 :(得分:0)

要让您的模板接收request对象,您需要使用RequestContext呈现模板。

如果您使用的django.shortcuts.render_to_response内容如下:

return render_to_response(template_name, dictionary)

然后你应该注意到,来自链接的文档:

  

默认情况下,模板将使用Context实例

呈现

并且您将要使用以下构造:

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

但是,更好的方法是使用默认使用RequestContext的{​​{3}}(在Django 1.3中引入),所以你可以这样做:

return render(request, template_name, dictionary)