def test_clear_site_cache_domain(self): site = Site.objects.create(name='example2.com', domain='example2.com') request = HttpRequest() request.META = { "SERVER_NAME": "example2.com", "SERVER_PORT": "80", } get_current_site(request) # prime the models.SITE_CACHE expected_cache = {site.domain: site} self.assertEqual(models.SITE_CACHE, expected_cache) # Site exists in 'default' database so using='other' shouldn't clear. clear_site_cache(Site, instance=site, using='other') self.assertEqual(models.SITE_CACHE, expected_cache) # using='default' should clear. clear_site_cache(Site, instance=site, using='default') self.assertEqual(models.SITE_CACHE, {})
def test_get_current_site_no_site_id_and_handle_port_fallback(self): request = HttpRequest() s1 = self.site s2 = Site.objects.create(domain='example.com:80', name='example.com:80') # Host header without port request.META = {'HTTP_HOST': 'example.com'} site = get_current_site(request) self.assertEqual(site, s1) # Host header with port - match, no fallback without port request.META = {'HTTP_HOST': 'example.com:80'} site = get_current_site(request) self.assertEqual(site, s2) # Host header with port - no match, fallback without port request.META = {'HTTP_HOST': 'example.com:81'} site = get_current_site(request) self.assertEqual(site, s1) # Host header with non-matching domain request.META = {'HTTP_HOST': 'example.net'} with self.assertRaises(ObjectDoesNotExist): get_current_site(request) # Ensure domain for RequestSite always matches host header with self.modify_settings(INSTALLED_APPS={'remove': 'djmodels.contrib.sites'}): request.META = {'HTTP_HOST': 'example.com'} site = get_current_site(request) self.assertEqual(site.name, 'example.com') request.META = {'HTTP_HOST': 'example.com:80'} site = get_current_site(request) self.assertEqual(site.name, 'example.com:80')
def test_get_current_site_no_site_id(self): request = HttpRequest() request.META = { "SERVER_NAME": "example.com", "SERVER_PORT": "80", } del settings.SITE_ID site = get_current_site(request) self.assertEqual(site.name, "example.com")
def test_clear_site_cache(self): request = HttpRequest() request.META = { "SERVER_NAME": "example.com", "SERVER_PORT": "80", } self.assertEqual(models.SITE_CACHE, {}) get_current_site(request) expected_cache = {self.site.id: self.site} self.assertEqual(models.SITE_CACHE, expected_cache) with self.settings(SITE_ID=''): get_current_site(request) expected_cache.update({self.site.domain: self.site}) self.assertEqual(models.SITE_CACHE, expected_cache) clear_site_cache(Site, instance=self.site, using='default') self.assertEqual(models.SITE_CACHE, {})
def test_get_current_site_host_with_trailing_dot(self): """ The site is matched if the name in the request has a trailing dot. """ request = HttpRequest() request.META = { 'SERVER_NAME': 'example.com.', 'SERVER_PORT': '80', } site = get_current_site(request) self.assertEqual(site.name, 'example.com')
def test_get_current_site(self): # The correct Site object is returned request = HttpRequest() request.META = { "SERVER_NAME": "example.com", "SERVER_PORT": "80", } site = get_current_site(request) self.assertIsInstance(site, Site) self.assertEqual(site.id, settings.SITE_ID) # An exception is raised if the sites framework is installed # but there is no matching Site site.delete() with self.assertRaises(ObjectDoesNotExist): get_current_site(request) # A RequestSite is returned if the sites framework is not installed with self.modify_settings(INSTALLED_APPS={'remove': 'djmodels.contrib.sites'}): site = get_current_site(request) self.assertIsInstance(site, RequestSite) self.assertEqual(site.name, "example.com")
def test_not_dependent_on_sites_app(self): """ The view returns a complete URL regardless of whether the sites framework is installed. """ user_ct = ContentType.objects.get_for_model(FooWithUrl) obj = FooWithUrl.objects.create(name='john') with self.modify_settings( INSTALLED_APPS={'append': 'djmodels.contrib.sites'}): response = shortcut(self.request, user_ct.id, obj.id) self.assertEqual( 'http://%s/users/john/' % get_current_site(self.request).domain, response._headers.get('location')[1]) with self.modify_settings( INSTALLED_APPS={'remove': 'djmodels.contrib.sites'}): response = shortcut(self.request, user_ct.id, obj.id) self.assertEqual('http://Example.com/users/john/', response._headers.get('location')[1])
def render(self, context): if 'request' in context: site_pk = get_current_site(context['request']).pk else: site_pk = settings.SITE_ID flatpages = FlatPage.objects.filter(sites__id=site_pk) # If a prefix was specified, add a filter if self.starts_with: flatpages = flatpages.filter( url__startswith=self.starts_with.resolve(context)) # If the provided user is not authenticated, or no user # was provided, filter the list to only public flatpages. if self.user: user = self.user.resolve(context) if not user.is_authenticated: flatpages = flatpages.filter(registration_required=False) else: flatpages = flatpages.filter(registration_required=False) context[self.context_name] = flatpages return ''
def flatpage(request, url): """ Public interface to the flat page view. Models: `flatpages.flatpages` Templates: Uses the template defined by the ``template_name`` field, or :template:`flatpages/default.html` if template_name is not defined. Context: flatpage `flatpages.flatpages` object """ if not url.startswith('/'): url = '/' + url site_id = get_current_site(request).id try: f = get_object_or_404(FlatPage, url=url, sites=site_id) except Http404: if not url.endswith('/') and settings.APPEND_SLASH: url += '/' f = get_object_or_404(FlatPage, url=url, sites=site_id) return HttpResponsePermanentRedirect('%s/' % request.path) else: raise return render_flatpage(request, f)
def shortcut(request, content_type_id, object_id): """ Redirect to an object's page based on a content-type ID and an object ID. """ # Look up the object, making sure it's got a get_absolute_url() function. try: content_type = ContentType.objects.get(pk=content_type_id) if not content_type.model_class(): raise Http404( _("Content type %(ct_id)s object has no associated model") % {'ct_id': content_type_id} ) obj = content_type.get_object_for_this_type(pk=object_id) except (ObjectDoesNotExist, ValueError): raise Http404( _("Content type %(ct_id)s object %(obj_id)s doesn't exist") % {'ct_id': content_type_id, 'obj_id': object_id} ) try: get_absolute_url = obj.get_absolute_url except AttributeError: raise Http404( _("%(ct_name)s objects don't have a get_absolute_url() method") % {'ct_name': content_type.name} ) absurl = get_absolute_url() # Try to figure out the object's domain, so we can do a cross-site redirect # if necessary. # If the object actually defines a domain, we're done. if absurl.startswith(('http://', 'https://', '//')): return HttpResponseRedirect(absurl) # Otherwise, we need to introspect the object's relationships for a # relation to the Site object try: object_domain = get_current_site(request).domain except ObjectDoesNotExist: object_domain = None if apps.is_installed('djmodels.contrib.sites'): Site = apps.get_model('sites.Site') opts = obj._meta for field in opts.many_to_many: # Look for a many-to-many relationship to Site. if field.remote_field.model is Site: site_qs = getattr(obj, field.name).all() if object_domain and site_qs.filter(domain=object_domain).exists(): # The current site's domain matches a site attached to the # object. break # Caveat: In the case of multiple related Sites, this just # selects the *first* one, which is arbitrary. site = site_qs.first() if site: object_domain = site.domain break else: # No many-to-many relationship to Site found. Look for a # many-to-one relationship to Site. for field in obj._meta.fields: if field.remote_field and field.remote_field.model is Site: try: site = getattr(obj, field.name) except Site.DoesNotExist: continue if site is not None: object_domain = site.domain break # If all that malarkey found an object domain, use it. Otherwise, fall back # to whatever get_absolute_url() returned. if object_domain is not None: protocol = request.scheme return HttpResponseRedirect('%s://%s%s' % (protocol, object_domain, absurl)) else: return HttpResponseRedirect(absurl)
def get_feed(self, obj, request): """ Return a feedgenerator.DefaultFeed object, fully populated, for this feed. Raise FeedDoesNotExist for invalid parameters. """ current_site = get_current_site(request) link = self._get_dynamic_attr('link', obj) link = add_domain(current_site.domain, link, request.is_secure()) feed = self.feed_type( title=self._get_dynamic_attr('title', obj), subtitle=self._get_dynamic_attr('subtitle', obj), link=link, description=self._get_dynamic_attr('description', obj), language=settings.LANGUAGE_CODE, feed_url=add_domain( current_site.domain, self._get_dynamic_attr('feed_url', obj) or request.path, request.is_secure(), ), author_name=self._get_dynamic_attr('author_name', obj), author_link=self._get_dynamic_attr('author_link', obj), author_email=self._get_dynamic_attr('author_email', obj), categories=self._get_dynamic_attr('categories', obj), feed_copyright=self._get_dynamic_attr('feed_copyright', obj), feed_guid=self._get_dynamic_attr('feed_guid', obj), ttl=self._get_dynamic_attr('ttl', obj), **self.feed_extra_kwargs(obj)) title_tmp = None if self.title_template is not None: try: title_tmp = loader.get_template(self.title_template) except TemplateDoesNotExist: pass description_tmp = None if self.description_template is not None: try: description_tmp = loader.get_template( self.description_template) except TemplateDoesNotExist: pass for item in self._get_dynamic_attr('items', obj): context = self.get_context_data(item=item, site=current_site, obj=obj, request=request) if title_tmp is not None: title = title_tmp.render(context, request) else: title = self._get_dynamic_attr('item_title', item) if description_tmp is not None: description = description_tmp.render(context, request) else: description = self._get_dynamic_attr('item_description', item) link = add_domain( current_site.domain, self._get_dynamic_attr('item_link', item), request.is_secure(), ) enclosures = self._get_dynamic_attr('item_enclosures', item) author_name = self._get_dynamic_attr('item_author_name', item) if author_name is not None: author_email = self._get_dynamic_attr('item_author_email', item) author_link = self._get_dynamic_attr('item_author_link', item) else: author_email = author_link = None tz = get_default_timezone() pubdate = self._get_dynamic_attr('item_pubdate', item) if pubdate and is_naive(pubdate): pubdate = make_aware(pubdate, tz) updateddate = self._get_dynamic_attr('item_updateddate', item) if updateddate and is_naive(updateddate): updateddate = make_aware(updateddate, tz) feed.add_item( title=title, link=link, description=description, unique_id=self._get_dynamic_attr('item_guid', item, link), unique_id_is_permalink=self._get_dynamic_attr( 'item_guid_is_permalink', item), enclosures=enclosures, pubdate=pubdate, updateddate=updateddate, author_name=author_name, author_email=author_email, author_link=author_link, categories=self._get_dynamic_attr('item_categories', item), item_copyright=self._get_dynamic_attr('item_copyright', item), **self.item_extra_kwargs(item)) return feed