Django URL常用模式匹配大全

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

Primary Key AutoField

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

Slug Field

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

Slug Field with Primary Key

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

Django User Username

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

Year

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

Year / Month

Regex (?P[0-9]{4})/(?P[0-9]{2})
Example url(r'^articles/(?P[0-9]{4})/(?P[0-9]{2})/$', views.month_archive, name='month')
Valid URL /articles/2016/01/
Captures {'year': '2016', 'month': '01'}

你可能感兴趣的:(Django URL常用模式匹配大全)