urls.py
urlpatterns = [ path('admin/', admin.site.urls), path('articles/2020/', views.special_case_2020), # 无名分组,按位置传参 re_path('^articles/([0-9]{4})/$', views.articles_year), # 有名分组, 按关键字传参 re_path("^articles/(?P<year>[0-9]{4})/$", views.articles_year), #无名分组,年月 # re_path("^articles/([0-9]{4})/([0-9]{2})/$", views.articles_y_m), # 有名分组, 年月 re_path("^articles/(?P<y>[0-9]{4})/(?P<m>[0-9]{2})/$", views.articles_y_m), ]
views.py
from django.shortcuts import render, HttpResponse, redirect from django.urls import reverse def special_case_2020(request): print("special_case_2020") return HttpResponse("special_case_2020") def articles_year(request, year): # 无名分组,按照位置传参 print("articles_%s" % year) return HttpResponse("articles_%s" % year) def articles_y_m(request, y, m): return HttpResponse("%s年-%s月" % (y, m))