[Answered ]-Extending class, date based generic views in django and get_context_data?

2👍

This is one way to do it which allows me to reuse code. I’m still not understanding why get_context_data wipes out the TodayArchiveView context the way I define it in my original question. It seems that using the scenario below would do the same thing to my mixin but it doesn’t. The ViewMixin context is preserved when calling get_context_data in DateMixin.

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"
👤Matt

0👍

The problem arise because you’re inhereting from 2 classes.

context = super(IndexView, self).get_context_data(**kwargs) will initialise the context with the method from BaseViewMixin not TodayArchiveView (super walks base classes from left to right) –> context variables from TodayArchiveView will be lost.

I think you can do this:

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)
    ...
👤manji

0👍

Not an exact answer to your question, but considering the fact that your goal seems to be adding a certain context to more than one view a context processor might be a good solution!

Leave a comment