0

I'm following a tutorial, and am getting an 404 error that http://127.0.0.1:8000/restaurants/ is not being matched by

url(r'^restaurants/(?P<slug>\w+)/$', RestaurantListView.as_view())

while http://127.0.0.1:8000/restaurants/x with any x is. How should I rewrite the path to match the url without any additional /x?

... Error message:

Using the URLconf defined in projekt.urls, Django tried these URL patterns, in this order:
admin/
^contact/$
^$
^about/$
^restaurants/(?P<slug>\w+)/$
The current path, restaurants/, didn't match any of these.
waterlemon
  • 158
  • 1
  • 7

2 Answers2

1

In django 2

path('restuarants/',RestaurantListView.as_view())

In django 1

url(r'^restaurants/$', RestaurantListView.as_view())
Ali
  • 2,541
  • 2
  • 17
  • 31
1

Your regex is matches restaurants/ at the start of input, then captured any 1+ word chars into a group "slug" and then requires and matches / at the end of the string ($ is the end of string anchor.)

You need to wrap the optional part with an optional non-capturing group:

r'^restaurants/(?:(?P<slug>\w+)/)?$'
               ^^^              ^^

The regex matches:

  • ^ - start of input
  • restaurants/ - a literal restaurants/ substring
  • (?: - start of a non-capturing group matching...
    • (?P<slug>\w+) - 1+ word chars captured into a slug group
    • / - a / char
  • )? - ... end of the non-capturing group matches 1 or 0 times
  • $ - end of input.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563