Class-based Generic Views: patterns and anti-patterns


couldn’t keep up with his code samples


Blog posts last week

  • Luke Plant
  • Nick Coghlan

What are views in Django?

“A view is a callable that takes a requests and returns a response”


  • Functional views are not deprecated
  • Generic functional views are

Pre Django-1.3 Django CBVs

  • Admin
  • RSS feeds
  • Sitemaps


class View(Object):

    def as_view(cls, **init):
        def view(request, *args, **kwargs):
            self = cls(**init)
            return self.dispatch(request, *args, **kwargs)

    # TODO find the rest

Declarative vs Imperative

  • CBVs have a much steeper learning curve
  • is a handy resource

Usage Tips for Django CBVs

  • try to keep for URL definition and nothing else
  • Keep decorators in views.oy


# TODO show Python 2.7 version here

class MyView(generic.ListView):
# Complete this

MRO, extend, don’t override

Unless you’re 100% sure of what you’re doing

Case Studies

Useful recipes

Form processing

TODO - get the form processing example

Nested Navigation

# TODO - get example


from le_social.registration import views

class Register(views.Register):
    form_class = blah

# TODO get example


Don’t set so many settings:

from le_social.registration import views

class Activate(views.Activate):
    expires_in = 3600 * 24 * 7 # 7 days

Shooting yourself in the foot

The problems with using CBVs

The 500 Error

class Handler500(generic.TemplateView):
    template_name = '500.html'

No matter what goes into this, it will throw out blank pages.