0

Its is easy to create URL pattern as below

url(r'^member/(?P<member_name>[a-z]+)/$', views.get_member, name='get_member'),

this will generate the complete url as http://example.com/member/john/ but I want to make urls like http://example.com/john/. What URL pattern should I make for this? If I do

url(r'^(?P<member_name>[a-z]+)/$', views.get_member, name='get_member'),

it will start matching all other urls in it.

1 Answer 1

3

You are correct adding a url such as url(r'^(?P<member_name>[a-z]+)/$', views.get_member, name='get_member') will match all urls. What matters will be the order the URLs appear in.

In your urls.py file place your get_member url at the bottom of the urls.py url list.

This way it will be the last pattern to be matched.

For example the following url patterns will match:

  • articles/
  • articles/2003
  • john/
  • steve/

    urlpatterns = [
        url(r'^articles/2003/$', views.special_case_2003),
        url(r'^articles/([0-9]{4})/$', views.year_archive),
        url(r'^(?P<member_name>[a-z]+)/$', views.get_member, name='get_member')
    ]
    

Now there could be some possible problems which you may or may not be aware of. What if a user joins your site with the name articles? The Url will match on the first url instance. This means the "article" user will never be able to access there profile.

To get around this problem you are going to have to have a number of restricted usernames which cannot be used. You will also need to make sure any new pages you add into your site do not conflict with an already created user name.

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

Comments

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.