Python django.templatetags.static.static() Examples

The following are 30 code examples of django.templatetags.static.static(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.templatetags.static , or try the search function .
Example #1
Source File: markdown.py    From FIR with GNU General Public License v3.0 7 votes vote down vote up
def rich_edit_static(context):

    files = [
        "<link href=\"%s\" rel=\"stylesheet\"/>" % static(
            "simplemde/simplemde.min.css"),
        "<link href=\"%s\" rel=\"stylesheet\"/>" % static(
            "font-awesome/css/font-awesome.min.css"),
        "<script type=\"text/javascript\" src=\"%s\"></script>" % static(
            "simplemde/marked.min.js"),
        "<script type=\"text/javascript\" src=\"%s\"></script>" % static(
            "simplemde/simplemde.min.js"),
        "<script type=\"text/javascript\" src=\"%s\"></script>" % static(
            "simplemde/inline-attachment.min.js"),
        "<script type=\"text/javascript\" src=\"%s\"></script>" % static(
            "simplemde/codemirror.inline-attachment.js"),
        "<script type=\"text/javascript\" src=\"%s\"></script>" % static(
            "simplemde/markdown.js")
    ]
    return mark_safe("\n".join(files)) 
Example #2
Source File: admin.py    From django-healthchecks with MIT License 7 votes vote down vote up
def last_beat_column(self, object):
        last_beat = object.last_beat
        if is_aware(last_beat):
            # Only for USE_TZ=True
            last_beat = localtime(last_beat)

        last_beat_str = localize(last_beat)
        if object.is_expired:
            # Make clearly visible
            alert_icon = static('admin/img/icon-alert.svg')
            return format_html(
                '<div style="vertical-align: middle; display: inline-block;">'
                '  <img src="{}" style="vertical-align: middle;"> '
                '  <span style="color: #efb80b; vertical-align: middle;">{}</span>'
                '</div>',
                alert_icon, last_beat_str
            )
        else:
            return last_beat_str 
Example #3
Source File: views.py    From ldap-oauth2 with GNU General Public License v3.0 6 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super(DocView, self).get_context_data(**kwargs)
        context['login_js_url'] = static('widget/js/login.min.js')
        context['Message_ID'] = make_msgid()
        context['SORTED_DISCIPLINES'] = SORTED_DISCIPLINES
        context['DEGREES'] = DEGREES
        context['HOSTELS'] = HOSTELS
        context['SEXES'] = SEXES
        context['USER_TYPES'] = UserProfile.objects.values_list('type').distinct()

        # Mark all tabs as inactive
        for tab_ in self.tabs:
            tab_.is_active = False

        tab = context.get('tab', '')
        for tab_ in self.tabs:
            if tab == tab_.tab_name:
                tab = tab_
                break
        else:
            tab = self.tabs[0]
        tab.is_active = True
        context['tabs'] = self.tabs
        context['active_tab'] = tab
        return context 
Example #4
Source File: utils.py    From sal with Apache License 2.0 6 votes vote down vote up
def get_plugin_placeholder_markup(group_type='all', group_id=None):
    result = []
    hidden = get_hidden_plugins(group_type, group_id)
    group_oses = get_member_oses(group_type, group_id)
    display_plugins = [p for p in Plugin.objects.exclude(name__in=hidden).order_by('order')]
    for enabled_plugin in display_plugins:
        name = enabled_plugin.name
        yapsy_plugin = PluginManager.get_plugin_by_name(name)
        if not yapsy_plugin:
            continue
        # Skip this plugin if the group's members OS families aren't supported
        # ...but only if this group has any members (group_oses is not empty
        plugin_os_families = set(yapsy_plugin.get_supported_os_families())
        if group_oses and not plugin_os_families.intersection(group_oses):
            continue
        width = yapsy_plugin.get_widget_width(group_type=group_type, group_id=group_id)
        html = ('<div id="plugin-{}" class="col-md-{}">\n'
                '    <img class="center-block blue-spinner" src="{}"/>\n'
                '</div>\n'.format(name, width, static('img/blue-spinner.gif')))
        result.append({'name': name, 'width': width, 'html': html})

    return order_plugin_output(result) 
Example #5
Source File: views.py    From django-sitemessage with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def mark_read(request, message_id, dispatch_id, hashed, redirect_to=None):
    """Handles mark message as read request.

    :param Request request:
    :param int message_id:
    :param int dispatch_id:
    :param str hashed:
    :param str redirect_to:
    :return:
    """
    if redirect_to is None:
        redirect_to = get_static_url('img/sitemessage/blank.png')

    return _generic_view(
        'handle_mark_read_request', sig_mark_read_failed,
        request, message_id, dispatch_id, hashed, redirect_to=redirect_to
    ) 
Example #6
Source File: middleware.py    From wagtail-tag-manager with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _add_lazy_manager(self):
        if hasattr(self.response, "content"):
            doc = BeautifulSoup(self.response.content, "html.parser")

            if doc.body:
                doc.body["data-wtm-config"] = reverse("wtm:config")
                doc.body["data-wtm-lazy"] = reverse("wtm:lazy")

                if getattr(settings, "WTM_INJECT_STYLE", True):
                    link = doc.new_tag("link")
                    link["rel"] = "stylesheet"
                    link["type"] = "text/css"
                    link["href"] = static("wagtail_tag_manager/wtm.bundle.css")
                    doc.body.append(link)

                if getattr(settings, "WTM_INJECT_SCRIPT", True):
                    script = doc.new_tag("script")
                    script["type"] = "text/javascript"
                    script["src"] = static("wagtail_tag_manager/wtm.bundle.js")
                    doc.body.append(script)

            self.response.content = doc.decode() 
Example #7
Source File: tinymce.py    From digihel with MIT License 6 votes vote down vote up
def build_js_init_arguments(self):
        args = super(DigiHelTinyMCERichTextArea, self).build_js_init_arguments()
        args.update(
            plugins=self.plugins,
        )
        args.pop('menubar', None)  # Always enable the menubar
        args['content_css'].append(static('css/tinymce-content.css'))
        args['skin'] = 'wagtail'
        args['height'] = 600
        args['style_formats'] = [
            {'title': 'Additional info','block': 'section','classes': 'more-info', 'wrapper': 'true'},
            {'title': 'Document link','inline': 'span','classes': 'document-link'},
        ]
        args['style_formats_merge'] = True
        args['extended_valid_elements'] = 'div[class]'
        return args 
Example #8
Source File: widgets.py    From freedomvote with GNU General Public License v3.0 6 votes vote down vote up
def render(self, name, value, attrs=None,):

        substitutions = {
            'clear_checkbox_label': self.clear_checkbox_label,
            'initial' : '<img class="img-responsive img-thumbnail" width="%s" src="%s">' % (
                force_text('100%'),
                force_text(get_thumbnailer(value)['medium'].url if value and hasattr(value, 'url') else static('images/placeholder.svg'))
            )
        }
        template = '%(initial)s%(input)s'

        substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)

        if not self.is_required:
            template = '%(initial)s%(clear_template)s%(input)s'
            checkbox_name = self.clear_checkbox_name(name)
            checkbox_id = self.clear_checkbox_id(checkbox_name)
            substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name)
            substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id)
            substitutions['clear'] = CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id})
            substitutions['clear_template'] = self.clear_checkbox_name(checkbox_name)

        return mark_safe(template % substitutions) 
