Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Made more extensive use of get_current_site

Refs #15089
  • Loading branch information...
commit 6c2faaceb0482267cec19da0ff432984028f9d0c 1 parent 1cd6e04
Claude Paroz authored September 28, 2012
4  django/contrib/comments/moderation.py
@@ -62,7 +62,7 @@ class EntryModerator(CommentModerator):
62 62
 from django.db.models.base import ModelBase
63 63
 from django.template import Context, loader
64 64
 from django.contrib import comments
65  
-from django.contrib.sites.models import Site
  65
+from django.contrib.sites.models import get_current_site
66 66
 from django.utils import timezone
67 67
 
68 68
 class AlreadyModerated(Exception):
@@ -240,7 +240,7 @@ def email(self, comment, content_object, request):
240 240
         t = loader.get_template('comments/comment_notification_email.txt')
241 241
         c = Context({ 'comment': comment,
242 242
                       'content_object': content_object })
243  
-        subject = '[%s] New comment posted on "%s"' % (Site.objects.get_current().name,
  243
+        subject = '[%s] New comment posted on "%s"' % (get_current_site(request).name,
244 244
                                                           content_object)
245 245
         message = t.render(c)
246 246
         send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
5  django/contrib/contenttypes/tests.py
@@ -3,7 +3,7 @@
3 3
 from django.db import models
4 4
 from django.contrib.contenttypes.models import ContentType
5 5
 from django.contrib.contenttypes.views import shortcut
6  
-from django.contrib.sites.models import Site
  6
+from django.contrib.sites.models import Site, get_current_site
7 7
 from django.http import HttpRequest, Http404
8 8
 from django.test import TestCase
9 9
 from django.utils.http import urlquote
@@ -219,9 +219,8 @@ def test_shortcut_view(self):
219 219
         obj = FooWithUrl.objects.create(name="john")
220 220
 
221 221
         if Site._meta.installed:
222  
-            current_site = Site.objects.get_current()
223 222
             response = shortcut(request, user_ct.id, obj.id)
224  
-            self.assertEqual("http://%s/users/john/" % current_site.domain,
  223
+            self.assertEqual("http://%s/users/john/" % get_current_site(request).domain,
225 224
                              response._headers.get("location")[1])
226 225
 
227 226
         Site._meta.installed = False
7  django/contrib/flatpages/templatetags/flatpages.py
... ...
@@ -1,6 +1,7 @@
1 1
 from django import template
2 2
 from django.conf import settings
3 3
 from django.contrib.flatpages.models import FlatPage
  4
+from django.contrib.sites.models import get_current_site
4 5
 
5 6
 
6 7
 register = template.Library()
@@ -19,7 +20,11 @@ def __init__(self, context_name, starts_with=None, user=None):
19 20
             self.user = None
20 21
 
21 22
     def render(self, context):
22  
-        flatpages = FlatPage.objects.filter(sites__id=settings.SITE_ID)
  23
+        if 'request' in context:
  24
+            site_pk = get_current_site(context['request']).pk
  25
+        else:
  26
+            site_pk = settings.SITE_ID
  27
+        flatpages = FlatPage.objects.filter(sites__id=site_pk)
23 28
         # If a prefix was specified, add a filter
24 29
         if self.starts_with:
25 30
             flatpages = flatpages.filter(
6  django/contrib/redirects/middleware.py
... ...
@@ -1,4 +1,5 @@
1 1
 from django.contrib.redirects.models import Redirect
  2
+from django.contrib.sites.models import get_current_site
2 3
 from django import http
3 4
 from django.conf import settings
4 5
 
@@ -7,14 +8,15 @@ def process_response(self, request, response):
7 8
         if response.status_code != 404:
8 9
             return response # No need to check for a redirect for non-404 responses.
9 10
         path = request.get_full_path()
  11
+        current_site = get_current_site(request)
10 12
         try:
11  
-            r = Redirect.objects.get(site__id__exact=settings.SITE_ID, old_path=path)
  13
+            r = Redirect.objects.get(site__id__exact=current_site.id, old_path=path)
12 14
         except Redirect.DoesNotExist:
13 15
             r = None
14 16
         if r is None and settings.APPEND_SLASH:
15 17
             # Try removing the trailing slash.
16 18
             try:
17  
-                r = Redirect.objects.get(site__id__exact=settings.SITE_ID,
  19
+                r = Redirect.objects.get(site__id__exact=current_site.id,
18 20
                     old_path=path[:path.rfind('/')]+path[path.rfind('/')+1:])
19 21
             except Redirect.DoesNotExist:
20 22
                 pass
2  django/views/decorators/cache.py
@@ -12,7 +12,7 @@ def cache_page(*args, **kwargs):
12 12
     The cache is keyed by the URL and some data from the headers.
13 13
     Additionally there is the key prefix that is used to distinguish different
14 14
     cache areas in a multi-site setup. You could use the
15  
-    sites.get_current().domain, for example, as that is unique across a Django
  15
+    sites.get_current_site().domain, for example, as that is unique across a Django
16 16
     project.
17 17
 
18 18
     Additionally, all headers from the response's Vary header will be taken
53  docs/ref/contrib/sites.txt
@@ -80,11 +80,11 @@ This accomplishes several things quite nicely:
80 80
   The view code that displays a given story just checks to make sure the
81 81
   requested story is on the current site. It looks something like this::
82 82
 
83  
-      from django.conf import settings
  83
+      from django.contrib.sites.models import get_current_site
84 84
 
85 85
       def article_detail(request, article_id):
86 86
           try:
87  
-              a = Article.objects.get(id=article_id, sites__id__exact=settings.SITE_ID)
  87
+              a = Article.objects.get(id=article_id, sites__id__exact=get_current_site(request).id)
88 88
           except Article.DoesNotExist:
89 89
               raise Http404
90 90
           # ...
@@ -131,49 +131,36 @@ For example::
131 131
             # Do something else.
132 132
 
133 133
 Of course, it's ugly to hard-code the site IDs like that. This sort of
134  
-hard-coding is best for hackish fixes that you need done quickly. A slightly
  134
+hard-coding is best for hackish fixes that you need done quickly. The
135 135
 cleaner way of accomplishing the same thing is to check the current site's
136 136
 domain::
137 137
 
138  
-    from django.conf import settings
139  
-    from django.contrib.sites.models import Site
  138
+    from django.contrib.sites.models import get_current_site
140 139
 
141 140
     def my_view(request):
142  
-        current_site = Site.objects.get(id=settings.SITE_ID)
  141
+        current_site = get_current_site(request)
143 142
         if current_site.domain == 'foo.com':
144 143
             # Do something
145 144
         else:
146 145
             # Do something else.
147 146
 
148  
-The idiom of retrieving the :class:`~django.contrib.sites.models.Site` object
149  
-for the value of :setting:`settings.SITE_ID <SITE_ID>` is quite common, so
150  
-the :class:`~django.contrib.sites.models.Site` model's manager has a
151  
-``get_current()`` method. This example is equivalent to the previous one::
  147
+This has also the advantage of checking if the sites framework is installed, and
  148
+return a :class:`RequestSite` instance if it is not.
  149
+
  150
+If you don't have access to the request object, you can use the
  151
+``get_current()`` method of the :class:`~django.contrib.sites.models.Site`
  152
+model's manager. You should then ensure that your settings file does contain
  153
+the :setting:`SITE_ID` setting. This example is equivalent to the previous one::
152 154
 
153 155
     from django.contrib.sites.models import Site
154 156
 
155  
-    def my_view(request):
  157
+    def my_function_without_request():
156 158
         current_site = Site.objects.get_current()
157 159
         if current_site.domain == 'foo.com':
158 160
             # Do something
159 161
         else:
160 162
             # Do something else.
161 163
 
162  
-For code which relies on getting the current domain but cannot be certain
163  
-that the sites framework will be installed for any given project, there is a
164  
-utility function :func:`~django.contrib.sites.models.get_current_site` that
165  
-takes a request object as an argument and returns either a Site instance (if
166  
-the sites framework is installed) or a RequestSite instance (if it is not).
167  
-This allows loose coupling with the sites framework and provides a usable
168  
-fallback for cases where it is not installed.
169  
-
170  
-.. function:: get_current_site(request)
171  
-
172  
-    Checks if contrib.sites is installed and returns either the current
173  
-    :class:`~django.contrib.sites.models.Site` object or a
174  
-    :class:`~django.contrib.sites.models.RequestSite` object based on
175  
-    the request.
176  
-
177 164
 Getting the current domain for display
178 165
 --------------------------------------
179 166
 
@@ -192,14 +179,14 @@ current site's :attr:`~django.contrib.sites.models.Site.name` and
192 179
 
193 180
 Here's an example of what the form-handling view looks like::
194 181
 
195  
-    from django.contrib.sites.models import Site
  182
+    from django.contrib.sites.models import get_current_site
196 183
     from django.core.mail import send_mail
197 184
 
198 185
     def register_for_newsletter(request):
199 186
         # Check form values, etc., and subscribe the user.
200 187
         # ...
201 188
 
202  
-        current_site = Site.objects.get_current()
  189
+        current_site = get_current_site(request)
203 190
         send_mail('Thanks for subscribing to %s alerts' % current_site.name,
204 191
             'Thanks for your subscription. We appreciate it.\n\n-The %s team.' % current_site.name,
205 192
             'editor@%s' % current_site.domain,
@@ -370,19 +357,19 @@ Here's how Django uses the sites framework:
370 357
 
371 358
 * In the :mod:`redirects framework <django.contrib.redirects>`, each
372 359
   redirect object is associated with a particular site. When Django searches
373  
-  for a redirect, it takes into account the current :setting:`SITE_ID`.
  360
+  for a redirect, it takes into account the current site.
374 361
 
375 362
 * In the comments framework, each comment is associated with a particular
376 363
   site. When a comment is posted, its
377  
-  :class:`~django.contrib.sites.models.Site` is set to the current
378  
-  :setting:`SITE_ID`, and when comments are listed via the appropriate
379  
-  template tag, only the comments for the current site are displayed.
  364
+  :class:`~django.contrib.sites.models.Site` is set to the current site,
  365
+  and when comments are listed via the appropriate template tag, only the
  366
+  comments for the current site are displayed.
380 367
 
381 368
 * In the :mod:`flatpages framework <django.contrib.flatpages>`, each
382 369
   flatpage is associated with a particular site. When a flatpage is created,
383 370
   you specify its :class:`~django.contrib.sites.models.Site`, and the
384 371
   :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`
385  
-  checks the current :setting:`SITE_ID` in retrieving flatpages to display.
  372
+  checks the current site in retrieving flatpages to display.
386 373
 
387 374
 * In the :mod:`syndication framework <django.contrib.syndication>`, the
388 375
   templates for ``title`` and ``description`` automatically have access to a

0 notes on commit 6c2faac

Please sign in to comment.
Something went wrong with that request. Please try again.