1

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

Santeau
  • 839
  • 3
  • 13
  • 23
  • 1
    The answer below tells you what you need to know, so I won't add an answer. But if you are learning Django now, I would highly recommend using the latest stable release (currently 3.1). Dango 1.11 isn't even supported anymore, and you'll just find more problems as you go. (Django 1.11 won't even get security updates now) – tim-mccurrach Dec 22 '20 at 00:46

1 Answers1

1

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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555