sites.txt 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. =====================
  2. The "sites" framework
  3. =====================
  4. .. module:: django.contrib.sites
  5. :synopsis: Lets you operate multiple Web sites from the same database and
  6. Django project
  7. Django comes with an optional "sites" framework. It's a hook for associating
  8. objects and functionality to particular Web sites, and it's a holding place for
  9. the domain names and "verbose" names of your Django-powered sites.
  10. Use it if your single Django installation powers more than one site and you
  11. need to differentiate between those sites in some way.
  12. The sites framework is mainly based on a simple model:
  13. .. class:: models.Site
  14. A model for storing the ``domain`` and ``name`` attributes of a Web site.
  15. .. attribute:: domain
  16. The domain name associated with the Web site.
  17. .. versionchanged:: 1.9
  18. The ``domain`` field was set to be
  19. :attr:`~django.db.models.Field.unique`.
  20. .. attribute:: name
  21. A human-readable "verbose" name for the Web site.
  22. The :setting:`SITE_ID` setting specifies the database ID of the
  23. :class:`~django.contrib.sites.models.Site` object associated with that
  24. particular settings file. If the setting is omitted, the
  25. :func:`~django.contrib.sites.shortcuts.get_current_site` function will
  26. try to get the current site by comparing the
  27. :attr:`~django.contrib.sites.models.Site.domain` with the host name from
  28. the :meth:`request.get_host() <django.http.HttpRequest.get_host>` method.
  29. How you use this is up to you, but Django uses it in a couple of ways
  30. automatically via simple conventions.
  31. Example usage
  32. =============
  33. Why would you use sites? It's best explained through examples.
  34. Associating content with multiple sites
  35. ---------------------------------------
  36. The Django-powered sites LJWorld.com_ and Lawrence.com_ are operated by the
  37. same news organization -- the Lawrence Journal-World newspaper in Lawrence,
  38. Kansas. LJWorld.com focuses on news, while Lawrence.com focuses on local
  39. entertainment. But sometimes editors want to publish an article on *both*
  40. sites.
  41. The brain-dead way of solving the problem would be to require site producers to
  42. publish the same story twice: once for LJWorld.com and again for Lawrence.com.
  43. But that's inefficient for site producers, and it's redundant to store
  44. multiple copies of the same story in the database.
  45. The better solution is simple: Both sites use the same article database, and an
  46. article is associated with one or more sites. In Django model terminology,
  47. that's represented by a :class:`~django.db.models.ManyToManyField` in the
  48. ``Article`` model::
  49. from django.db import models
  50. from django.contrib.sites.models import Site
  51. class Article(models.Model):
  52. headline = models.CharField(max_length=200)
  53. # ...
  54. sites = models.ManyToManyField(Site)
  55. This accomplishes several things quite nicely:
  56. * It lets the site producers edit all content -- on both sites -- in a
  57. single interface (the Django admin).
  58. * It means the same story doesn't have to be published twice in the
  59. database; it only has a single record in the database.
  60. * It lets the site developers use the same Django view code for both sites.
  61. The view code that displays a given story just checks to make sure the
  62. requested story is on the current site. It looks something like this::
  63. from django.contrib.sites.shortcuts import get_current_site
  64. def article_detail(request, article_id):
  65. try:
  66. a = Article.objects.get(id=article_id, sites__id=get_current_site(request).id)
  67. except Article.DoesNotExist:
  68. raise Http404("Article does not exist on this site")
  69. # ...
  70. .. _ljworld.com: http://www.ljworld.com/
  71. .. _lawrence.com: http://www.lawrence.com/
  72. Associating content with a single site
  73. --------------------------------------
  74. Similarly, you can associate a model to the
  75. :class:`~django.contrib.sites.models.Site`
  76. model in a many-to-one relationship, using
  77. :class:`~django.db.models.ForeignKey`.
  78. For example, if an article is only allowed on a single site, you'd use a model
  79. like this::
  80. from django.db import models
  81. from django.contrib.sites.models import Site
  82. class Article(models.Model):
  83. headline = models.CharField(max_length=200)
  84. # ...
  85. site = models.ForeignKey(Site)
  86. This has the same benefits as described in the last section.
  87. .. _hooking-into-current-site-from-views:
  88. Hooking into the current site from views
  89. ----------------------------------------
  90. You can use the sites framework in your Django views to do
  91. particular things based on the site in which the view is being called.
  92. For example::
  93. from django.conf import settings
  94. def my_view(request):
  95. if settings.SITE_ID == 3:
  96. # Do something.
  97. pass
  98. else:
  99. # Do something else.
  100. pass
  101. Of course, it's ugly to hard-code the site IDs like that. This sort of
  102. hard-coding is best for hackish fixes that you need done quickly. The
  103. cleaner way of accomplishing the same thing is to check the current site's
  104. domain::
  105. from django.contrib.sites.shortcuts import get_current_site
  106. def my_view(request):
  107. current_site = get_current_site(request)
  108. if current_site.domain == 'foo.com':
  109. # Do something
  110. pass
  111. else:
  112. # Do something else.
  113. pass
  114. This has also the advantage of checking if the sites framework is installed,
  115. and return a :class:`~django.contrib.sites.requests.RequestSite` instance if
  116. it is not.
  117. If you don't have access to the request object, you can use the
  118. ``get_current()`` method of the :class:`~django.contrib.sites.models.Site`
  119. model's manager. You should then ensure that your settings file does contain
  120. the :setting:`SITE_ID` setting. This example is equivalent to the previous one::
  121. from django.contrib.sites.models import Site
  122. def my_function_without_request():
  123. current_site = Site.objects.get_current()
  124. if current_site.domain == 'foo.com':
  125. # Do something
  126. pass
  127. else:
  128. # Do something else.
  129. pass
  130. Getting the current domain for display
  131. --------------------------------------
  132. LJWorld.com and Lawrence.com both have email alert functionality, which lets
  133. readers sign up to get notifications when news happens. It's pretty basic: A
  134. reader signs up on a Web form and immediately gets an email saying,
  135. "Thanks for your subscription."
  136. It'd be inefficient and redundant to implement this sign up processing code
  137. twice, so the sites use the same code behind the scenes. But the "thank you for
  138. signing up" notice needs to be different for each site. By using
  139. :class:`~django.contrib.sites.models.Site`
  140. objects, we can abstract the "thank you" notice to use the values of the
  141. current site's :attr:`~django.contrib.sites.models.Site.name` and
  142. :attr:`~django.contrib.sites.models.Site.domain`.
  143. Here's an example of what the form-handling view looks like::
  144. from django.contrib.sites.shortcuts import get_current_site
  145. from django.core.mail import send_mail
  146. def register_for_newsletter(request):
  147. # Check form values, etc., and subscribe the user.
  148. # ...
  149. current_site = get_current_site(request)
  150. send_mail('Thanks for subscribing to %s alerts' % current_site.name,
  151. 'Thanks for your subscription. We appreciate it.\n\n-The %s team.' % current_site.name,
  152. 'editor@%s' % current_site.domain,
  153. [user.email])
  154. # ...
  155. On Lawrence.com, this email has the subject line "Thanks for subscribing to
  156. lawrence.com alerts." On LJWorld.com, the email has the subject "Thanks for
  157. subscribing to LJWorld.com alerts." Same goes for the email's message body.
  158. Note that an even more flexible (but more heavyweight) way of doing this would
  159. be to use Django's template system. Assuming Lawrence.com and LJWorld.com have
  160. different template directories (:setting:`DIRS <TEMPLATES-DIRS>`), you could
  161. simply farm out to the template system like so::
  162. from django.core.mail import send_mail
  163. from django.template import loader, Context
  164. def register_for_newsletter(request):
  165. # Check form values, etc., and subscribe the user.
  166. # ...
  167. subject = loader.get_template('alerts/subject.txt').render(Context({}))
  168. message = loader.get_template('alerts/message.txt').render(Context({}))
  169. send_mail(subject, message, 'editor@ljworld.com', [user.email])
  170. # ...
  171. In this case, you'd have to create :file:`subject.txt` and :file:`message.txt`
  172. template files for both the LJWorld.com and Lawrence.com template directories.
  173. That gives you more flexibility, but it's also more complex.
  174. It's a good idea to exploit the :class:`~django.contrib.sites.models.Site`
  175. objects as much as possible, to remove unneeded complexity and redundancy.
  176. Getting the current domain for full URLs
  177. ----------------------------------------
  178. Django's ``get_absolute_url()`` convention is nice for getting your objects'
  179. URL without the domain name, but in some cases you might want to display the
  180. full URL -- with ``http://`` and the domain and everything -- for an object.
  181. To do this, you can use the sites framework. A simple example::
  182. >>> from django.contrib.sites.models import Site
  183. >>> obj = MyModel.objects.get(id=3)
  184. >>> obj.get_absolute_url()
  185. '/mymodel/objects/3/'
  186. >>> Site.objects.get_current().domain
  187. 'example.com'
  188. >>> 'http://%s%s' % (Site.objects.get_current().domain, obj.get_absolute_url())
  189. 'http://example.com/mymodel/objects/3/'
  190. .. _enabling-the-sites-framework:
  191. Enabling the sites framework
  192. ============================
  193. To enable the sites framework, follow these steps:
  194. 1. Add ``'django.contrib.sites'`` to your :setting:`INSTALLED_APPS`
  195. setting.
  196. 2. Define a :setting:`SITE_ID` setting::
  197. SITE_ID = 1
  198. 3. Run :djadmin:`migrate`.
  199. ``django.contrib.sites`` registers a
  200. :data:`~django.db.models.signals.post_migrate` signal handler which creates a
  201. default site named ``example.com`` with the domain ``example.com``. This site
  202. will also be created after Django creates the test database. To set the
  203. correct name and domain for your project, you can use a :ref:`data migration
  204. <data-migrations>`.
  205. In order to serve different sites in production, you'd create a separate
  206. settings file with each ``SITE_ID`` (perhaps importing from a common settings
  207. file to avoid duplicating shared settings) and then specify the appropriate
  208. :envvar:`DJANGO_SETTINGS_MODULE` for each site.
  209. Caching the current ``Site`` object
  210. ===================================
  211. As the current site is stored in the database, each call to
  212. ``Site.objects.get_current()`` could result in a database query. But Django is a
  213. little cleverer than that: on the first request, the current site is cached, and
  214. any subsequent call returns the cached data instead of hitting the database.
  215. If for any reason you want to force a database query, you can tell Django to
  216. clear the cache using ``Site.objects.clear_cache()``::
  217. # First call; current site fetched from database.
  218. current_site = Site.objects.get_current()
  219. # ...
  220. # Second call; current site fetched from cache.
  221. current_site = Site.objects.get_current()
  222. # ...
  223. # Force a database query for the third call.
  224. Site.objects.clear_cache()
  225. current_site = Site.objects.get_current()
  226. The ``CurrentSiteManager``
  227. ==========================
  228. .. class:: managers.CurrentSiteManager
  229. If :class:`~django.contrib.sites.models.Site` plays a key role in your
  230. application, consider using the helpful
  231. :class:`~django.contrib.sites.managers.CurrentSiteManager` in your
  232. model(s). It's a model :doc:`manager </topics/db/managers>` that
  233. automatically filters its queries to include only objects associated
  234. with the current :class:`~django.contrib.sites.models.Site`.
  235. .. admonition:: Mandatory :setting:`SITE_ID`
  236. The ``CurrentSiteManager`` is only usable when the :setting:`SITE_ID`
  237. setting is defined in your settings.
  238. Use :class:`~django.contrib.sites.managers.CurrentSiteManager` by adding it to
  239. your model explicitly. For example::
  240. from django.db import models
  241. from django.contrib.sites.models import Site
  242. from django.contrib.sites.managers import CurrentSiteManager
  243. class Photo(models.Model):
  244. photo = models.FileField(upload_to='/home/photos')
  245. photographer_name = models.CharField(max_length=100)
  246. pub_date = models.DateField()
  247. site = models.ForeignKey(Site)
  248. objects = models.Manager()
  249. on_site = CurrentSiteManager()
  250. With this model, ``Photo.objects.all()`` will return all ``Photo`` objects in
  251. the database, but ``Photo.on_site.all()`` will return only the ``Photo`` objects
  252. associated with the current site, according to the :setting:`SITE_ID` setting.
  253. Put another way, these two statements are equivalent::
  254. Photo.objects.filter(site=settings.SITE_ID)
  255. Photo.on_site.all()
  256. How did :class:`~django.contrib.sites.managers.CurrentSiteManager`
  257. know which field of ``Photo`` was the
  258. :class:`~django.contrib.sites.models.Site`? By default,
  259. :class:`~django.contrib.sites.managers.CurrentSiteManager` looks for a
  260. either a :class:`~django.db.models.ForeignKey` called
  261. ``site`` or a
  262. :class:`~django.db.models.ManyToManyField` called
  263. ``sites`` to filter on. If you use a field named something other than
  264. ``site`` or ``sites`` to identify which
  265. :class:`~django.contrib.sites.models.Site` objects your object is
  266. related to, then you need to explicitly pass the custom field name as
  267. a parameter to
  268. :class:`~django.contrib.sites.managers.CurrentSiteManager` on your
  269. model. The following model, which has a field called ``publish_on``,
  270. demonstrates this::
  271. from django.db import models
  272. from django.contrib.sites.models import Site
  273. from django.contrib.sites.managers import CurrentSiteManager
  274. class Photo(models.Model):
  275. photo = models.FileField(upload_to='/home/photos')
  276. photographer_name = models.CharField(max_length=100)
  277. pub_date = models.DateField()
  278. publish_on = models.ForeignKey(Site)
  279. objects = models.Manager()
  280. on_site = CurrentSiteManager('publish_on')
  281. If you attempt to use :class:`~django.contrib.sites.managers.CurrentSiteManager`
  282. and pass a field name that doesn't exist, Django will raise a ``ValueError``.
  283. Finally, note that you'll probably want to keep a normal
  284. (non-site-specific) ``Manager`` on your model, even if you use
  285. :class:`~django.contrib.sites.managers.CurrentSiteManager`. As
  286. explained in the :doc:`manager documentation </topics/db/managers>`, if
  287. you define a manager manually, then Django won't create the automatic
  288. ``objects = models.Manager()`` manager for you. Also note that certain
  289. parts of Django -- namely, the Django admin site and generic views --
  290. use whichever manager is defined *first* in the model, so if you want
  291. your admin site to have access to all objects (not just site-specific
  292. ones), put ``objects = models.Manager()`` in your model, before you
  293. define :class:`~django.contrib.sites.managers.CurrentSiteManager`.
  294. .. _site-middleware:
  295. Site middleware
  296. ===============
  297. If you often use this pattern::
  298. from django.contrib.sites.models import Site
  299. def my_view(request):
  300. site = Site.objects.get_current()
  301. ...
  302. there is simple way to avoid repetitions. Add
  303. :class:`django.contrib.sites.middleware.CurrentSiteMiddleware` to
  304. :setting:`MIDDLEWARE_CLASSES`. The middleware sets the ``site`` attribute on
  305. every request object, so you can use ``request.site`` to get the current site.
  306. How Django uses the sites framework
  307. ===================================
  308. Although it's not required that you use the sites framework, it's strongly
  309. encouraged, because Django takes advantage of it in a few places. Even if your
  310. Django installation is powering only a single site, you should take the two
  311. seconds to create the site object with your ``domain`` and ``name``, and point
  312. to its ID in your :setting:`SITE_ID` setting.
  313. Here's how Django uses the sites framework:
  314. * In the :mod:`redirects framework <django.contrib.redirects>`, each
  315. redirect object is associated with a particular site. When Django searches
  316. for a redirect, it takes into account the current site.
  317. * In the :mod:`flatpages framework <django.contrib.flatpages>`, each
  318. flatpage is associated with a particular site. When a flatpage is created,
  319. you specify its :class:`~django.contrib.sites.models.Site`, and the
  320. :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`
  321. checks the current site in retrieving flatpages to display.
  322. * In the :mod:`syndication framework <django.contrib.syndication>`, the
  323. templates for ``title`` and ``description`` automatically have access to a
  324. variable ``{{ site }}``, which is the
  325. :class:`~django.contrib.sites.models.Site` object representing the current
  326. site. Also, the hook for providing item URLs will use the ``domain`` from
  327. the current :class:`~django.contrib.sites.models.Site` object if you don't
  328. specify a fully-qualified domain.
  329. * In the :mod:`authentication framework <django.contrib.auth>`, the
  330. :func:`django.contrib.auth.views.login` view passes the current
  331. :class:`~django.contrib.sites.models.Site` name to the template as
  332. ``{{ site_name }}``.
  333. * The shortcut view (``django.contrib.contenttypes.views.shortcut``)
  334. uses the domain of the current
  335. :class:`~django.contrib.sites.models.Site` object when calculating
  336. an object's URL.
  337. * In the admin framework, the "view on site" link uses the current
  338. :class:`~django.contrib.sites.models.Site` to work out the domain for the
  339. site that it will redirect to.
  340. ``RequestSite`` objects
  341. =======================
  342. .. _requestsite-objects:
  343. Some :doc:`django.contrib </ref/contrib/index>` applications take advantage of
  344. the sites framework but are architected in a way that doesn't *require* the
  345. sites framework to be installed in your database. (Some people don't want to,
  346. or just aren't *able* to install the extra database table that the sites
  347. framework requires.) For those cases, the framework provides a
  348. :class:`django.contrib.sites.requests.RequestSite` class, which can be used as
  349. a fallback when the database-backed sites framework is not available.
  350. .. class:: requests.RequestSite
  351. A class that shares the primary interface of
  352. :class:`~django.contrib.sites.models.Site` (i.e., it has
  353. ``domain`` and ``name`` attributes) but gets its data from a Django
  354. :class:`~django.http.HttpRequest` object rather than from a database.
  355. .. method:: __init__(request)
  356. Sets the ``name`` and ``domain`` attributes to the value of
  357. :meth:`~django.http.HttpRequest.get_host`.
  358. A :class:`~django.contrib.sites.requests.RequestSite` object has a similar
  359. interface to a normal :class:`~django.contrib.sites.models.Site` object,
  360. except its :meth:`~django.contrib.sites.requests.RequestSite.__init__()`
  361. method takes an :class:`~django.http.HttpRequest` object. It's able to deduce
  362. the ``domain`` and ``name`` by looking at the request's domain. It has
  363. ``save()`` and ``delete()`` methods to match the interface of
  364. :class:`~django.contrib.sites.models.Site`, but the methods raise
  365. :exc:`NotImplementedError`.
  366. ``get_current_site`` shortcut
  367. =============================
  368. Finally, to avoid repetitive fallback code, the framework provides a
  369. :func:`django.contrib.sites.shortcuts.get_current_site` function.
  370. .. function:: shortcuts.get_current_site(request)
  371. A function that checks if ``django.contrib.sites`` is installed and
  372. returns either the current :class:`~django.contrib.sites.models.Site`
  373. object or a :class:`~django.contrib.sites.requests.RequestSite` object
  374. based on the request. It looks up the current site based on
  375. :meth:`request.get_host() <django.http.HttpRequest.get_host>` if the
  376. :setting:`SITE_ID` setting is not defined.
  377. Both a domain and a port may be returned by :meth:`request.get_host()
  378. <django.http.HttpRequest.get_host>` when the Host header has a port
  379. explicitly specified, e.g. ``example.com:80``. In such cases, if the
  380. lookup fails because the host does not match a record in the database,
  381. the port is stripped and the lookup is retried with the domain part
  382. only. This does not apply to
  383. :class:`~django.contrib.sites.requests.RequestSite` which will always
  384. use the unmodified host.
  385. .. versionchanged:: 1.8
  386. Looking up the current site based on ``request.get_host()`` was added.
  387. .. versionchanged:: 1.9
  388. Retrying the lookup with the port stripped was added.