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