Django - 实⽤URL模式列表

技巧部分是正则表达式。我准备了⼀个最常⽤的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'}

具体更多有关正则表达式的匹配细节见链接:List of Useful URL Patterns

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值