1

I'm trying to get my head around regexp in Django urls. I'm currently developing locally and I want to be able to direct a request such as http://localhost:8000/options/items/item-string-1121/ to the 'details' view in my app called 'options', passing in the final number part of the request string (1121) as a parameter 'id' to the view function.

The signature for details in options/views.py is as follows, taking id=1 as default:

def details(request, id=1):
    ...

I have the following in my root urls.py:

...

urlpatterns += patterns('',
    url(r'^options/, include(options.urls')),
)

and in options/urls.py:

urlpatterns = patterns('options.views', 
    url(r'^items/(.+)(P<id>\d+)/$', 'details'),
    ...
)

Now when I try to request the above URL the dev server says it tried to match against the pattern ^options/ ^items/(.+)(P<id>\d+)/$ but it doesn't match.

Can anyone see the problem?

1
  • There is not need to capture unnamed group, r'^items/.+-(?P<id>\d+)/$' is fine. Commented Apr 28, 2012 at 18:43

2 Answers 2

3

You need a non-greedy quantifier on the (.+), so r'^items/(.+?)(P\d+)/$'. Otherwise that first glob happily eats until the end of the string, preventing the ID from ever matching.

Sign up to request clarification or add additional context in comments.

4 Comments

Makes sense, but it's still not matching.. I just get a 404
Ahh, and that should also be (?P<id>), thats the more important one :-)
ok, that got it.. not sure what that second ? is for but thanks! :)
(?P<name>...) marks a named capture, in general most special types of capture groups start with (?
0

You are missing quotes.

urlpatterns += patterns('',
    url(r'^options/, include(options.urls')),
)

Should be

urlpatterns += patterns('',
    url(r'^options/', include('options.urls')),
)

I'm not too sure of your expression, might try this:

urlpatterns = patterns('options.views', 
    url(r'^items/(?<=-)(?P<id>\d+)/$', 'details'),
    ...
)

1 Comment

The part between / and (?P...) does not get matched hence no match for whole

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.