简体   繁体   English

如何使Django url正则表达式不包含所有单词?

[英]How can I make Django url regular expression not to catch all words?

This is my project's url patterns : 这是我项目的网址格式:

urlpatterns = [
    # ex) /snu/
    url(r'^$', views.site_list, name='site_list'),

    # ex) /snu/cse/
    url(r'^(?i)(?P<site_name>[a-zA-Z]+)/$', views.post_list, name='post_list'),

    # ex) /snu/cse/post/3
    url(r'^(?i)(?P<site_name>[a-zA-Z]+)/post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),

    # ex) /snu/cse/post/3/remove
    url(r'^(?i)(?P<site_name>[a-zA-Z]+)/post/(?P<pk>\d+)/remove/$', views.post_remove, name='post_remove'),

    # ex) /snu/upload
    url(r'^(?i)upload/$', views.upload, name='upload'),
]

Unfortunately, r'^(?i)(?P<site_name>[a-zA-Z]+)/$' catches everything so /snu/upload doesn't work as I expected. 不幸的是, r'^(?i)(?P<site_name>[a-zA-Z]+)/$'捕获了所有内容,因此/snu/upload无法正常工作。

Something like r'^(?i)(?P<site_name>[a-zA-Z]+)/upload$' might works, but I don't want it. 类似于r'^(?i)(?P<site_name>[a-zA-Z]+)/upload$'可能有用,但我不希望这样。 It should be r'^(?i)upload/$' . 应该是r'^(?i)upload/$' Any ideas? 有任何想法吗?

The order matters in pattern matching for URL dispatcher. 顺序对于URL调度程序的模式匹配很重要。 The first match is resolved and returned. 第一次比赛解决并返回。

Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL. Django按顺序运行每个URL模式,并在与请求的URL匹配的第一个停止。

So you might want to move the "specific" patterns higher up. 因此,您可能希望将“特定”模式向上移动。

In other words, move 换句话说,移动

# ex) /snu/upload
url(r'^(?i)upload/$', views.upload, name='upload'),

to the second position. 到第二个位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM