Django set default empty url

1.2k Views Asked by At

I'm trying to learn Django and I'm following Corey Shafer's tutorials (https://www.youtube.com/watch?v=a48xeeo5Vnk), but when I try to make two different pages, I get automatically directed to the one with an "empty address":

In his:

/Blog /urls.py

it looks like this:

from django.conf.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='blog-home'),
    path('about/', views.about, name='blog-about'),

]

and when he goes to localhost:8000/blog/about, the page displays correctly

When I try to imitate his code for blog/urls.py:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'', views.home, name='blog-home'),
    url(r'^about/', views.about, name='blog-about'),
]

the result of the localhost:8000/blog/about is the content of views.home, and not views.about.

The following works correctly, when I write a name instead of an empty string:

urlpatterns = [
    url(r'^home', views.home, name='blog-home'), 
    url(r'^about/', views.about, name='blog-about'),

]

But I don't understand why it worked in a previous version, why it won't work now, and what could fix it

1

There are 1 best solutions below

0
willeM_ Van Onsem On BEST ANSWER

A url matches if it can find a substring that matches, the empty string r'' thus matches every string.

You should make use of anchors to specify the start (^) and end ($) of the string:

urlpatterns = [
    #     ↓ ↓ anchors
    url(r'^/$', views.home, name='blog-home'),
    url(r'^about/', views.about, name='blog-about'),
]

Note: As of , url(…) [Django-doc] is deprecated in favor of re_path(…) [Django-doc]. Furthermore a new syntax for paths has been introduced with path converters: you use path(…) [Django-doc] for that.