attribute: Phillie Casablanca

Notes on urls.py



I was confused for quite some time about how to get multiple generic views in a single urlpatterns definition in the urls.py file.

The examples I had been looking at would define urlpatterns something like this:

[code]

urlpatterns = patterns('django.views.generic.date_based',
(r'^$','archive_index',
{'queryset': Post.objects.all(),
'date_field': 'date',
'allow_empty':True,
}),
)

[/code]

And until today I couldn't figure out how to get multple view types in there.
The first value given to patterns seemed to restrict what views could be used.

Well I finally ran across the documentation (http://www.djangoproject.com/documentation/0.96/url_dispatch/), and apparently that first string entry definition is the view prefix, which just means you can reduce the amount of writing if your using the same base view for all your views.

In other words if you want to use multiple views in the same urlpatterns def you just leave that first value blank:

[code]
urlpatterns = patterns('',
(r'^articles/(\d{4})/$', 'mysite.news.views.year_archive'),
(r'^articles/(\d{4})/(\d{2})/$', 'mysite.news.views.month_archive'),
(r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'mysite.news.views.article_detail'),
)
[/code]

I'm sure its helpfull if your writting a lot of patterns, but it confused me for quite a while.
Maybe if the various examples defined this with "prefix=" I would have caught on earlier without having to dig through the documentation.

monkut // May 28, 2008 // 8:59 p.m.