Tip: Reuse Django view in urlconf
Python, Web January 11th, 2009
The Pro Django introduces a convenient way to reuse the way: fill an optional dictionary object to feed extra information.
We may extend this trick a little bit further. Book model has two unique fields, isbn and ean. They are essential the same except the queried field. We can reuse the view by categorizing the request by the length:
urlpatterns = patterns(”,
(r‘^books/(?P<isbn>[\d\w]{10})$’, views.detail) , # ISBN
(r‘^books/(?P<ean>[\d\w]{13})$’, views.detail), # EAN
)
(r‘^books/(?P<isbn>[\d\w]{10})$’, views.detail) , # ISBN
(r‘^books/(?P<ean>[\d\w]{13})$’, views.detail), # EAN
)
Then in detail, using the magic kwargs to bring the information in:
def detail(request, **kwargs):
book_qs = Book.objects.filter(**kwargs)
book_qs = Book.objects.filter(**kwargs)







Hah, great idea and another reason why Python is awesome!
I already know a few spots in my own projects where this could be implemented.