django获取不到特定链接

python日常踩坑系列

按照教程方式打开本地特定链接报错
源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
from django.conf.urls import url
from . import views

urlpatterns = [

url(r'^$', views.index, name='index'),

# Show all topics.
url(r'^topics/$', views.topics, name='topics'),

# Detail page for a single topic.
url(r'^topics/(?P<topic_id>d+)/$', views.topic, name='topic'),
]

打开http://127.0.0.1:8000/topics/1/报错:

1
2
3
4
5
6
 Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order:
1. admin/
2. [name='index']
3. topics [name='topics']
4. topics/?P<topic_id>d+/ [name='topic']
The current path, topics/1/, didn't match any of these.

原因:

Django2.0有更新
对于django.urls.path()函数,允许有简单的表示方法:

url(r’^articles/(?P[0-9]{4})/$’, views.year_archive),

可以写成:

path(‘articles//‘, views.year_archive),

所以代码可更改为:

1
2
3
4
5
6
7
8
9
10
11
12
13
from django.urls import path
from . import views

app_name = 'lerning_logs'
urlpatterns = [
#主页
path('', views.index, name='index'),
#显示所有主题
path('topics', views.topics, name='topics'),
#特定主题的详细页面
#path('topics/?P<topic_id>d+/', views.topic, name='topic'),
path('topics/<topic_id>/', views.topic, name='topic'),
]