Django 1.6 has been finally released… these are the changes I introduced into my codebase

Django 1.6 has been finally released, but this update is quite obtrusive, in fact…

Issue n.1: tests not found!

the dev team has changed significantly how unit tests are discovered and my old approach stopped working (no tests to run found).
In my previous system I created a “tests” package for each app in my project, in these packages I created a test class for each tested class, named like “TestClassName” and I exposed these classes at “tests” package level by customizing its file.
But starting with Django 1.6 the default test runner doesn’t care about “tests” modules/packages, it looks instead for file matching the pattern “test*.py” and since this pattern is CASE SENSITIVE (aaaarghh!!!) my test CLASSES (so they start with an uppercase letter) are ignored! Fortunately is very simple to override the default runner in order to match another pattern :)
This is my custom runner:

from django.test.runner import DiscoverRunner

class TestRunner(DiscoverRunner):

    def __init__(self, pattern=None, top_level=None, verbosity=1, interactive=True, failfast=False, **kwargs):
        super(TestRunner, self).__init__('Test*.py', top_level, verbosity, interactive, failfast, **kwargs)

and in the settings module:

TEST_RUNNER = 'myapp.TestRunner.TestRunner'

Issue n.2: PyCharm Django Tests configuration is now broken!

If you are using PyCharm as your python IDE, the “Django tests” run configuration is now broken (honestly I don’t understand why the guys of JetBrains have set up a such perverse way to run Django tests by writing their own python modules LOL)… so I defined a simple python run configuration in which I call “python test“… it’s not so pleasant, like the Django tests run configuration because is basically the same output of the shell script without the “green bar” and the red/yellow/green buttons that show the results of the run tests… but at the moment it does the job, and the important thing is that, differently from launching tests from the shell I can use breakpoints in the IDE to stop code execution and debug the situation! (like before)
Uh… the good part is that now my tests are executed ~40% faster!!! (10 seconds vs 14 seconds in the old run configuration)

Issue n.3: Where is gone GeoIP?!

Another problem I faced is that the GeoIP wrapper around MaxMind api has been moved from django.contrib.gis.utils to django.contrib.gis.geoip (and this change seems not documented in the release notes!)

Creating class based view decorators using simple Django function decorators

I love decorators because they allow to extend class/functions capabilities and to be be added and removed easily. Django offers a set of decorators but unfortunely they are designed for functions or class methods only and instead I want to add them to the whole class in order to avoid to override the orignal method just to add the decorator annotation above it. Fortunately wrapping the simple Django decorators in order to use them against classes (basically View classes) is quite simple and I’m gonna show you what I done.
For example let’s consider we have a view that require a POST method. If we use a simple function view we can write the following:

def myView(request):
	return HttpResponse('hello world!')

but, if we use class views (and we should!), we are forced to write:

class MyView(SomeKindOfParentClassView):
	# ...imagine several methods here

	def dispatch(self, request, *args, **kwargs):
		return HttpResponse('hello world!')

wouldn’t be cleaner and more elegant instead to simply write the following?

class MyView(SomeKindOfParentClassView):
	# ...imagine several methods here

…and this is the class decorator implementation:

from django.views.decorators.http import require_POST as post_only

def require_POST(View):
    View.dispatch = method_decorator(post_only)(View.dispatch)
    return View

Basically I redefined the class method and returned the class itself.
This was really simple since the concrete implementation of the decorator has been added using the existend Django decorators… but what if we want to create a custom decorator? For example in my app I created a decorator that enable access to a view only if it’s requested via ajax, this is how I implemented it:

def require_AJAX(SomeKindOfParentClassView):
    def ajaxOnly(function):
        def wrap(request, *args, **kwargs):
            if not request.is_ajax():
                return HttpResponseForbidden()
            return function(request, *args, **kwargs)

        return wrap

    View.dispatch = method_decorator(ajaxOnly)(View.dispatch)
    return View

And the decorated view looks like this:

class MyView(SomeKindOfParentClassView):
    # ...imagine several methods here

As you can see that annotations are really readable, immediate and self-describing.

How to make AngularJS and Django play nice together

In order to make AngularJS working as I wish in my Django app, these are the settings that I’ve adopted:

1. Differentiate Angular templates symbols from Django ones:

Both Angular than Django use doble curly braces to mark variables and/or expressions ({{ myVar }}).
In order to have the full control on how and by who our templates are rendered, I redefined the Angular interpolations signs in the config() method of my client app.


2. Change the default Angular Content-type header used in POST method:

Angular defines the “Content-Type” header as “application/json” for ajax POST, but Django doesn’t understand that content properly and as result, the POST data is not an object as we expect but rather a string! So, I modified the default content type as “application/x-www-form-urlencoded” (which is the format used by jQuery and other JavaScript libraries).

$['Content-Type'] = 'application/x-www-form-urlencoded';

3. Assign the CSFR token to each ajax call automagically

