sites.txt 17 KB

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