Django URL常用模式匹配大全

Django 中的正则表达式技巧。这个列表有很多常用的模式。需要时可以查看。

Primary Key AutoField

Regex (?P<pk>\d+)
Example url(r'^questions/(?P<pk>\d+)/$', views.question, name='question')
Valid URL /questions/934/
Captures {'pk': '934'}

Slug Field

Regex (?P<slug>[-\w]+)
Example url(r'^posts/(?P<slug>[-\w]+)/$', views.post, name='post')
Valid URL /posts/hello-world/
Captures {'slug': 'hello-world'}

Slug Field with Primary Key

Regex (?P<slug>[-\w]+)-(?P<pk>\d+)
Example url(r'^blog/(?P<slug>[-\w]+)-(?P<pk>\d+)/$', views.blog_post, name='blog_post')
Valid URL /blog/hello-world-159/
Captures {'slug': 'hello-world', 'pk': '159'}

Django User Username

Regex (?P<username>[\w.@+-]+)
Example url(r'^profile/(?P<username>[\w.@+-]+)/$', views.user_profile, name='user_profile')
Valid URL /profile/vitorfs/
Captures {'username': 'vitorfs'}

Year

nRegex (?P<year>[0-9]{4})
Example url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive, name='year')
Valid URL /articles/2016/
Captures {'year': '2016'}

Year / Month

Regex (?P<year>[0-9]{4})/(?P<month>[0-9]{2})
Example url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive, name='month')
Valid URL /articles/2016/01/
Captures {'year': '2016', 'month': '01'}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容