A Note About the Site Root

Django does nothing special with the site root (/)—it’s just another URL. In fact, if you go to your browser and try to navigate to http://127.0.0.1:8000/ now, Django will throw an HTTP 404 (Not found) error.

This is because when we updated our events app’s urls.py file, we removed the mapping to the root directory (''). Let’s fix that by adding the root mapping back to urls.py (change in bold):

  1. # \myclub_root\events\urls.py
  2. 1 from django.urls import path, re_path
  3. 2 from . import views
  4. 3
  5. 4 urlpatterns = [
  6. 5 path('', views.index, name='index'),
  7. 6 re_path(r'^(?P<year>[0-9]{4})/(?P<month>0?[1-9]|1[0-2])/', views.index, name='index'),
  8. 7 ]

This is simple enough—I’ve added the same URL configuration for the root URL we used back at the beginning of this chapter. But, we’re not finished: if you navigate to the root now, your browser is going to look like Figure 5.5.

A Note About the Site Root - 图1

Figure 5-5: The index view requires the year and month arguments.

This error occurs because the index view requires the year and month arguments to render the calendar. As there are no arguments to capture from the root URL, the call fails.

We solve this problem by using default arguments. Make the following small change (in bold) to the index function definition:

  1. # \myclub_root\events\views.py
  2. # ...
  3. def index(request, year=date.today().year, month=date.today().month):
  4. # ...

In this change, we are setting the default values for year and month to the current year and month. This way, if you don’t pass the year and month to the index function, Django will default to showing the current month. You can try this out in your browser—if you navigate to http://127.0.0.1:8000/, your browser will display the current month in the calendar.