Skip to content

Instantly share code, notes, and snippets.

@killown
Last active November 19, 2017 13:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save killown/13b93c3330b4589cf0f93f0868fa5b08 to your computer and use it in GitHub Desktop.
Save killown/13b93c3330b4589cf0f93f0868fa5b08 to your computer and use it in GitHub Desktop.
List of Useful URL Patterns (Django)

Primary Key AutoField

Regex: (?P\d+)

url(r'^questions/(?P\d+)/$', views.question_details, name='question_details'),

Match

URL Captures
/questions/0/ {'pk': '0'}
/questions/1/ {'pk': '1'}
/questions/934/ {'pk': '934'}

Won't match URL /questions/-1/ /questions/test-1/ /questions/abcdef/

Slug Fields

Regex: (?P[-\w]+)

url(r'^posts/(?P[-\w]+)/$', views.post, name='post'),

Match

URL Captures
/posts/0/ {'slug': '0'}
/posts/hello-world/ {'slug': 'hello-world'}
/posts/-hello-world_/ {'slug': '-hello-world_'}

Won't match URL /posts/hello world/ /posts/hello%20world/ /posts/@hello-world*/ Slug with Primary Key

  Regex: (?P<slug>[-\w]+)-(?P<pk>\d+)

url(r'^blog/(?P[-\w]+)-(?P\d+)/$', views.blog_post, name='blog_post'),

Match

URL Captures
/blog/hello-world-159/ {'slug': 'hello-world', 'pk': '159'}
/blog/a-0/ {'slug': 'a', 'pk': '0'}

Won't match URL /blog/hello-world/ /blog/1/ /blog/helloworld1/ /hello-world-1-test/ Usernames

  Regex: (?P<username>[\w.@+-]+)

url(r'^profile/(?P[\w.@+-]+)/$', views.user_profile),

Match

URL Captures
/profile/vitorfs/ {'username': 'vitorfs'}
/profile/vitor.fs/ {'username': 'vitor.fs'}
/profile/@vitorfs/ {'username': '@vitorfs'}

Won't match URL /profile/*vitorfs/ /profile/$vitorfs/ /profile/vitor fs/ Dates

Year

  Regex: (?P<year>[0-9]{4})

url(r'^articles/(?P[0-9]{4})/$', views.year_archive)

Match

URL Captures
/articles/2016/ {'year': '2016'}
/articles/9999/ {'year': '9999'}

Won't match URL /articles/999/ Year / Month

Regex: (?P[0-9]{4})/(?P[0-9]{2})

url(r'^articles/(?P[0-9]{4})/(?P[0-9]{2})/$', views.month_archive),

Match

URL Captures
/articles/2016/01/ {'year': '2016', 'month': '01'}
/articles/2016/12/ {'year': '2016', 'month': '12'}

Won't match URL /articles/2016/1/ Year / Month / Day

  Regex: (?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})

url(r'^articles/(?P[0-9]{4})/(?P[0-9]{2})/(?P[0-9]{2})/$', views.article_detail)

Match

URL Captures
/articles/2016/01/01/ {'year': '2016', 'month': '01', day: '01'}
/articles/2016/02/28/ {'year': '2016', 'month': '02', 'day': '28'}
/articles/9999/99/99/ {'year': '9999', 'month': '99', 'day': '99'}

Won't match URL /articles/2016/01/9/ /articles/2016/01/290/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment