Skip to content

Instantly share code, notes, and snippets.

@DanThomson
Last active August 30, 2015 22:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanThomson/e643354cd27f41a2a2ac to your computer and use it in GitHub Desktop.
Save DanThomson/e643354cd27f41a2a2ac to your computer and use it in GitHub Desktop.
Better django urls
#This is a work in progress.
from django.conf.urls import patterns, url
from view_file_name import my_view
def kwarg(kwarg_name, kwarg_regex=r'[a-z0-9-]+'):
"""
:param kwarg_name: The key to which this kwarg will be assigned
:param kwarg_regex: The regular expression the keyword's value must match
:returns: A string which can be used to add a keyword to a django url
Keyword argument format is r'(?P<{kwarg_name}>{kwarg_regex})/'
"""
return r'(?P<{kwarg_name}>){kwarg_regex})/'.format(kwarg_name=kwarg_name, kwarg_regex=kwarg_regex)
year_regex = r'\d\d\d\d|\d\d' # accept either two digit year or four digit year
month_regex = r'\d{1,2}'
day_regex = r'\d{1,2}'
year = kwarg('year', year_regex)
month = kwarg('month', month_regex)
day = kwarg('day', day_regex)
urlpatterns = patterns('calendar',
#url(regex, view_function, name='url.name'),
url('^events/' + year + month + day + '?$', my_view_func, name='events')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment