psychok7
psychok7

Reputation: 5463

django urls regular expressions

So i have a main urls.py that looks like this:

    urlpatterns = patterns('',
(r'^users/(?P<username>.*)/', include('app.urls')), 
url(r'^users/(?P<username>.*)$',direct_to_template,{'template':'accounts/profile.html'}, name='profile'),)

and a app.urls.py

urlpatterns = patterns('',url(r'^app/create/$', create_city ,name='create_city'),)

my problem is, when i localhost:8000/users/michael/app/create/ it doesn't call my view. I have tried changing the order of the urls with no luck so i believe my problem is with the regular expressions but with no idea on what to change, anyone?

Upvotes: 0

Views: 4089

Answers (1)

Alasdair
Alasdair

Reputation: 308769

The named group (?P<username>.*) will match any characters, zero or more times. in your username, including forward slashes.

In url patterns, it would be more common to use (?P<username>[-\w]+). This would match at least one character from the set of lowercase a-z, uppercase A-Z, digits 0-9 hyphens and underscores.

I also recommend that you add a trailing slash to your pattern for your profile view.

Putting it all together, I suggest you use the following as a starting point for your urls.py:

urlpatterns = patterns('',
   url(r'^users/(?P<username>[-\w]+)/$',direct_to_template, {'template':'accounts/profile.html'}, name='profile'), 
   (r'^users/(?P<username>[-\w]+)/', include('app.urls')), 
)

Upvotes: 1

Related Questions