Chris Pickett

Beautiful URL Patterns

Python > Django | Sept. 13, 2013, 7:08 a.m. | 1 min read

Make your Django url configs just a little prettier with kwargs.

I'm always looking for some way to make my code just a little more readable and while I love Django, I've always thought that one of the ugliest parts of it is the urls.py, specifically the url specification:

url(r'^(?P<slug>[\w-]+)/$', ProjectDetail.as_view(), name='projects_project_detail'),

Which is okay on it's own but when you get several of them in a file it can be difficult to see exactly what's going on. Recently I've taken to passing in keyword arguments to url. The url method accepts five keyword arguments:

url(
    regex=r'...',
    view=MyView.as_view(),
    kwargs=None,
    name=app_model_action,
    prefix=''
)

Using this we can re-write the first example as:

url(
    regex=r'^(?P<slug>[\w-]+)/$',
    view=ProjectDetail.as_view(),
    name='projects_project_detail',
),

I think that this is far more readable, especially since it puts the regex on its own line. This also works for includes, but can be a bit more confusing, because the include(...) is passed in to the url function as the view:

url(
    regex=r'^blog/$',
    view=include('blog.urls'),
),

Comments

comments powered by Disqus