[Fixed]-Django: What is the most ideal place to store project-specific middleware?


My usual layout for a django site is:



  • projects contains your main project and any others
  • common contains things you may share across sites, or are at least not project-specific, like if you need to download django-profile and django-registration rather than having it directly in python/site-packages
  • templates contains just that
  • local contains things that are going to be specific to the current machine, so that you can have properly separated data, like database location and password – I then soft-link the machine-specific versions (say “machine1-localconfig.py”) to local/localconfig.py and then can “import localconfig” in settings.py

I generally put middleware that’s project-specific inside a project, and middleware that’s not project-specific in common/middleware/

Make sure to add the templates directory to the right place in settings (or most probably, localconfig.py and then import it in settings), and makse sure to add the projects, common, and local directories to your PYTHONPATH.


If you have only a couple of tightly coupled middleware classes put them into a middleware.py module under the app root. (This is how the django.contrib apps do it – see the sessions’ app middleware here).

If you have many varying middleware classes, create a middleware pacakge with submodules of the related middleware classes. Though if you do end up in this situation, consider how you can refactor your project into several mini-apps that all solve a specific need (and open source them :)).

Personally, I have a common django package where I dump common middleware (like the your linked LoginRequiredMiddleware class) into a middleware package. If this makes sense in your project’s context I would highly suggest it. It’s saved my countless hours of duplication, and bug fixing. django-common and django-annoying are good examples of this kind of project layout

Leave a comment