Django自定义中间件呈现没有csrf令牌
我的自定义中间件返回呈现的响应(使用 RequestContext
) .
这似乎导致 csrf_token
context var设置为 NOTPROVIDED
(Djangos sentinel value for not provided),而 {% csrf_token %}
没有输出,因为the CSRF middleware is called on process_view,我假设在这种情况下我们永远不会运行 .
中间件呈现的响应并不复杂,并且它是一种很少使用的特殊情况,但是更改语言需要CSRF令牌,因为这是对Djangos内置 set_language
视图的POST请求 .
解决这个问题的最佳方法是什么?
回答(2)
来自1.5 docs:
process_request()应返回None或HttpResponse对象 .
尝试:
class FooMiddleware():
def process_request(self, request):
if some_clause:
return render(request, 'foo.html', {'foo': 'bar'})
return None
2 years ago
为什么你没有在process_request中使用csrf令牌的原因是,在csrf中间件的
process_view
中设置了令牌,该中间件在每个中间件的process_request
之后运行,所以你需要将代码移到_2777819中: