Esempio n. 1
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)
Esempio n. 2
0
    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        rel_to = self.rel.model
        if rel_to in self.admin_site._registry:
            # The related object is registered with the same AdminSite
            related_url = reverse(
                'admin:%s_%s_changelist' % (
                    rel_to._meta.app_label,
                    rel_to._meta.model_name,
                ),
                current_app=self.admin_site.name,
            )

            params = self.url_parameters()
            if params:
                related_url += '?' + '&'.join('%s=%s' % (k, v)
                                                  for k, v in params.items())
            context['related_url'] = mark_safe(related_url)
            context['link_title'] = _('Lookup')
            # The JavaScript code looks for this class.
            context['widget']['attrs'].setdefault(
                'class', 'vForeignKeyRawIdAdminField')
        if context['widget']['value']:
            context['link_label'], context[
                'link_url'] = self.label_and_url_for_value(value)
        return context
Esempio n. 3
0
 def get_context_data(self, **kwargs):
     return super().get_context_data(
         **{
             **kwargs,
             'root_path': reverse('admin:index'),
             **admin.site.each_context(self.request),
         })
Esempio n. 4
0
    def format_callback(obj):
        model = obj.__class__
        has_admin = model in admin_site._registry
        opts = obj._meta

        no_edit_link = '%s: %s' % (capfirst(opts.verbose_name), obj)

        if has_admin:
            if not admin_site._registry[model].has_delete_permission(
                    request, obj):
                perms_needed.add(opts.verbose_name)
            try:
                admin_url = reverse(
                    '%s:%s_%s_change' %
                    (admin_site.name, opts.app_label, opts.model_name), None,
                    (quote(obj.pk), ))
            except NoReverseMatch:
                # Change url doesn't exist -- don't display link to edit
                return no_edit_link

            # Display a link to the admin page.
            return format_html('{}: <a href="{}">{}</a>',
                               capfirst(opts.verbose_name), admin_url, obj)
        else:
            # Don't display link to edit, because it either has no
            # admin or is edited inline.
            return no_edit_link
Esempio n. 5
0
    def render(self, context):
        from server.urls import reverse, NoReverseMatch
        args = [arg.resolve(context) for arg in self.args]
        kwargs = {k: v.resolve(context) for k, v in self.kwargs.items()}
        view_name = self.view_name.resolve(context)
        try:
            current_app = context.request.current_app
        except AttributeError:
            try:
                current_app = context.request.resolver_match.namespace
            except AttributeError:
                current_app = None
        # Try to look up the URL. If it fails, raise NoReverseMatch unless the
        # {% url ... as var %} construct is used, in which case return nothing.
        url = ''
        try:
            url = reverse(view_name,
                          args=args,
                          kwargs=kwargs,
                          current_app=current_app)
        except NoReverseMatch:
            if self.asvar is None:
                raise

        if self.asvar:
            context[self.asvar] = url
            return ''
        else:
            if context.autoescape:
                url = conditional_escape(url)
            return url
Esempio n. 6
0
def index(request,
          sitemaps,
          template_name='sitemap_index.xml',
          content_type='application/xml',
          sitemap_url_name='server.contrib.sitemaps.views.sitemap'):

    req_protocol = request.scheme
    req_site = get_current_site(request)

    sites = []  # all sections' sitemap URLs
    for section, site in sitemaps.items():
        # For each section label, add links of all pages of its sitemap
        # (usually generated by the `sitemap` view).
        if callable(site):
            site = site()
        protocol = req_protocol if site.protocol is None else site.protocol
        sitemap_url = reverse(sitemap_url_name, kwargs={'section': section})
        absolute_url = '%s://%s%s' % (protocol, req_site.domain, sitemap_url)
        sites.append(absolute_url)
        # Add links to all pages of the sitemap.
        for page in range(2, site.paginator.num_pages + 1):
            sites.append('%s?p=%s' % (absolute_url, page))

    return TemplateResponse(request,
                            template_name, {'sitemaps': sites},
                            content_type=content_type)
Esempio n. 7
0
def parse_rst(text, default_reference_context, thing_being_parsed=None):
    """
    Convert the string from reST to an XHTML fragment.
    """
    overrides = {
        'doctitle_xform': True,
        'initial_header_level': 3,
        "default_reference_context": default_reference_context,
        "link_base": reverse('server-admindocs-docroot').rstrip('/'),
        'raw_enabled': False,
        'file_insertion_enabled': False,
    }
    thing_being_parsed = thing_being_parsed and force_bytes(
        '<%s>' % thing_being_parsed)
    # Wrap ``text`` in some reST that sets the default role to ``cmsreference``,
    # then restores it.
    source = """
.. default-role:: cmsreference

%s

.. default-role::
"""
    parts = docutils.core.publish_parts(
        source % text,
        source_path=thing_being_parsed,
        destination_path=None,
        writer_name='html',
        settings_overrides=overrides,
    )
    return mark_safe(parts['fragment'])
