Django can make cyclic python imports confusing

I've just had a horrible bug regarding import problems. I had a website migrated from another developer service running nicely so I tried to deploy it on my usual nginx/gunicorn set up. It raised an error telling me it could not import a middleware file that it imported perfectly happily in either the Django shell or when using Django's runserver command.

After much head banging and searching I found the problem which was a cyclic import: Three modules in the migrated site were involved:

'middleware' imports 'models' and 'models' imports 'listeners'. 'listeners' imports 'middleware' so you get an error if you try to import 'middleware' because of the cyclic dependency. Right? Not necessarily:

The thing that hid this common Python problem so well is the fact that Django's management commands perform model validation, importing each of the project's model modules. When the above model is imported that level, there is no cyclic problem and when the middleware is subsequently imported, the models module is already imported so no problem occurs.

Clearly, the original code is poorly structured, but I needed to get it working so the easiest workaround I came up with was to import the badly structured model in the normal wsgi startup:

from danemco.authenticatedpages import models # Fix cyclic import problem if middleware is imported without doing this import first


There are currently no comments

New Comment


required (not published)


Australia: 07 3103 2894

International: +61 410 545 357