Search code examples
djangourldjango-urlsurl-parameters

Django urls multiple parameters matching to wrong pattern


My goal is to create a url structure where simply inputting mywebsite.com/apple/ would return c_one, and inputting mywebsite.com/apple/homepage would return c_two with company=apple and pagetype=homepage.

However, the url mywebsite.com/apple/homepage is returning c_one and considers company to be "apple/homepage".

My code is below, let me know if there is any way around this issue for urls to realize that there are two variables if a slash is used. Thank you!

url(r'^c/(?P<company>[\w|\W]+)/$', views.c_one, name='c_one'),
url(r'^c/(?P<company>[\w|\W]+)/(?P<pagetype>[\w|\W]+)/$', views.c_two, name='c_two'),
url(r'^c/(?P<company>[\w|\W]+)/(?P<pagetype>[\w|\W]+)/(?P<topic>[\w|\W]+)/$', views.c_three, name='c_three')

Solution

  • The problem lies in your definition of the patterns.

    With using both, \w and \W you're basically saying any given character.

    According to Wikipedia the definition of \w is [A-Za-z0-9_] and the definition of \W is [^A-Za-z0-9_]. Basically \W is the complement of \w, so you're matching any character.

    Modify your config like this and it should work:

    url(r'^c/(?P<company>\w+)/$', views.c_one, name='c_one'),
    url(r'^c/(?P<company>\w+)/(?P<pagetype>\w+)/$', views.c_two, name='c_two'),
    url(r'^c/(?P<company>\w+)/(?P<pagetype>\w+)/(?P<topic>\w+)/$', views.c_three, name='c_three')