YearArchiveView: get_year fails

I have a rather simple view:

class YearView(YearArchiveView, LoginRequiredMixin):
    template_name = 'year.html'
    date_field = 'workday'
    model = Entry
    allow_future = True
    allow_empty = True

    # def is_leap_year(self):
    #     return c.isleap(self.year)

    def get_context_data(self, **kwargs):
        print("self.year in get_context_data:", self.year)  # Debug
        print("self.kwargs:", self.kwargs)  # Debug URL parameters
        context = super().get_context_data(**kwargs)
        # context['is_leap_year'] = self.is_leap_year()
        context['bla'] = self.year

        return context

I want to have a context variable that knows whether the current year is a leap year. When calling the view, I get this output in the console:

self.year in get_context_data: None
self.kwargs: {'year': 2025}

I have not overwritten get_year(). But the view’s year remains None. Any suggestions?

Side note: Mixins need to appear before the base class in views. In other words, your view definition should be:
class YearView(LoginRequredMixin, YearArchiveView):

The self.year instance variable is not set by url parameters. It is only set in the __init__ method, which means it would be set by a url definiton parameter.

To access the year within the view, you need to call get_year.

For a complete description of the process involved here, I suggest reading the full code at YearArchiveView -- Classy CBV, in particular the get_year method.

1 Like

Thanks for the link Ken. That made it very obvious how it is intended.