Search code examples
djangowagtail

Wagtail view with URL params, or multiple custom URLs


I have a calendar that is used in a general Django app, but I also want to show it within the Wagtail app (which shows general text content/blog) for this site.

I have got to the point where I can display the calendar on the Wagtail page, with some manual entry for the date params. The model for that looks like:

class SchedulePage(PostPageExtras, RoutablePageMixin, Page):

    content_panels = Page.content_panels
    
    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        context['schedule'] = self.get_calendar()
        return context
        
    def get_calendar(self):
        the_year = 2024
        the_month = 7
        cal = ScheduleCalendar().formatmonth(the_year, the_month, withyear=True)
        return cal
        

I have tried to work this out with the RoutablePageMixin but didn’t make any progress. I can generate the_year and the_month values that derive from .now(), so the calendar always shows the current month. But I want the user to be able to navigate to next/previous months.

The way that this is done in the Django app is that there are two urls that point to the same view, and the view interprets the parameters as required:

path('/schedule/', views.ScheduleCalendarView.as_view(), name='control-schedule-calendar'),
re_path(r'^/schedule/(?P<year>\d+)/(?P<month>\d+)/$', views.ScheduleCalendarView.as_view(), name='control-schedule-monthview'), 

With these two URLs you'll get the same page display (at July 2024):

https://example.com/schedule/

https://examle.com/schedule/2024/07/

Because, in the first example, the view creates the the_year/the_month parameters if they are not present in the URL.

There is a third URL, with a different view, that shows the detail for a particular day:

re_path(r'^/schedule/(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/$', views.ControlScheduleDayView.as_view(), name='control-schedule-dayview'),

Which is all fairly easy in regular Django.

I suppose I would like to follow the same pattern, or three URLs, and possibly not need a second view for the day view, there would be some kind of switch if the day parameter was in the URL.

How to do this in a Wagtail model? Alternatively, how to do it in a general Django environment, loading the Wagtail/blog templates and showing the Wagtail/blog navigation?

Thanks in advance.


Solution

  • We do this - in fact this is our second iteration on the same pattern. It was easier to extract the code into a gist: https://gist.github.com/cnk/603c48f6029e033d38e006db6988843a