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
)

Then in detail, using the magic kwargs to bring the information in:

def detail(request, **kwargs):
  book_qs = Book.objects.filter(**kwargs)
Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks

One Comment to “Tip: Reuse Django view in urlconf”

  1. BartekNo Gravatar | January 12th, 2009 at 4:19 am

    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.

Leave a Comment

This site is using OpenAvatar based on