一、路徑的匹配

from django.contrib import admin from django.urls import path from index import views urlpatterns = [ path('articles/2003/', views.special_case_2003), path('articles/<int:year>/', views.year_archive), path('articles/<int:year>/<int:month>/', views.month_archive), path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail), ]

from django.http import HttpResponse def special_case_2003(request): return HttpResponse("This is the special 2003") def year_archive(request,year): return HttpResponse("This is year archive,Year number is %d" % year) def month_archive(request,year,month): return HttpResponse("This is month archive,It's %d year %d month" %(year,month)) def article_detail(request,year,month,slug): return HttpResponse("This is month articl details,It's %d year, %d month,slug is %s" %(year,month,slug))
1.由/分開,獲取參數用尖括號,可以指定類型
2.路徑后面一定要有/不然匹配不到任何路徑
3.傳遞給視圖函數view包含的參數有request實例以及路徑中獲取到的參數
4.順序匹配
二、轉換器
尖括號內的東西有以下幾類
- str,匹配除/的非空字符串,未指定轉換器默認
- int,匹配整形
- slug, 匹配任意由 ASCII 字母或數字以及連字符和下划線組成的短標簽
- uuid,這個不知道干啥的
- path,匹配包含/的非空字段
path('articles/<path:anythings>/',views.anythings)
def anythings(request,anythings): return HttpResponse("match nonthing above,your input is %s" % anythings)
訪問http://127.0.0.1:8000/articles/mylove/hello/check/
響應match nonthing above,your input is mylove/hello/check
三、自定義轉換器

class FourDigitYearConverter: regex = '[0-9]{4}' def to_python(self, value): return int(value) def to_url(self, value): return '%04d' % value
from django.urls import path,register_converter
register_converter(converter.FourDigitYearConverter,'yyyy')
查看register_converter文件可以看到django規定的集中默認的轉換器的規則,regex是匹配到的正則表達值。
to_python 是前段往后端python程序傳的類型或值,可以在這里做特殊轉換
四、正則表達式轉換器
path---> re_path
轉換器寫法: (?P<匹配后參數名>正則表達式)
例如:re_path('articles/?P<year>[0-9]{4}/$',views.function)
五、include
將同類的url指定到app里的urlconf。