How to chain views in Django?

我是研究僧i 提交于 2019-12-19 03:59:11

问题


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.


回答1:


  1. Write a wrapper which uses the URL to look up the appropriate flat page object.
  2. From your wrapper, call (and return the response from) the contact form view, passing the flat page in the extra_context argument (which is there for, among other things, precisely this sort of use case).
  3. There is no third step.



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/505703/how-to-chain-views-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!