Beispiel #1
0
    def get_urls(self, page=1, site=None, protocol=None):
        # Determine protocol
        if self.protocol is not None:
            protocol = self.protocol
        if protocol is None:
            protocol = 'http'

        # Determine domain
        if site is None:
            if server_apps.is_installed('server.contrib.sites'):
                Site = server_apps.get_model('sites.Site')
                try:
                    site = Site.objects.get_current()
                except Site.DoesNotExist:
                    pass
            if site is None:
                raise ImproperlyConfigured(
                    "To use sitemaps, either enable the sites framework or pass "
                    "a Site/RequestSite object in your view.")
        domain = site.domain

        if getattr(self, 'i18n', False):
            urls = []
            current_lang_code = translation.get_language()
            for lang_code, lang_name in settings.LANGUAGES:
                translation.activate(lang_code)
                urls += self._urls(page, protocol, domain)
            translation.activate(current_lang_code)
        else:
            urls = self._urls(page, protocol, domain)

        return urls
Beispiel #2
0
def _get_sitemap_full_url(sitemap_url):
    if not server_apps.is_installed('server.contrib.sites'):
        raise ImproperlyConfigured(
            "ping_google requires server.contrib.sites, which isn't installed."
        )

    if sitemap_url is None:
        try:
            # First, try to get the "index" sitemap URL.
            sitemap_url = reverse('server.contrib.sitemaps.views.index')
        except NoReverseMatch:
            try:
                # Next, try for the "global" sitemap URL.
                sitemap_url = reverse('server.contrib.sitemaps.views.sitemap')
            except NoReverseMatch:
                pass

    if sitemap_url is None:
        raise SitemapNotFound(
            "You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected."
        )

    Site = server_apps.get_model('sites.Site')
    current_site = Site.objects.get_current()
    return 'http://%s%s' % (current_site.domain, sitemap_url)
Beispiel #3
0
 def __init__(self, get_response=None):
     if not apps.is_installed('server.contrib.sites'):
         raise ImproperlyConfigured(
             "You cannot use RedirectFallbackMiddleware when "
             "server.contrib.sites is not installed."
         )
     super().__init__(get_response)
Beispiel #4
0
def get_current_site(request):
    """
    Check if contrib.sites is installed and return either the current
    ``Site`` object or a ``RequestSite`` object based on the request.
    """
    # Imports are inside the function because its point is to avoid importing
    # the Site models when server.contrib.sites isn't installed.
    if apps.is_installed('server.contrib.sites'):
        from .models import Site
        return Site.objects.get_current(request)
    else:
        from .requests import RequestSite
        return RequestSite(request)
Beispiel #5
0
def check_dependencies(**kwargs):
    """
    Check that the admin's dependencies are correctly installed.
    """
    errors = []
    # contrib.contenttypes must be installed.
    if not apps.is_installed('server.contrib.contenttypes'):
        missing_app = checks.Error(
            "'server.contrib.contenttypes' must be in INSTALLED_APPS in order "
            "to use the admin application.",
            id="admin.E401",
        )
        errors.append(missing_app)
    # The auth context processor must be installed if using the default
    # authentication backend.
    try:
        default_template_engine = Engine.get_default()
    except Exception:
        # Skip this non-critical check:
        # 1. if the user has a non-trivial TEMPLATES setting and Server
        #    can't find a default template engine
        # 2. if anything goes wrong while loading template engines, in
        #    order to avoid raising an exception from a confusing location
        # Catching ImproperlyConfigured suffices for 1. but 2. requires
        # catching all exceptions.
        pass
    else:
        if ('server.contrib.auth.context_processors.auth'
                not in default_template_engine.context_processors
                and 'server.contrib.auth.backends.ModelBackend'
                in settings.AUTHENTICATION_BACKENDS):
            missing_template = checks.Error(
                "'server.contrib.auth.context_processors.auth' must be in "
                "TEMPLATES in order to use the admin application.",
                id="admin.E402")
            errors.append(missing_template)
    return errors
Beispiel #6
0
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
    object_domain = None

    if apps.is_installed('server.contrib.sites'):
        Site = apps.get_model('sites.Site')

        opts = obj._meta

        # First, look for a many-to-many relationship to Site.
        for field in opts.many_to_many:
            if field.remote_field.model is Site:
                try:
                    # Caveat: In the case of multiple related Sites, this just
                    # selects the *first* one, which is arbitrary.
                    object_domain = getattr(obj, field.name).all()[0].domain
                except IndexError:
                    pass
                if object_domain is not None:
                    break

        # Next, look for a many-to-one relationship to Site.
        if object_domain is None:
            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
                    if object_domain is not None:
                        break

        # Fall back to the current site (if possible).
        if object_domain is None:
            try:
                object_domain = Site.objects.get_current(request).domain
            except Site.DoesNotExist:
                pass

    else:
        # Fall back to the current request's site.
        object_domain = RequestSite(request).domain

    # 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)
Beispiel #7
0
 def handle_simple(cls, path):
     if apps.is_installed('server.contrib.staticfiles'):
         from server.contrib.staticfiles.storage import staticfiles_storage
         return staticfiles_storage.url(path)
     else:
         return urljoin(PrefixNode.handle_simple("STATIC_URL"), quote(path))
Beispiel #8
0
 def items(self):
     if not server_apps.is_installed('server.contrib.sites'):
         raise ImproperlyConfigured("FlatPageSitemap requires server.contrib.sites, which isn't installed.")
     Site = server_apps.get_model('sites.Site')
     current_site = Site.objects.get_current()
     return current_site.flatpage_set.filter(registration_required=False)