Djangocon: Demystifying mixins with Django - Ana Balica

Tags: django, djangocon

(One of the summaries of a talk at the 2015 Djangocon EU conference).

Ana Balica talks about mixins. Mixins are ways to add extra behaviour into classes. Mixins aren’t anything special in python. They are just classes.

Mixins are nice for providing modularity. They should have one specific goal and they should not themselves be extended or instantiated.

You could use them for instance to work around copy-pasting code around between classes. Just make a class with the otherwise copy-pasted code.

How do you use it? Python’s multi-inheritance. A class can have multiple parents:

class Foo(SomeMixin, BaseFoo):

In django, mixins are especially useful for class based views. As an example, let’s build a mixin that checks if our users are logged in:

class LoginRequiredMixin(object):

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            raise PermissionDenied
        return super(LoginRequiredMixin, self).dispatch(
            request, *args, **kwargs)

class AboutView(LoginRequiredMixin, TemplateView):
    template_name = 'about.html'

dispatch() is handy to keep in mind. Likewise .get_context_data(). (Note by Reinout: doing something with get_context_data is probably not needed).

How do you discover what’s in django’s class based views? You could look at the source code of django. But looking at is handier.

There are a lot of mixins already written for you, ready for use in django-braces. Like the LoginRequiredMixin!

Go back to your views and start writing mixins to clean up the code!

Holiday picture from the Eifel region logo

About me

My name is Reinout van Rees and I work a lot with Python (programming language) and Django (website framework). I live in The Netherlands and I'm happily married to Annie van Rees-Kooiman.

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):