Example #9
Source File: manifest.py    From Inboxen with GNU Affero General Public License v3.0 6 votes vote down vote up
def manifest(request):
    data = {
        "name": settings.SITE_NAME,
        "short_name": settings.SITE_NAME,
        "icons": [
            {
                "src": static("imgs/megmelon-icon-white.png"),
                "sizes": "128x128",
                "type": "image/png"
            }
        ],
        "theme_color": "#ffffff",
        "background_color": "#ffffff",
        "display": "browser",
        "start_url": reverse("user-home"),
    }

    return JsonResponse(data) 
Example #10
Source File: test_forms.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_absolute_url(self):
        m = Media(
            css={'all': ('path/to/css1', '/path/to/css2')},
            js=(
                '/path/to/js1',
                'http://media.other.com/path/to/js2',
                'https://secure.other.com/path/to/js3',
                static('relative/path/to/js4'),
            ),
        )
        self.assertEqual(
            str(m),
            """<link href="https://example.com/assets/path/to/css1" type="text/css" media="all" rel="stylesheet">
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
<script type="text/javascript" src="https://example.com/assets/relative/path/to/js4"></script>"""
        ) 
Example #11
Source File: widgets.py    From dissemin with GNU Affero General Public License v3.0 6 votes vote down vote up
def media(self):
        """
        Construct Media as a dynamic property.
        .. Note:: For more information visit
            https://docs.djangoproject.com/en/stable/topics/forms/media/#media-as-a-dynamic-property
        """
        lang = get_language()
        select2_js = (settings.SELECT2_JS,) if settings.SELECT2_JS else ()
        select2_css = (settings.SELECT2_CSS,) if settings.SELECT2_CSS else ()

        i18n_name = SELECT2_TRANSLATIONS.get(lang)
        if i18n_name not in settings.SELECT2_I18N_AVAILABLE_LANGUAGES:
            i18n_name = None

        i18n_file = (
            ('%s/%s.js' % (settings.SELECT2_I18N_PATH, i18n_name),)
            if i18n_name
            else ()
        )

        return forms.Media(
            js=select2_js + i18n_file + (static("js/django_select2.js"), ),
            css={'screen': select2_css}
        ) 
Example #12
Source File: staticfiles.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def versioned_static(path):
    """
    Wrapper for Django's static file finder to append a cache-busting query parameter
    that updates on each Wagtail version
    """
    # An absolute path is returned unchanged (either a full URL, or processed already)
    if path.startswith(('http://', 'https://', '/')):
        return path

    base_url = static(path)

    # if URL already contains a querystring, don't add our own, to avoid interfering
    # with existing mechanisms
    if VERSION_HASH is None or '?' in base_url:
        return base_url
    else:
        return base_url + '?v=' + VERSION_HASH 
Example #13
Source File: vue.py    From TheSpaghettiDetective with GNU Affero General Public License v3.0 6 votes vote down vote up
def bundle(bundle_name, extension=None, config='DEFAULT', attrs=''):
    if settings.WEBPACK_LOADER_ENABLED:
        return render_bundle(
            bundle_name, extension=extension, config=config, attrs=attrs)
    else:
        tags = []
        extensions = (extension, ) if extension is not None else ('js', 'css')

        prefix = settings.WEBPACK_LOADER[config]['BUNDLE_DIR_NAME']
        prefix = prefix.rstrip("/")

        for ext in extensions:
            url = static(f'{prefix}/{ext}/{bundle_name}.{ext}')

            t = TEMPLATES.get(ext)

            if t is not None:
                tags.append(t.format(url, attrs))

        return mark_safe("\n".join(tags)) 
Example #14
Source File: widgets.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def media(self):
        media = super()._get_media()
        media += Media(css={'all': [static("joyous/css/recurrence_admin.css")]},
                       js=[static("joyous/js/recurrence_admin.js")])
        return media

# ------------------------------------------------------------------------------ 
Example #15
Source File: utilities.py    From open-humans with MIT License 5 votes vote down vote up
def make_badge(project, badge_class="oh-badge"):
    """
    Return HTML for a badge.
    """
    if project == "public_data":
        badge_data = {
            "name": "Public Data Sharing",
            "static_url": static("images/public-data-sharing-badge.png"),
            "badge_class": badge_class,
            "href": reverse("public-data:home"),
        }
    else:
        try:
            badge_url = project.badge_image.url
        except ValueError:
            badge_url = static("images/default-badge.png")
        badge_data = {
            "name": project.name,
            "badge_class": badge_class,
            "static_url": badge_url,
            "href": reverse("activity", kwargs={"slug": project.slug}),
        }

    return mark_safe(
        """<a href="{href}" class="{badge_class}">
            <img class="{badge_class}"
              src="{static_url}" alt="{name}" title="{name}">
           </a>""".format(
            **badge_data
        )
    ) 
Example #16
Source File: models.py    From Ghostwriter with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def avatar_url(self):
        try:
            return self.avatar.url
        except ValueError:
            return static('images/default_avatar.png')

    # @receiver(post_save, sender=User)
    # def create_user_profile(sender, instance, created, **kwargs):
    #     """Whenever a new `User` model entry is created create a `UserProfile`
    #     entry.
    #     """
    #     if created:
    #         UserProfile.objects.create(user=instance) 
Example #17
Source File: tethys_gizmos.py    From tethys with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _load_gizmos_rendered(self, context):
        """
        This loads the rendered gizmos into context
        """
        # Add gizmo name to 'gizmos_rendered' context variable (used to load static  libraries
        if 'gizmos_rendered' not in context:
            context.update({'gizmos_rendered': []})

        # add the gizmo in the tag to gizmos_rendered list
        if self.gizmo_name is not None:
            if self.gizmo_name not in context['gizmos_rendered']:
                if self.gizmo_name not in GIZMO_NAME_MAP:
                    raise TemplateSyntaxError('The gizmo name "{0}" is invalid.'.format(self.gizmo_name))
                context['gizmos_rendered'].append(self.gizmo_name) 
Example #18
Source File: widgets.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def media(self):
        # TODO: think about changing this to a static definition
        return Media(css={'all': [static("joyous/css/recurrence_admin.css")]},
                     js=[static("joyous/js/recurrence_admin.js")])

# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------ 
Example #19
Source File: widgets.py    From django-loci with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def media(self):
        js = (static('django-loci/js/floorplan-widget.js'),)
        css = _floorplan_css
        return forms.Media(js=js, css=css) 
Example #20
Source File: widgets.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def media(self):
        return Media(js=[static('joyous/js/vendor/moment-2.22.0.min.js'),
                         static("joyous/js/time12hr_admin.js")])

