super9
super9

Reputation: 30111

Django url regex question

I have the following url

url(r'^(?P<name>[A-Za-z0-9-]+)/$', 'user', name='user')

This matches URLS like /tom/ and /tom-max/ but not on URL's like /tom-2/ or tom-brandy-monster which I want.

Basically I would like to capture a combination of hyphens, letters and numbers.

UPDATE

This is in my urls.py

urlpatterns = patterns('',
    url(r'^$', 'homepage.views.home', name='home'),
    url(r'^user/', include('users.urls')),
    url(r'^plans/', include('plans.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

This is in my users/urls.py

urlpatterns = patterns(
    'users.views',
    url(r'^(?P<user>[A-Za-z0-9-]+)/$', 'user', name='user'), 
)

UPDATE2

The fault was in my views. This regex works for all the above-mentioned examples.

Upvotes: 1

Views: 1366

Answers (1)

Chris Morgan
Chris Morgan

Reputation: 90752

What you have there will match all of these that you have specified (see below). You should check to make sure that (a) you don't have a URL pattern which will match earlier and (b) that this one is being included (one common culprit is using urlpatterns = ... rather than urlpatterns += ... after initialising it).

>>> import re
>>> urlpattern = re.compile(r'^(?P<name>[A-Za-z0-9-]+)/$')
>>> urlpattern.match('tom/').group('name')
'tom'
>>> urlpattern.match('tom-max/').group('name')
'tom-max'
>>> urlpattern.match('tom-2/').group('name')
'tom-2'
>>> urlpattern.match('tom-brandy-monster/').group('name')
'tom-brandy-monster'

Upvotes: 4

Related Questions