如何一次设置所有Django通用视图的上下文变量?

问题描述 投票:0回答:2

我将为CRUD操作提供标准的基于类的视图,这些视图继承自各种通用视图,如ListView,DetailView等。我将把他们所有的context_object_name属性设置为相同的值。

我想知道是否有办法更加pythonic,不在代码中多次重复操作,但是如果有必要可以在一个地方更改该变量?

PS。我想到的当然是进一步的继承,但也许还有更多类似django的方式?

python django django-class-based-views
2个回答
0
投票

Middleware can do the trick

class SetContextObjectNameMiddleware:

    def process_template_response(self, request, response):
        if 'object' in response.context_data:
            response.context_data['foo'] = response.context_data['object']
        return response

然后将中间件添加到settings.py

它并没有真正设置视图的context_object_name,但它实现了相同的结果。


0
投票

您也可以使用mixin而不是中间件应用:

class CommonContextMixin(object):
    def get_context_data(self, *args, **kwargs):
        context = super(CommonContextMixin, self).get_context_data(*args, **kwargs)
        context['foo'] = 'bar'

        return context

然后在你的视图中使用mixin:

class MyView(TemplateView, CommonContextMixin):
    """ This view now has the foo variable as part of its context. """

相关的Django文档:https://docs.djangoproject.com/en/2.1/topics/class-based-views/mixins/

© www.soinside.com 2019 - 2024. All rights reserved.