Django 的 slug url 正则匹配

 

如果按照 .* 去匹配,最后会把 /edit/ 和 /delete/ 也匹配进去。

urlpatterns = [
    #...
    url(r'^(?P<slug>.*)/$', post_detail, name='detail'),
    url(r'^(?P<slug>.*)/edit/$', post_update, name='update'),
    url(r'^(?P<slug>.*)/delete/$', post_delete),
]

所以使用 [-\w+] 表示匹配 - 符号(短横线 hyphen),以及所有小写的英文字母。

urlpatterns = [
    #...
    url(r'^(?P<slug>[-\w]+)/$', post_detail, name='detail'),
    url(r'^(?P<slug>[-\w]+)/edit/$', post_update, name='update'),
    url(r'^(?P<slug>[-\w]+)/delete/$', post_delete),
]

 

 

参考:

https://www.jianshu.com/p/8207b66db9ca

https://www.cnblogs.com/yang-wei/p/9997776.html

 

 

 

猜你喜欢

转载自www.cnblogs.com/sea-stream/p/11518143.html
今日推荐