我将为CRUD操作提供标准的基于类的视图,这些视图继承自各种通用视图,如ListView,DetailView等。我将把他们所有的context_object_name
属性设置为相同的值。
我想知道是否有办法更加pythonic,不在代码中多次重复操作,但是如果有必要可以在一个地方更改该变量?
PS。我想到的当然是进一步的继承,但也许还有更多类似django的方式?
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
,但它实现了相同的结果。
您也可以使用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/