The “sites” framework

Django comes with an optional “sites” framework. It’s a hook for associatingobjects and functionality to particular websites, and it’s a holding place forthe domain names and “verbose” names of your Django-powered sites.

Use it if your single Django installation powers more than one site and youneed to differentiate between those sites in some way.

The sites framework is mainly based on this model:

  • class models.Site
  • A model for storing the domain and name attributes of a website.

    • domain
    • The fully qualified domain name associated with the website.For example, www.example.com.

    • name

    • A human-readable “verbose” name for the website.

The SITE_ID setting specifies the database ID of theSite object associated with thatparticular settings file. If the setting is omitted, theget_current_site() function willtry to get the current site by comparing thedomain with the host name fromthe request.get_host() method.

How you use this is up to you, but Django uses it in a couple of waysautomatically via a couple of conventions.

Example usage

Why would you use sites? It’s best explained through examples.

Associating content with multiple sites

The Django-powered sites LJWorld.com and Lawrence.com are operated by thesame news organization – the Lawrence Journal-World newspaper in Lawrence,Kansas. LJWorld.com focuses on news, while Lawrence.com focuses on localentertainment. But sometimes editors want to publish an article on _both_sites.

The naive way of solving the problem would be to require site producers topublish the same story twice: once for LJWorld.com and again for Lawrence.com.But that’s inefficient for site producers, and it’s redundant to storemultiple copies of the same story in the database.

A better solution removes the content duplication: Both sites use the samearticle database, and an article is associated with one or more sites. InDjango model terminology, that’s represented by aManyToManyField in the Article model:

  1. from django.contrib.sites.models import Site
  2. from django.db import models
  3.  
  4. class Article(models.Model):
  5. headline = models.CharField(max_length=200)
  6. # ...
  7. sites = models.ManyToManyField(Site)

This accomplishes several things quite nicely:

  • It lets the site producers edit all content – on both sites – in asingle interface (the Django admin).

  • It means the same story doesn’t have to be published twice in thedatabase; it only has a single record in the database.

  • It lets the site developers use the same Django view code for both sites.The view code that displays a given story checks to make sure the requestedstory is on the current site. It looks something like this:

  1. from django.contrib.sites.shortcuts import get_current_site
  2.  
  3. def article_detail(request, article_id):
  4. try:
  5. a = Article.objects.get(id=article_id, sites__id=get_current_site(request).id)
  6. except Article.DoesNotExist:
  7. raise Http404("Article does not exist on this site")
  8. # ...

Associating content with a single site

Similarly, you can associate a model to theSitemodel in a many-to-one relationship, usingForeignKey.

For example, if an article is only allowed on a single site, you’d use a modellike this:

  1. from django.contrib.sites.models import Site
  2. from django.db import models
  3.  
  4. class Article(models.Model):
  5. headline = models.CharField(max_length=200)
  6. # ...
  7. site = models.ForeignKey(Site, on_delete=models.CASCADE)

This has the same benefits as described in the last section.

Hooking into the current site from views

You can use the sites framework in your Django views to doparticular things based on the site in which the view is being called.For example:

  1. from django.conf import settings
  2.  
  3. def my_view(request):
  4. if settings.SITE_ID == 3:
  5. # Do something.
  6. pass
  7. else:
  8. # Do something else.
  9. pass

Of course, it’s ugly to hard-code the site IDs like that. This sort ofhard-coding is best for hackish fixes that you need done quickly. Thecleaner way of accomplishing the same thing is to check the current site’sdomain:

  1. from django.contrib.sites.shortcuts import get_current_site
  2.  
  3. def my_view(request):
  4. current_site = get_current_site(request)
  5. if current_site.domain == 'foo.com':
  6. # Do something
  7. pass
  8. else:
  9. # Do something else.
  10. pass

This has also the advantage of checking if the sites framework is installed,and return a RequestSite instance ifit is not.

If you don’t have access to the request object, you can use theget_current() method of the Sitemodel’s manager. You should then ensure that your settings file does containthe SITE_ID setting. This example is equivalent to the previous one:

  1. from django.contrib.sites.models import Site
  2.  
  3. def my_function_without_request():
  4. current_site = Site.objects.get_current()
  5. if current_site.domain == 'foo.com':
  6. # Do something
  7. pass
  8. else:
  9. # Do something else.
  10. pass

Getting the current domain for display

LJWorld.com and Lawrence.com both have email alert functionality, which letsreaders sign up to get notifications when news happens. It’s pretty basic: Areader signs up on a Web form and immediately gets an email saying,“Thanks for your subscription.”

It’d be inefficient and redundant to implement this sign up processing codetwice, so the sites use the same code behind the scenes. But the “thank you forsigning up” notice needs to be different for each site. By usingSiteobjects, we can abstract the “thank you” notice to use the values of thecurrent site’s name anddomain.

