An Introduction to Django's Loose Coupling

July 22, 2008. Filed under django 72

One of Django's core design philosophies is that of loose coupling. This is one of the best parts of Django, but its also something that takes some time and exposure before its value (and how to take advantage of it) really clicks. This short string of tutorials will begin by briefly examining what Django's loose coupling philosophy means and why its advantageous for those of us building with Django, and will then continue with a handful of small example projects that look at how to replace individual pieces of the Django stack.

What it Means

Loose coupling means that individual components of Django's feature stack are kept as separate as possible. For example, Django templating language makes it very pleasant to represent the contents of your models, but its equally easy to use Django's templating language to represent other kinds of Python objects as well. The Django ORM makes it easy to setup and access a database, but it possible to use SQLAlchemy instead.

This makes it easier to integrate Django applications with legacy apps, but more importantly it lets you use the tools you are familiar with, and the tools that are most suited for your specific problem. Often new developers who come to Django dislike part of the Django toolkit, and submit suggestions to make Django function more similarly to the frameworks and tools they are already familiar with. However, the Django solution is both extremely simple and extremely powerful: if you prefer other tools, use them.

Django isn't a monolithic tool that descends from the heavens to rule our project, it provides a handful of tools that are willing to cooperate with one another, but are equally willing to cooperate with tools of your own choosing. Developers coming from Ruby on Rails or other extremely opinionated frameworks may be used to following their framework's best practices to avoid fighting against a framework which feels that it knows your project better than you do, but with Django you'll be back in the driver's seat1.

Now, lets start looking at examples of loose coupling in Django by using the Jinga2 template engine to render webpages.

  1. Which seems to be one of the biggest complaints against Django: it doesn't make enough decisions for you. Which, it seems, is actually a fair complaint, since for many projects you simply need to make any decision, and not having to think about it will save time and energy. However, I think you'll find as you get more comfortable with Django that while it will let you make decisions, it will rarely make you make a decision.