Creating a dynamic multisite using Django

Posted on: August 13, 2011Author: Rob

Django is a great framework for rapid web development. Because it is chock-full of features, you can create great web applications using only a couple of lines of code. One thing I found out, though, is that it doesn’t support dynamic multisites out of the box.

Dynamic multisites are dynamically created sites, which are served from a single server instance. In Django terms: one project serves multiple dynamically created sites. Well known examples of dynamic multisites are blogspot and wordpress, where users receive their own subdomain for every account.

Fortunately, Django is very easily extensible and we are going to do just that to add dynamic multisite support. We’ll be using the sites framework and a custom middleware component to enable this feature.

This tutorial is structured as follows:

Getting started

First things first. In order to create a dynamic multisite, we need to have a site first. I’ll use the Django tutorial as a starting point. If you are new to Django I highly recommend following those steps to make yourself more familiar with the framework. Once you’ve completed the tutorial, you should be able to create polls, add answers and vote for those answers. Your directory structure should look something like this:
Directory Structure Tutorial

Continue to the Sites framework.

Pages: 1 2 3

  • Dylan Verheul

    Very nice tutorial. Do you think it is safe to overwrite settings.SITE_ID? What about multithreading servers?

    • Rob

      I think Django’s thread safety should prevent any serious issues, although I must admit I haven’t tested that yet. It is a valid concern though, I’ll see if I can think of an easy way to test this :).

      • RobM

        Hi Rob,

        Did you ever figure out a way to test if indeed Django prevents serious problems? Seems there hasn’t been a follow up on this for a while.

    • Rob

      It seems like this solution indeed faces some threading issues. However, the general direction is valid, we just need some extra measures. Another example implementation can be found here:

  • PhilipR

    Hi Rob

    This example was exactly what I was looking for, and it’s well written. Did you ever test the thread safety issue?

    • Rob Been

      Hi Philip,

      Because we are directly updating the settings in the middleware this solution unfortunatly does have some threading issues.

      However, I’ve found another example implementation which uses adds another middleware to avoid the threading issues:

      Hope this helps :D