# ------------------------------------------------------------------------------ 
Example #21
Source File: tests_admin_ca.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def assertCSS(self, response, path):
        css = '<link href="%s" type="text/css" media="all" rel="stylesheet" />' % static(path)
        self.assertInHTML(css, response.content.decode('utf-8'), 1) 
Example #22
Source File: util.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def xstatic(*tags):
    from .vendors import vendors
    node = vendors

    fs = []
    lang = get_language()

    cls_str = str if six.PY3 else basestring
    for tag in tags:
        try:
            for p in tag.split('.'):
                node = node[p]
        except Exception as e:
            if tag.startswith('xadmin'):
                file_type = tag.split('.')[-1]
                if file_type in ('css', 'js'):
                    node = "xadmin/%s/%s" % (file_type, tag)
                else:
                    raise e
            else:
                raise e

        if isinstance(node, cls_str):
            files = node
        else:
            mode = 'dev'
            if not settings.DEBUG:
                mode = getattr(settings, 'STATIC_USE_CDN',
                               False) and 'cdn' or 'production'

            if mode == 'cdn' and mode not in node:
                mode = 'production'
            if mode == 'production' and mode not in node:
                mode = 'dev'
            files = node[mode]

        files = type(files) in (list, tuple) and files or [files, ]
        fs.extend([f % {'lang': lang.replace('_', '-')} for f in files])

    return [f.startswith('http://') and f or static(f) for f in fs] 
Example #23
Source File: rangefilter_compat.py    From Ouroboros with GNU General Public License v3.0 5 votes vote down vote up
def static(path):
    return _static(path) 
Example #24
Source File: admin_list.py    From python2017 with MIT License 5 votes vote down vote up
def _boolean_icon(field_val):
    icon_url = static('admin/img/icon-%s.svg' %
                      {True: 'yes', False: 'no', None: 'unknown'}[field_val])
    return format_html('<img src="{}" alt="{}" />', icon_url, field_val) 
Example #25
Source File: admin_static.py    From python2017 with MIT License 5 votes vote down vote up
def static(path):
    # Backwards compatibility alias for django.templatetags.static.static().
    # Deprecation should start in Django 2.0.
    return _static(path) 
Example #26
Source File: widgets.py    From python2017 with MIT License 5 votes vote down vote up
def absolute_path(self, path):
        """
        Given a relative or absolute path to a static asset, return an absolute
        path. An absolute path will be returned unchanged while a relative path
        will be passed to django.templatetags.static.static().
        """
        if path.startswith(('http://', 'https://', '/')):
            return path
        return static(path) 
Example #27
Source File: util.py    From Mxonline3 with Apache License 2.0 5 votes vote down vote up
def xstatic(*tags):
    from .vendors import vendors
    node = vendors

    fs = []
    lang = get_language()

    cls_str = str
    for tag in tags:
        try:
            for p in tag.split('.'):
                node = node[p]
        except Exception as e:
            if tag.startswith('xadmin'):
                file_type = tag.split('.')[-1]
                if file_type in ('css', 'js'):
                    node = "xadmin/%s/%s" % (file_type, tag)
                else:
                    raise e
            else:
                raise e

        if isinstance(node, cls_str):
            files = node
        else:
            mode = 'dev'
            if not settings.DEBUG:
                mode = getattr(settings, 'STATIC_USE_CDN',
                               False) and 'cdn' or 'production'

            if mode == 'cdn' and mode not in node:
                mode = 'production'
            if mode == 'production' and mode not in node:
                mode = 'dev'
            files = node[mode]

        files = type(files) in (list, tuple) and files or [files, ]
        fs.extend([f % {'lang': lang.replace('_', '-')} for f in files])

    return [f.startswith('http://') and f or static(f) for f in fs] 
Example #28
Source File: __init__.py    From adhocracy4 with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_category_pin_url(name):
    if not name:
        name = 'default'
    return static('category_icons/pins/{}_pin.svg'.format(name)) 
Example #29
Source File: __init__.py    From adhocracy4 with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_category_icon_url(name):
    if not name:
        name = 'default'
    return static('category_icons/icons/{}_icon.svg'.format(name)) 
Example #30
Source File: views.py    From intake with MIT License 5 votes vote down vote up
def post_valid(self, request):
        """Expects a POST request from Twilio, and return a response directing
        Twilio to play the greeting mp3 and post the recorded response to
        the handle voicemail URL
        """
        response = VoiceResponse()
        self.static_greeting_path = static(self.voicemail_static_path)
        self.record_voicemail_url = request.build_absolute_uri(
            reverse('phone-handle_new_message')).replace('http:', 'https:')
        response.play(self.static_greeting_path)
        response.record(action=self.record_voicemail_url, method='POST')
        return HttpResponse(response)