In Django templates we can use the tag {% csrf_token %} inside a form to print an hidden input containing the token. But when it comes to making an xhr post request, how can we pass the token in an effective and DRY manner? The answer I gave myself is to set a default http header for ajax calls containing the value of the token obtained by reading the session cookie (in this way this stuff is handle 100% by JavaScript).

$['X-CSRFToken'] = $cookies.csrftoken;

Differently from points 1 and 2, this is done in the run() method, since $cookies is an Angular service and can’t be used in config() block (in that function only provider objects can be used).
In order to use $cookies we have also to import “angular-cookies.js” in addition to the base “angular.js“.

The final configuration is the following:

angular.module('myapp', ['ngCookies']).
    function($httpProvider, $interpolateProvider) {
        $['Content-Type'] = 'application/x-www-form-urlencoded';
    function($http, $cookies) {
        $['X-CSRFToken'] = $cookies.csrftoken;


Starting from Angular 1.2, you have also to set default headers in order to use Django helper method is_ajax() in your views:

$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

Effective TDD: Tricks to speed up Django tests (up to 10x faster!)

TDD (Test Driven Development) is one of the best practices to follow in order to write better software and once you get used to this practice you can’t write code without writing tests.
In TDD, tests must be executed very frequently and so it’s fundamental that they run as fast as possible in order to avoid time wasting.
In this post I want to share all the tricks I discovered that will make your Django tests run very quickly (at the time of this writing I have a suite of 250 tests that has been tuned to run in ~5 seconds rather than ~50 seconds of the untuned version… that’s 10 times faster!)
In this article I’m assuming that you know: how to run Django unit tests, how to use a different settings module for testing.
These are my tips:

1) Change password hashing

This is the most effective setting you can use to improve the speed of tests, it may sounds ridicolous, but password hashing in Django is designed to be very strong and it makes use of several “hashers”, but this also means that the hashing is very slow. The fastest hasher is the MD5PasswordHasher, so you can use just that one in this way:


2) Use a faster storage system

Currently the fastest database you can use with Django is SQLite. I was initially doubtful about switching from Postgres (my database of choice) to SQLite, but I’m not testing Django itself, I’m testing my own API and since I don’t use raw SQL statements the underlying storage backend should not make differences!
So, to configure SQLite:

    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'simple_test_db'

3) Remove unnecessary middlewares

Middleware layer is one of the Django features that I like the most, BUT the more middleware classes you use, the more your response time will increase (since all the middleware must be executed sequentially before returning the final HTTPResponse, ALWAYS!). So be sure to include only the stuff you really and absolutely need!
One middleware in particular that is very slow and that I removed for the tests is:


4) Remove unnecessary apps

There are several third party apps that you may remove during testing like the debug toolbar, try to remove all the unused/unnecessary apps.

5) Disable debugging

We don’t need extended traceback during tests, so we can disable debugging:

DEBUG = False

6) Turn off logging

This is a significant modification only if we have a huge amount of logging and/or additional logic involved in logs (such object inspections, heavy string manipulation and so on), but anyway logging is futile during testing, so:


7) Use a faster Email backend (by “patching” Django)

By default Django will use django.core.mail.backends.locmem.EmailBackend, which is an in-memory backend designed for testing, however I had several problems with that backend during my tests, they did block unexplainably for ~30 seconds due to headers checking. So I decided to write my own in-memory backend which mimics the Django one but does not check email headers in order to be blazing fast:

from django.core.mail.backends.base import BaseEmailBackend
from django.core import mail

class TestEmailBackend(BaseEmailBackend):

    def send_messages(self, messages):
        return len(messages)

In order to use this backend I had to use the @override_settings decorator, since defining it in settings file is helpless because that asshole of Django (1.5.x) will use django.core.mail.backends.locmem.EmailBackend anyway!
So, by following DRY phylosophy I created a subclass of Django’s TestCase which includes that overridden setting (so I don’t have to remember to define my own backend for each test):

from django.test import TestCase as DjangoTestCase
from django.test.utils import override_settings

class TestCase(DjangoTestCase):

8) Make use of bulk_create

If you are creating more objects don’t rely on save() for each object, but instead create objects in batch using bulk_create() (it’s a method provided by Django ORM to insert multiple records in a single query)

9) Use an in-memory backend for Celery

If you are using Celery, these are my optimal settings for testing:


That’s all! If you have other advices please let me know ;)

Check Django messages (quantity and type) in unit tests

Ok, in this short (but I hope very helpful post), I’m gonna show how to check messages (Django messages framework) in your tests.
I don’t know if there is a better or “normalized” way to do this, but it’s the simplest and effective way I found by myself… so, let’s suppose we have a test in which we want to check that if the submitted form data is invalid, an error message is sent back with the response context:

def testIfSubmittedDataIsInvalidAnErrorMessageIsReturned(self):
    response =, {})
    messages = list(response.context['messages'])
    self.assertEqual(len(messages), 1)
    self.assertEqual(messages[0].level, MSG.ERROR)

MSG is a reference to messages levels constants imported in this way:

from django.contrib.messages import constants as MSG