How to chain views in Django?

2019-02-14 16:49发布

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.

3条回答
虎瘦雄心在
2楼-- · 2019-02-14 17:29

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.

查看更多
我只想做你的唯一
3楼-- · 2019-02-14 17:40

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.

查看更多
SAY GOODBYE
4楼-- · 2019-02-14 17:44
  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.
查看更多
登录 后发表回答