我正在尝试使用我自己的mixin“BaseViewMixin”扩展一个简单的基于日期的视图(使用1.3泛型类方法):
class BaseViewMixin(object):
"""define some basic context for our views"""
model = Alert
month_format = "%m"
date_field = "date"
def get_context_data(self, **kwargs):
"""extra context"""
context = super(BaseViewMixin, self).get_context_data(**kwargs)
context["CACHE_SERVERS"] = settings.CACHE_SERVERS
return context
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(BaseViewMixin, self).dispatch(*args, **kwargs)
class IndexView(BaseViewMixin, TodayArchiveView):
template_name= "index.html"
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
queryset = Alert.objects.default(self.day)
tickets = Alert.objects.tickets(self.day)
alert_groups = []
for item in tickets:
alert_groups.append({"ticket": item, "alerts": queryset.filter(ticket=item["ticket"])})
context["alert_groups"] = alert_groups
return context
问题是,一旦我覆盖了我的IndexView类的get_context_data方法,就会消除您通常在上下文中获得的所有基于日期的事物。这是为什么?我希望{{day}},{{previous_day}}等出现在上下文中,以及self中。当我删除我的get_context_data方法时,所有通用日期的东西都有效。
urls.py条目只是:
url(r'^$', IndexView.as_view(), name='index'),
答案 0 :(得分:2)
这是一种允许我重用代码的方法。我仍然不理解为什么get_context_data
在原始问题中按照我的定义方式消除TodayArchiveView
上下文。似乎使用下面的场景对我的mixin做同样的事情,但事实并非如此。在get_context_data
中调用DateMixin
时,会保留ViewMixin上下文。
class ViewMixin(object):
"""define some basic context for our views"""
model = Alert
def get_context_data(self, **kwargs):
"""extra context"""
context = super(ViewMixin, self).get_context_data(**kwargs)
context["CACHE_SERVERS"] = settings.CACHE_SERVERS
return context
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(ViewMixin, self).dispatch(*args, **kwargs)
class DateMixin(object):
month_format = "%m"
date_field = 'date'
def get_alert_groups(self):
none, qs, dated_items = self.get_dated_items()
day = dated_items["day"]
queryset = Alert.objects.default(day)
tickets = Alert.objects.tickets(day)
alert_groups = []
for item in tickets:
alert_groups.append({"ticket": item, "alerts": queryset.filter(ticket=item["ticket"])})
return alert_groups
def get_context_data(self, **kwargs):
context = super(DateMixin, self).get_context_data(**kwargs)
context["alert_groups"] = self.get_alert_groups()
return context
class IndexView(ViewMixin, DateMixin, TodayArchiveView):
template_name= "index.html"
答案 1 :(得分:0)
出现这个问题是因为你从2个课程中就已经存在了。
context = super(IndexView, self).get_context_data(**kwargs)
将使用BaseViewMixin
而不是TodayArchiveView
(从左到右的超级步行基类)的方法初始化上下文 - >来自TodayArchiveView
的上下文变量将丢失。
我认为你可以这样做:
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context_day = super(BaseViewMixin, self).get_context_data(**kwargs)
context = dict(context, **context_day)
...
答案 2 :(得分:0)
不是您问题的准确答案,但考虑到您的目标似乎是为多个视图添加某个上下文,context processor可能是一个很好的解决方案!