简体   繁体   中英

Django url pattern order and regex

There is something I can't understand which is happening with my app. This is what django documentation says.

  1. Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.

This is my url pattern which works.

urlpatterns = patterns('',

    #rosa
    url(r'^league/(.+)/rose/$','fantacalcio.views.rose',name='rose'),
    #league page
    url(r'^league/(.+)/$', 'fantacalcio.views.league_home',name='league_home'),  
)

This is my url pattern which I expected to work:

urlpatterns = patterns('',

    #league page
    url(r'^league/(.+)/$', 'fantacalcio.views.league_home',name='league_home'),   
    #rosa
    url(r'^league/(.+)/rose/$','fantacalcio.views.rose',name='rose'),  
)

but that instead gives me this error:

ValueError at /league/1/rose/
invalid literal for int() with base 10: '1/rose'

This is happening because /league/1/rose/ stops at league/1/ , doesn't move to the next url, as far as I understand. I don't get why, since on django documentation I can find this example:

urlpatterns = patterns('',
    url(r'^articles/2003/$', 'news.views.special_case_2003'),
    url(r'^articles/(\d{4})/$', 'news.views.year_archive'),
    url(r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
    url(r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
)

What am I missing?

Because the pattern (.+) matches 1/rose . You're not limiting it to just alphanumeric characters, so it grabs everything.

You already know that swapping the order of the regexes works. But you probably want to limit what it matches, in any case. If you're only expecting numeric IDs, this would be better:

'^league/(\d+)/$'

or you could match alphanumeric chars:

'^league/(\w+)/$'

or even everything except slashes:

'^league/([^/]+)/$'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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