如何在 Django 中链接视图?
我正在实施 James Bennett 的出色 django-contact-form 但遇到了障碍。 我的联系页面不仅包含表格,还包含其他平面页面信息。
在不重写联系表单使用的现有视图的情况下,我希望能够包装或链接视图。 这样我就可以通过上下文注入一些附加信息,以便表单和平面页面数据都可以在同一模板中呈现。
我听说这是可能的,但我似乎不知道如何让它发挥作用。 我创建了自己的包装视图(称为联系表单视图),并尝试检查 HttpResponse 对象中是否有可以附加的属性,但我似乎无法弄清楚它是哪个(如果有)。
编辑:詹姆斯评论说可以找到最新的代码此处位于 BitBucket。
I'm implementing James Bennett's excellent django-contact-form but have hit a snag. My contact page not only contains the form, but also additional flat page information.
Without rewriting the existing view the contact form uses, I'd like to be able to wrap, or chain, the views. This way I could inject some additional information via the context so that both the form and the flat page data could be rendered within the same template.
I've heard it mentioned that this is possible, but I can't seem to figure out how to make it work. I've created my own wrapper view, called the contact form view, and attempted to inspect the HttpResponse object for an attribute I can append to, but I can't seem to figure out which, if any, it is.
EDIT: James commented that the latest code can new be found here at BitBucket.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
上下文处理器就是您所想到的。 和 render_to_response 无关。 所需的信息是视图是否使用 RequestContext,因为这会激活上下文处理器。
除此之外,没有办法“链接”视图以添加到上下文 - 您可以将一个视图包装在另一个视图中并更改进入其中的数据,但您不能以这种方式添加到上下文。
Context processors are what you're thinking of. And render_to_response is irrelevant. The required piece of information is if the view uses RequestContext or not, as that is what activates context processors.
Other than those, there is no way to "chain" views to add to context - you can wrap one view in another and alter the data going into it, but you cannot add to context that way.
extra_context
参数中传递平面页面(除其他外,该参数正是针对此类用例)。extra_context
argument (which is there for, among other things, precisely this sort of use case).有一个上下文处理器可以做你想做的事情。
http://docs.djangoproject.com/en/dev/ref/templates /api/
您可能可以将各种“平面页面信息”添加到上下文中。
There's a context processor that may do what you want.
http://docs.djangoproject.com/en/dev/ref/templates/api/
You can probably add your various pieces of "flat page information" to the context.