Debian Codegraph @

docs/ref/contrib/sites.txt

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