Djangocon: Django class based views - Leonardo Giordani

Tags: djangocon, django

(One of the summaries of a talk at 2014 djangocon.eu)

Leonardo Giordani gives a survival guide for novices on django’s class based views: what they are and how they work.

What are they? Django views based on python classes. For many this translates into some django stuff based on some python magic. If you followed the tutorial but don’t exactly understand what a view is, class based views can be quite hard to understand.

A view is the part of django that gets the request and returns a response. Views used to be monolithic functions. A request comes in and a response goes out. It is hard to replace one specific part of it. If you could split it up, you could replace the individual parts.

Object oriented programming (so: classes) is a good way to split up something that’s monolithic into several separate methods on an object. That’s what django’s class based views do.

In the case of class based views, it is worth your time to actually read django’s source code. Get familiar with the details, it helps you understand what happens.

  • First the as_view() method you see in the urls.py: url(... SomeView.as_view()). It makes sure your view class can be used as a regular django function based view.

  • Upon an incoming request, it calls dispatch() that simply calls a method named after the kind of request (post() for a POST request, get() for a GET, etc).

  • A get() again calls get_context_data(), that you for instance can override to return what you want in your template’s context.

It goes deeper and deeper. Automatic query sets, form handling, whatever. And every small piece can be changed by you. You still keep all the rest of the functionality and only change what you need to.

Handy: if you extracted arguments or keyword arguments in your url, you can access them inside your views as self.args and self.kwargs.

Several of the provided base classes deal with CRUD (create/replace/update/delete) operations. get(), post(), etc. This makes it easy to work with. Ever seen the regular if request.method == 'POST' in a form-handling page? No need to do that anymore as get() and post() do the right thing. And both methods use the same methods and attributes to give you your form or the model you’re working on.

In case you need to delve in to the class hierarchy, look at http://ccbv.co.uk.

For a simpler class hierarchy, look at django vanilla views.

 
vanrees.org logo

Reinout van Rees

My name is Reinout van Rees and I program in Python, I live in the Netherlands, I cycle recumbent bikes and I have a model railway.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):