Sub-domains in Django

A while back when growing a Django site I wanted to put specific apps on their own subdomain. The reason was they were large enough and from a visitor perspective, a subdomain made sense. When examining the options in Django, still being new to the framework (I’m still very much learning it), I decided I wanted to accomplish serving all the subdomains from a single project, and therefore a single WSGI application.

I found the workarounds necessary and patched something together that worked after some trial and error. I thought I had done a good thing. Once it was in production however, the maintainability and consequences of that decision became apparent.

First, I traded all apps in one project/site, which I thought would be easier to maintain, for flexibility. Now any code change, on any subdomain, and the requisite touch of the wsgi file, would cause all subdomains to reload. Not necessary and it became a minor annoyance to check each subdomain after changes. What also was supposed to be easier to maintain became more problematic, as errors on one subdomain could affect the others.

Second, I found that the patching I had done had broken Django’s APPEND_SLASH of the CommonMiddleware, so people typing URL’s were often getting 404’s. Initially, I knew it was broke, but wasn’t sure why as I double checked all my settings. It wasn’t until I broke the project apart and removed the code and found the functionality returned that I realized I broke it.

A few months ago I broke the project apart into 3 projects, 1 for each subdomain, with any future subdomains getting their own project as well after about a year with the initial design. This has improved the manageability of the sites, made their configuration simpler and cleaner and provided other benefits, like being able to size the subdomain sites to their traffic, and even relocate them to different servers. Currently, they all share the same database and the refresh took out any display of subdomain B’s info on subdomain A’s templates, (a business decision that followed the technological one) but that could return with some new template_tags that use raw queries. I will leave that investigation to when I decide cross-domain info is needed.

I’m sold that I’m now doing it the right way now. There are uses for multi-subdomains in one project, such as subdomains for every user, but for an app that should be on its own subdomain, it should have its own project. I hope this post helps others contemplating subdomains in Django see the pitfalls of keeping it all together.

QOTW

From 20 years ago, but so much more apt today.

All this modern technology just makes people try to do everything at once.

Hobbes