Tip: Reuse Django view in urlconf

djangopython

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[\d\w]{10})$', views.detail) , # ISBN
    (r'^books/(?P[\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)