Alternate syntax for Django urlpatterns

Django’s urlpatterns variable has traditionally expected callbacks to be specified as strings, and extra arguments (commonly used with generic views) to be passed as a separate dict, for example:


  info_dict = {
    ‘queryset’: Entry.objects.all(),
    ‘date_field’: ‘pub_date’,
  }

  urlpatterns = patterns(‘django.views.generic.date_based’,
    (r‘^(?P<year>\d{4})/$’,   ‘archive_year’,   info_dict),
  )
 

This makes me just a little bit queasy:

  • Representing view methods as strings seem overly indirect, sacrificing some early-warning type safety for little gain. True, you would have to import the view methods or their module, but one import per view module isn’t much of an issue. In r3554 Django adds support for using callables (the view methods themselves) in urlpatterns, so there’s nothing holding you back.

  • Passing view arguments in a dict (info_dict) seems un-pythonic when you could just as well pass them as keyword arguments, though you would need to learn about partial functional application (or currying) as provided by the partial method in Python 2.5’s functools module, or the curry method in Django’s utils.functional module.

The good news is that you don’t have to change anything in Django. You can just start doing it yourself:


  from django.views import generic
  from django.utils.functional import curry 
  kwargs = dict(
    queryset = Entry.objects.all(),
    date_field = ‘pub_date’,
  )
  urlpatterns = patterns(‘’,
    (r‘^(?P<year>\d{4})/$’,   curry(generic.archive_year, **kwargs)),
    …
  )
 

In the end it comes down to personal preference. I just thought I’d throw these options out there.

Share it on...
del.icio.us  Digg it  Netscape  Newsvine  reddit  StumbleUpon  Yahoo MyWeb  

Leave a Reply


tracker