Search code examples
djangodjango-viewsdjango-generic-views

Default to current month in MonthArchiveView


I have an MonthArchiveView for events on my site. How can I make the archive default to the current month instead of raising an exception, when no year and month is submitted (e.g. if a user visits just /events/?

# urls.py
url(r'^events/$', EventMonthView.as_view(), name="event_month"),
url(r'^events/(?P<year>[0-9]{4})/(?P<month>[0-9]+)/$', EventMonthView.as_view(month_format='%m'), name="event_month"),

#views.py
class EventMonthView(MonthArchiveView):
    template_name = "events.html"
    queryset = Event.objects.all()
    date_field = "date"
    allow_future = True
    month_format='%m'
    year_format='%Y'

Solution

  • You could override the get_month and get_year methods so they return a default value:

    from django.http import Http404
    from django.utils.timezone import now
    from django.views.generic import MonthArchiveView
    
    
    class EventMonthView(MonthArchiveView):
        # ...
    
        def get_month(self):
            try:
                month = super(EventMonthView, self).get_month()
            except Http404:
                month = now().strftime(self.get_month_format())
    
            return month
    
        def get_year(self):
            try:
                year = super(EventMonthView, self).get_year()
            except Http404:
                year = now().strftime(self.get_year_format())
    
            return year