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
importthe 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 thepartialmethod in Python 2.5’s functools module, or thecurrymethod 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.