0

I'm trying to match two strings in an url, but it's not working out likely due to my poor knowledge of regex. I want urls like the following:

  • testserver/username/
  • testserver/username/1234/
  • testserver/username/rewards/

Username would be passed in to the url as a kwarg. Here's what I have:

url(r'^(?P<username>[-\w]+)/$', Posts_Index, name="userposts"),
url(r'^(?P<username>[-\w]+)/photos/$', Photo_Index, name="userphotos"),
url(r'^(?P<username>[-\w]+)/rewards/$', Rewards_Index, name="userrewards"),
url(r'^(?P<username>[-\w]+)/following/$', Follower_Index, name="userfollowers"),
url(r'^(?P<username>[-\w]+)/followers/$', Following_Index, name="userfollowing"),
url(r'^(?P<username>[-\w]+)/(?P<pk>\d+)/$', SinglePost_Index, name="singlepost"),

However, only userposts will be found. If I try to query userphotos or anything below userposts, only the userposts url will be checked, which obviously leads to failure. How can I fix this issue?

user3084860
  • 421
  • 5
  • 19
  • in the rewards url there isn't a `/` symbol at the last. And also to match one or more numbers, you need to use `\d+`, `\d` matches only a single digit. – Avinash Raj Aug 23 '14 at 14:24
  • @AvinashRaj Thanks for spotting that. When you say there isn't a / symbol at the last for the rewards url, I'm assuming you're talking about the desired urls I listed. Then yeah. But in the urlconf, the / is present. Will edit it though, I guess. – user3084860 Aug 23 '14 at 14:30
  • i think `testserver/` would be added automatically. Am i correct? – Avinash Raj Aug 23 '14 at 14:32
  • @AvinashRaj , Correct, I'm just concerned with what comes after testserver – user3084860 Aug 23 '14 at 14:34
  • Post the whole urlpatterns variable please – Bob Aug 23 '14 at 14:58

1 Answers1

0

From the django docs: Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.

Thus if you reverse the order of the urls it should work better.

Jonathan
  • 8,453
  • 9
  • 51
  • 74