sites.txt 20 KB

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