Django:如何为所有视图(而不是模板)提供上下文? [英] Django: How to provide context to all views (not templates)?

查看:131
本文介绍了Django:如何为所有视图(而不是模板)提供上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为所有基于函数的视图(FBV)提供一些上下文,类似于 TEMPLATE_CONTEXT_PROCESSORS (CP)为所有模板提供上下文。后者不适用于我,因为在渲染模板之前我需要这个上下文。



特别是在我的网站上,我有一个函数需要一个请求并返回关于项目的类别的模型。我的CP为所有模板提供了这一点,但是我发现自己从FBV中拨出相同的电话,并希望消除这种冗余。



这个问题是类似的,但它预先考虑访问CP输出的方法从意见。这似乎是黑客,我不知道这是最好的方法。



Django的做法是什么?

解决方案

a href =https://docs.djangoproject.com/en/1.9/topics/http/middleware/ =nofollow>中间件 ...


$ b $

request.extra_model = self.get_model(request.user);

request.extra_model = self.get_model(request.user )


I want to provide some context to all my function-based views (FBV) similar to the way TEMPLATE_CONTEXT_PROCESSORS (CP) provides context to all of one's templates. The latter doesn't work for me because I need that context prior to rendering the templates.

In particular, on my site I have a function which takes a request and returns the model for the Category of item in focus. My CP provides this for all templates, but I find myself making the same call from my FBV's and would like to remove this redundancy.

This question is similar but it presupposes the approach of accessing the output of the CP from the views. This seems hacky, and I'm not sure it's the best approach.

What's the Django way to do this?

解决方案

Use Middleware...

class MyModelMiddleware(object):
    def process_request(self, request):

        request.extra_model = self.get_model(request.user)

这篇关于Django:如何为所有视图(而不是模板)提供上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