Django:请求对象到模板上下文透明度
我想在我的请求对象中包含一个初始化的数据结构,使其可以从我的模板的上下文对象中访问。我现在正在做的是在我的所有视图中手动传递它并且很烦人:
render_to_response(...., ( {'menu': RequestContext(request)}))
请求对象包含使用自定义上下文处理器注入的键、值对。虽然这有效,但我希望有一种更通用的方法将请求对象的选定部分传递到模板上下文。我尝试通过通用视图传递它,但事实证明,在解析 urlpatterns 列表时,请求对象并未实例化。
I want to include an initialized data structure in my request object, making it accessible in the context object from my templates. What I'm doing right now is passing it manually and tiresome within all my views:
render_to_response(...., ( {'menu': RequestContext(request)}))
The request object contains the key, value pair which is injected using a custom context processor. While this works, I had hoped there was a more generic way of passing selected parts of the request object to the template context. I've tried passing it by generic views, but as it turns out the request object isn't instantiated when parsing the urlpatterns list.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要实现此目的,您可能必须 创建您自己的中间件。这样,您就可以完全控制请求,无论是在视图函数之前还是之后。
中间件是一个非常强大的概念,实现起来并不像看起来那么困难,但也不要做得太过分——它会让遵循程序流程变得困难。
To accomplish this, you will probably have to create your own middleware. That way, you have full control of the request, both before and after the view function.
Middleware is a very powerful concept, and not as hard to implement as it could seem, but don’t overdo it – it makes it hard to follow the program flow.
我不一定很好地理解你的问题。
要么您抱怨必须在所有视图中包含
RequestContext
,在这种情况下您需要编写一个为您传递 RequestContext 的包装器。但您仍然必须将请求传递给它。如果您也不想通过它,您可能必须按照 mikl 的建议创建自己的中间件。或者,您抱怨必须在每个视图中传递大量菜单项。这是错误的方法,您需要 定义一个模板上下文处理器,确保默认情况下这些内容存在于模板中。
I don't necessarily understand your question well enough.
Either you are complaining having to include the
RequestContext
in all views, in which case you need to write a wrapper that passes RequestContext for you. But you will still have to pass to it the request. If you don't want to pass that too, you may have to create your own middleware as mikl suggests.Or, you are complaining about having to pass a lot of menu items, in each and every view. Which is wrong way to do it, you need to define a template context processor that ensures these are present in the template by default.