Here’s an example of what the form-handling view looks like:

  1. from django.contrib.sites.shortcuts import get_current_site
  2. from django.core.mail import send_mail
  3.  
  4. def register_for_newsletter(request):
  5. # Check form values, etc., and subscribe the user.
  6. # ...
  7.  
  8. current_site = get_current_site(request)
  9. send_mail(
  10. 'Thanks for subscribing to %s alerts' % current_site.name,
  11. 'Thanks for your subscription. We appreciate it.\n\n-The %s team.' % (
  12. current_site.name,
  13. ),
  14. 'editor@%s' % current_site.domain,
  15. [user.email],
  16. )
  17.  
  18. # ...

On Lawrence.com, this email has the subject line “Thanks for subscribing tolawrence.com alerts.” On LJWorld.com, the email has the subject “Thanks forsubscribing to LJWorld.com alerts.” Same goes for the email’s message body.

Note that an even more flexible (but more heavyweight) way of doing this wouldbe to use Django’s template system. Assuming Lawrence.com and LJWorld.com havedifferent template directories (DIRS), you couldfarm out to the template system like so:

  1. from django.core.mail import send_mail
  2. from django.template import Context, loader
  3.  
  4. def register_for_newsletter(request):
  5. # Check form values, etc., and subscribe the user.
  6. # ...
  7.  
  8. subject = loader.get_template('alerts/subject.txt').render(Context({}))
  9. message = loader.get_template('alerts/message.txt').render(Context({}))
  10. send_mail(subject, message, 'editor@ljworld.com', [user.email])
  11.  
  12. # ...

In this case, you’d have to create subject.txt and message.txttemplate files for both the LJWorld.com and Lawrence.com template directories.That gives you more flexibility, but it’s also more complex.

It’s a good idea to exploit the Siteobjects as much as possible, to remove unneeded complexity and redundancy.

Getting the current domain for full URLs

Django’s get_absolute_url() convention is nice for getting your objects’URL without the domain name, but in some cases you might want to display thefull URL – with http:// and the domain and everything – for an object.To do this, you can use the sites framework. An example:

  1. >>> from django.contrib.sites.models import Site
  2. >>> obj = MyModel.objects.get(id=3)
  3. >>> obj.get_absolute_url()
  4. '/mymodel/objects/3/'
  5. >>> Site.objects.get_current().domain
  6. 'example.com'
  7. >>> 'https://%s%s' % (Site.objects.get_current().domain, obj.get_absolute_url())
  8. 'https://example.com/mymodel/objects/3/'

Enabling the sites framework

To enable the sites framework, follow these steps:

  1. SITE_ID = 1

django.contrib.sites registers apost_migrate signal handler which creates adefault site named example.com with the domain example.com. This sitewill also be created after Django creates the test database. To set thecorrect name and domain for your project, you can use a data migration.

In order to serve different sites in production, you’d create a separatesettings file with each SITE_ID (perhaps importing from a common settingsfile to avoid duplicating shared settings) and then specify the appropriateDJANGO_SETTINGS_MODULE for each site.

Caching the current Site object

As the current site is stored in the database, each call toSite.objects.get_current() could result in a database query. But Django is alittle cleverer than that: on the first request, the current site is cached, andany subsequent call returns the cached data instead of hitting the database.

If for any reason you want to force a database query, you can tell Django toclear the cache using Site.objects.clear_cache():

  1. # First call; current site fetched from database.
  2. current_site = Site.objects.get_current()
  3. # ...
  4.  
  5. # Second call; current site fetched from cache.
  6. current_site = Site.objects.get_current()
  7. # ...
  8.  
  9. # Force a database query for the third call.
  10. Site.objects.clear_cache()
  11. current_site = Site.objects.get_current()

The CurrentSiteManager

  • class managers.CurrentSiteManager
  • If Site plays a key role in yourapplication, consider using the helpfulCurrentSiteManager in yourmodel(s). It’s a model manager thatautomatically filters its queries to include only objects associatedwith the current Site.

Mandatory SITE_ID

The CurrentSiteManager is only usable when the SITE_IDsetting is defined in your settings.

Use CurrentSiteManager by adding it toyour model explicitly. For example:

  1. from django.contrib.sites.models import Site
  2. from django.contrib.sites.managers import CurrentSiteManager
  3. from django.db import models
  4.  
  5. class Photo(models.Model):
  6. photo = models.FileField(upload_to='photos')
  7. photographer_name = models.CharField(max_length=100)
  8. pub_date = models.DateField()
  9. site = models.ForeignKey(Site, on_delete=models.CASCADE)
  10. objects = models.Manager()
  11. on_site = CurrentSiteManager()

With this model, Photo.objects.all() will return all Photo objects inthe database, but Photo.on_site.all() will return only the Photo objectsassociated with the current site, according to the SITE_ID setting.

