sites.txt 20 KB

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