技巧部分是正则表达式。我准备了⼀个最常⽤的URL patterns的列表。当你需要⼀个特定的URL时你可以参考这个列表:
1.主键自增字段:Regex: (?P<pk>\d+)
url(r'^questions/(?P<pk>\d+)/$', views.question_details, name='question_details'),
URL | 捕获 |
/questions/1/ | {'pk': '1'} |
/questions/23/ | {'pk': '23'} |
/questions/102/ | {'pk': '102'} |
2.Slug字段:Regex: (?P<slug>[-\w]+)
url(r'^posts/(?P<slug>[-\w]+)/$', views.post, name='post'),
URL | 捕获 |
/posts/0/ | {'slug': '0'} |
/posts/hello-world/ | {'slug': 'hello-world'} |
/posts/-hello-world_/ | {'slug': '-hello-world_'} |
3.有主键的Slug字段:Regex: (?P<slug>[-\w]+)-(?P<pk>\d+)
url(r'^blog/(?P<slug>[-\w]+)-(?P<pk>\d+)/$', views.blog_post, name='blog_post'),
URL | 捕获 |
/blog/hello-world-159/ | {'slug': 'hello-world', 'pk': '159'} |
/blog/a-0/ | {'slug': 'a', 'pk': '0'} |
4.Django⽤户名:Regex: (?P<username>[\w.@+-]+)
url(r'^profile/(?P<username>[\w.@+-]+)/$', views.user_profile),
URL | 捕获 |
/profile/xuedinge/ | {'username': xuedinge} |
/profile/xuedinge.fs/ | 'username': xuedinge.fs} |
/profile/@xuedinge/ | 'username': @xuedinge} |
5.Year:Regex: (?P<year>[0-9]{4})
url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
URL | 捕获 |
/articles/2019/ | {'year': '2019'} |
/articles/9999/ | {'year': 9999} |
6.Year/Month:Regex: (?P<year>[0-9]{4})/(?P<month>[0-9]{2})
url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
URL | 捕获 |
/articles/2019/01/ | {'year': '2019', 'month': '01'} |
/articles/2019/12/ | {'year': '2019', 'month': '12'} |