Put another way, these two statements are equivalent:

  1. Photo.objects.filter(site=settings.SITE_ID)
  2. Photo.on_site.all()

How did CurrentSiteManagerknow which field of Photo was theSite? By default,CurrentSiteManager looks for aeither a ForeignKey calledsite or aManyToManyField calledsites to filter on. If you use a field named something other thansite or sites to identify whichSite objects your object isrelated to, then you need to explicitly pass the custom field name asa parameter toCurrentSiteManager on yourmodel. The following model, which has a field called publish_on,demonstrates this:

  1. from django.contrib.sites.models import Site
  2. from django.contrib.sites.managers import CurrentSiteManager
  3. from django.db import models
  4.  
  5. class Photo(models.Model):
  6. photo = models.FileField(upload_to='photos')
  7. photographer_name = models.CharField(max_length=100)
  8. pub_date = models.DateField()
  9. publish_on = models.ForeignKey(Site, on_delete=models.CASCADE)
  10. objects = models.Manager()
  11. on_site = CurrentSiteManager('publish_on')

If you attempt to use CurrentSiteManagerand pass a field name that doesn’t exist, Django will raise a ValueError.

Finally, note that you’ll probably want to keep a normal(non-site-specific) Manager on your model, even if you useCurrentSiteManager. Asexplained in the manager documentation, ifyou define a manager manually, then Django won’t create the automaticobjects = models.Manager() manager for you. Also note that certainparts of Django – namely, the Django admin site and generic views –use whichever manager is defined first in the model, so if you wantyour admin site to have access to all objects (not just site-specificones), put objects = models.Manager() in your model, before youdefine CurrentSiteManager.

Site middleware

If you often use this pattern:

  1. from django.contrib.sites.models import Site
  2.  
  3. def my_view(request):
  4. site = Site.objects.get_current()
  5. ...

To avoid repetitions, adddjango.contrib.sites.middleware.CurrentSiteMiddleware toMIDDLEWARE. The middleware sets the site attribute on everyrequest object, so you can use request.site to get the current site.

How Django uses the sites framework

Although it’s not required that you use the sites framework, it’s stronglyencouraged, because Django takes advantage of it in a few places. Even if yourDjango installation is powering only a single site, you should take the twoseconds to create the site object with your domain and name, and pointto its ID in your SITE_ID setting.

Here’s how Django uses the sites framework:

  • In the redirects framework, eachredirect object is associated with a particular site. When Django searchesfor a redirect, it takes into account the current site.
  • In the flatpages framework, eachflatpage is associated with a particular site. When a flatpage is created,you specify its Site, and theFlatpageFallbackMiddlewarechecks the current site in retrieving flatpages to display.
  • In the syndication framework, thetemplates for title and description automatically have access to avariable {{ site }}, which is theSite object representing the currentsite. Also, the hook for providing item URLs will use the domain fromthe current Site object if you don’tspecify a fully-qualified domain.
  • In the authentication framework,django.contrib.auth.views.LoginView passes the currentSite name to the template as{{ site_name }}.
  • The shortcut view (django.contrib.contenttypes.views.shortcut)uses the domain of the currentSite object when calculatingan object’s URL.
  • In the admin framework, the “view on site” link uses the currentSite to work out the domain for thesite that it will redirect to.

RequestSite objects

Some django.contrib applications take advantage ofthe sites framework but are architected in a way that doesn’t require thesites framework to be installed in your database. (Some people don’t want to,or just aren’t able to install the extra database table that the sitesframework requires.) For those cases, the framework provides adjango.contrib.sites.requests.RequestSite class, which can be used asa fallback when the database-backed sites framework is not available.

  • class requests.RequestSite
  • A class that shares the primary interface ofSite (i.e., it hasdomain and name attributes) but gets its data from a DjangoHttpRequest object rather than from a database.

    • init(request)
    • Sets the name and domain attributes to the value ofget_host().

A RequestSite object has a similarinterface to a normal Site object,except its init()method takes an HttpRequest object. It’s able to deducethe domain and name by looking at the request’s domain. It hassave() and delete() methods to match the interface ofSite, but the methods raiseNotImplementedError.

get_current_site shortcut

Finally, to avoid repetitive fallback code, the framework provides adjango.contrib.sites.shortcuts.get_current_site() function.

  • shortcuts.getcurrent_site(_request)
  • A function that checks if django.contrib.sites is installed andreturns either the current Siteobject or a RequestSite objectbased on the request. It looks up the current site based onrequest.get_host() if theSITE_ID setting is not defined.

Both a domain and a port may be returned by request.get_host() when the Host header has a portexplicitly specified, e.g. example.com:80. In such cases, if thelookup fails because the host does not match a record in the database,the port is stripped and the lookup is retried with the domain partonly. This does not apply toRequestSite which will alwaysuse the unmodified host.