无名参数
配置 urls ,我们需要导入 url 模块,以()定义一个无名的变量
from django.contrib import admin
from django.urls import path
from blog import views
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
path('userInfo', views.userInfo),
#path('articles/2003/', views.specila_case_2003),
#url(r'^articles/[0-9]{4}/$', views.year_archive),
url(r'^articles/([0-9]{4})/([0-9]{2})$', views.year_archive),
]+ static(settings.STATIC_URL, document_root=settings.STATICFILES_DIRS)
在 views.py 中定义函数, 定义两个形参 y,m 来接收变量
def year_archive(req, y, m):
return HttpResponse(y+" years "+ m + " month")
浏览器访问:http://127.0.0.1:8888/articles/2003/12
有名参数
在 urls.py 中定义
url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})$', views.year_archive),
# 解析:(?P<year>[0-9]{4}) --> ?P<year> 定义一个有名参数 year,正则匹配的是 [0-9]{4}
在 views.py 中修改,这里的形参必须写 urls.py 中所定义的参数名
def year_archive(req, year, month):
return HttpResponse(year+" years "+ month + " month")