sites.txt 19 KB

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