djangodjango-sites

Django 'Sites' Model - what is and why is 'SITE_ID = 1'?


I am trying to work with Sites Model of Django.

I dont quite understand why SITE_ID should be SITE_ID = 1.

in the docs:

The ID, as an integer, of the current site in the django_site database table. This is used so that application data can hook into specific sites and a single database can manage content for multiple sites.

why 1? what is the current site? this is not clearly explained in the docs.

lets say, I have www.coolsite.com and some other subdomains like www.wow.coolsite.com and www.awesome.coolsite.com

I want to render different content depending on domain name.

my question is, or better, are:

  1. Do I have to add all those domains into Sites Table in DB?
  2. if so, how should I set SITE_ID in settings? Do I have to set all ids like SITE_ID = 1, SITE_ID = 2.. etc?
  3. what does current site has to do with SITE_ID = 1?

I am a bit confused here.

I thought, each Site (e.g. www.wow.coolsite.com) should be a separate django project so that they can have their own settings.py? and in each of those settings.py's, I will set the id of that page from Sites table? but then there are many django projects which also doesnot make sense to me.


Solution

  • Django was created from a set of scripts developed at a newspaper to publish content on multiple domains; using one single content base.

    This is where the "sites" module comes in. Its purpose is to mark content to be displayed for different domains.

    In previous versions of django, the startproject script automatically added the django.contrib.sites application to INSTALLED_APPS, and when you did syncdb, a default site with the URL example.com was added to your database, and since this was the first site, its ID was 1 and that's where the setting comes from.

    Keep in mind that starting from 1.6, this framework is not enabled by default. So if you need it, you must enable it

    The SITE_ID setting sets the default site for your project. So, if you don't specify a site, this is the one it will use.

    So to configure your application for different domains:

    1. Enable the sites framework
    2. Change the default site from example.com to whatever your default domain is. You can do this from the django shell, or from the admin.
    3. Add your other sites for which you want to publish content to the sites application. Again, you can do this from the django shell just like any other application or from the admin.
    4. Add a foreign key to the Site model in your object site = models.ForeignKey(Site)
    5. Add the site manager on_site = CurrentSiteManager()

    Now, when you want to filter content for the default site, or a particular site:

    foo = MyObj.on_site.all() # Filters site to whatever is `SITE_ID`
    foo = MyObj.objects.all() # Get all objects, irrespective of what site
                              # they belong to
    

    The documentation has a full set of examples.