Esempio n. 8
0
 def location(self, obj):
     return reverse(
         'server.contrib.gis.sitemaps.views.%s' % self.geo_format,
         kwargs={
             'label': obj[0],
             'model': obj[1],
             'field_name': obj[2],
         },
     )
Esempio n. 9
0
    def get_redirect_url(self, *args, **kwargs):
        """
        Return the URL redirect to. Keyword arguments from the URL pattern
        match generating the redirect request are provided as kwargs to this
        method.
        """
        if self.url:
            url = self.url % kwargs
        elif self.pattern_name:
            url = reverse(self.pattern_name, args=args, kwargs=kwargs)
        else:
            return None

        args = self.request.META.get('QUERY_STRING', '')
        if args and self.query_string:
            url = "%s?%s" % (url, args)
        return url
Esempio n. 10
0
    def label_and_url_for_value(self, value):
        key = self.rel.get_related_field().name
        try:
            obj = self.rel.model._default_manager.using(
                self.db).get(**{key: value})
        except (ValueError, self.rel.model.DoesNotExist, ValidationError):
            return '', ''

        try:
            url = reverse('%s:%s_%s_change' % (
                self.admin_site.name,
                obj._meta.app_label,
                obj._meta.object_name.lower(),
            ),
                          args=(obj.pk, ))
        except NoReverseMatch:
            url = ''  # Admin not registered for target model.

        return Truncator(obj).words(14, truncate='...'), url
Esempio n. 11
0
def resolve_url(to, *args, **kwargs):
    """
    Return a URL appropriate for the arguments passed.

    The arguments could be:

        * A model: the model's `get_absolute_url()` function will be called.

        * A view name, possibly with arguments: `urls.reverse()` will be used
          to reverse-resolve the name.

        * A URL, which will be returned as-is.
    """
    # If it's a model, use get_absolute_url()
    if hasattr(to, 'get_absolute_url'):
        return to.get_absolute_url()

    if isinstance(to, Promise):
        # Expand the lazy instance, as it can cause issues when it is passed
        # further to some Python functions like urlparse.
        to = str(to)

    if isinstance(to, str):
        # Handle relative URLs
        if to.startswith(('./', '../')):
            return to

    # Next try a reverse URL resolution.
    try:
        return reverse(to, args=args, kwargs=kwargs)
    except NoReverseMatch:
        # If this is a callable, re-raise.
        if callable(to):
            raise
        # If this doesn't "feel" like a URL, re-raise.
        if '/' not in to and '.' not in to:
            raise

    # Finally, fall back and assume it's a URL
    return to
Esempio n. 12
0
 def get_url(self):
     model = self.rel.model
     return reverse(self.url_name %
                    (self.admin_site.name, model._meta.app_label,
                     model._meta.model_name))
Esempio n. 13
0
 def get_related_url(self, info, action, *args):
     return reverse("admin:%s_%s_%s" % (info + (action, )),
                    current_app=self.admin_site.name,
                    args=args)
Esempio n. 14
0
 def url_for_result(self, result):
     pk = getattr(result, self.pk_attname)
     return reverse('admin:%s_%s_change' % (self.opts.app_label,
                                            self.opts.model_name),
                    args=(quote(pk),),
                    current_app=self.model_admin.admin_site.name)
Esempio n. 15
0
    def user_change_password(self, request, id, form_url=''):
        if not self.has_change_permission(request):
            raise PermissionDenied
        user = self.get_object(request, unquote(id))
        if user is None:
            raise Http404(
                _('%(name)s object with primary key %(key)r does not exist.') %
                {
                    'name': self.model._meta.verbose_name,
                    'key': escape(id),
                })
        if request.method == 'POST':
            form = self.change_password_form(user, request.POST)
            if form.is_valid():
                form.save()
                change_message = self.construct_change_message(
                    request, form, None)
                self.log_change(request, user, change_message)
                msg = gettext('Password changed successfully.')
                messages.success(request, msg)
                update_session_auth_hash(request, form.user)
                return HttpResponseRedirect(
                    reverse(
                        '%s:%s_%s_change' % (
                            self.admin_site.name,
                            user._meta.app_label,
                            user._meta.model_name,
                        ),
                        args=(user.pk, ),
                    ))
        else:
            form = self.change_password_form(user)

        fieldsets = [(None, {'fields': list(form.base_fields)})]
        adminForm = admin.helpers.AdminForm(form, fieldsets, {})

        context = {
            'title':
            _('Change password: %s') % escape(user.get_username()),
            'adminForm':
            adminForm,
            'form_url':
            form_url,
            'form':
            form,
            'is_popup': (IS_POPUP_VAR in request.POST
                         or IS_POPUP_VAR in request.GET),
            'add':
            True,
            'change':
            False,
            'has_delete_permission':
            False,
            'has_change_permission':
            True,
            'has_absolute_url':
            False,
            'opts':
            self.model._meta,
            'original':
            user,
            'save_as':
            False,
            'show_save':
            True,
            **self.admin_site.each_context(request),
        }

        request.current_app = self.admin_site.name

        return TemplateResponse(
            request,
            self.change_user_password_template
            or 'admin/auth/user/change_password.html',
            context,
        )