Python django.templatetags.static.static() Examples

The following are 30 code examples for showing how to use django.templatetags.static.static(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.templatetags.static , or try the search function .

Example 1
Project: FIR   Author: certsocietegenerale   File: markdown.py    License: 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
Project: django-healthchecks   Author: mvantellingen   File: admin.py    License: MIT License 6 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
Project: django-sitemessage   Author: idlesign   File: views.py    License: 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 4
Project: wagtail-tag-manager   Author: jberghoef   File: middleware.py    License: 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 5
Project: dissemin   Author: dissemin   File: widgets.py    License: 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 6
Project: wagtail   Author: wagtail   File: staticfiles.py    License: 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 7
Project: ldap-oauth2   Author: DheerendraRathor   File: views.py    License: 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 8
Project: sal   Author: salopensource   File: utils.py    License: 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 9
Project: freedomvote   Author: freedomvote   File: widgets.py    License: 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 10
Project: Inboxen   Author: Inboxen   File: manifest.py    License: 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 11
Project: djongo   Author: nesdis   File: test_forms.py    License: 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 12
Project: TheSpaghettiDetective   Author: TheSpaghettiDetective   File: vue.py    License: 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 13
Project: digihel   Author: City-of-Helsinki   File: tinymce.py    License: 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 14
Project: StormOnline   Author: stormsha   File: util.py    License: 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 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 15
Project: GTDWeb   Author: lanbing510   File: admin_static.py    License: GNU General Public License v2.0 5 votes vote down vote up
def static(path):
    global _static
    if _static is None:
        if apps.is_installed('django.contrib.staticfiles'):
            from django.contrib.staticfiles.templatetags.staticfiles import static as _static
        else:
            from django.templatetags.static import static as _static
    return _static(path) 
Example 16
Project: wagtail-tag-manager   Author: jberghoef   File: wtm_tags.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render(self, context):
        request = context.get("request", None)
        if request:
            tag_config = TagTypeSettings().get(self.tag_type)

            if TagStrategy(request=request).should_include(self.tag_type, tag_config):
                ctx = Tag.create_context(request=request, context=context)

                if self.src:
                    if self.src.endswith(".html"):
                        return render_to_string(self.src, ctx)

                    elif self.src.endswith(".css"):
                        tag = BeautifulSoup("", "html.parser").new_tag("link")
                        tag["rel"] = "stylesheet"
                        tag["type"] = "text/css"
                        tag["href"] = static(self.src)

                    elif self.src.endswith(".js"):
                        tag = BeautifulSoup("", "html.parser").new_tag("script")
                        tag["type"] = "text/javascript"
                        tag["src"] = static(self.src)

                    return mark_safe(tag.decode())

                output = self.nodelist.render(ctx)
                return output

        return "" 
Example 17
Project: jinja2-django-tags   Author: MoritzS   File: extensions.py    License: MIT License 5 votes vote down vote up
def _static(self, path):
        return django_static(path) 
Example 18
Project: bioforum   Author: reBiocoder   File: widgets.py    License: 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 19
Project: bioforum   Author: reBiocoder   File: widgets.py    License: MIT License 5 votes vote down vote up
def merge(list_1, list_2):
        """
        Merge two lists while trying to keep the relative order of the elements.
        Warn if the lists have the same two elements in a different relative
        order.

        For static assets it can be important to have them included in the DOM
        in a certain order. In JavaScript you may not be able to reference a
        global or in CSS you might want to override a style.
        """
        # Start with a copy of list_1.
        combined_list = list(list_1)
        last_insert_index = len(list_1)
        # Walk list_2 in reverse, inserting each element into combined_list if
        # it doesn't already exist.
        for path in reversed(list_2):
            try:
                # Does path already exist in the list?
                index = combined_list.index(path)
            except ValueError:
                # Add path to combined_list since it doesn't exist.
                combined_list.insert(last_insert_index, path)
            else:
                if index > last_insert_index:
                    warnings.warn(
                        'Detected duplicate Media files in an opposite order:\n'
                        '%s\n%s' % (combined_list[last_insert_index], combined_list[index]),
                        MediaOrderConflictWarning,
                    )
                # path already exists in the list. Update last_insert_index so
                # that the following elements are inserted in front of this one.
                last_insert_index = index
        return combined_list 
Example 20
Project: bioforum   Author: reBiocoder   File: admin_static.py    License: 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 21
Project: bioforum   Author: reBiocoder   File: admin_list.py    License: 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 22
Project: django-admin-rangefilter   Author: silentsokolov   File: rangefilter_compat.py    License: MIT License 5 votes vote down vote up
def static(path):
    return _static(path) 
Example 23
Project: django-radio   Author: iago1460   File: 0007_change_default_image.py    License: GNU General Public License v3.0 5 votes vote down vote up
def change_programmes(apps, schema_editor):
    # We can't import the Programme model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Programme = apps.get_model("programmes", "Programme")
    for programme in Programme.objects.all():
        print(programme.photo.name)
        if programme.photo.name == static('radio/images/default-programme-photo.jpg'):
            programme.photo = 'defaults/default-programme-photo.jpg'
            programme.save() 
Example 24
Project: django-radio   Author: iago1460   File: 0007_change_default_image.py    License: GNU General Public License v3.0 5 votes vote down vote up
def change_users(apps, schema_editor):
    UserProfile = apps.get_model("users", "UserProfile")
    for profile in UserProfile.objects.all():
        if profile.avatar.name == static('radio/images/default-userprofile-avatar.jpg'):
            profile.avatar = 'defaults/default-userprofile-avatar.jpg'
            profile.save() 
Example 25
Project: django-radio   Author: iago1460   File: 0004_change_photo_url.py    License: GNU General Public License v3.0 5 votes vote down vote up
def change_photo_url(apps, schema_editor):
    # We can't import the Programme model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Programme = apps.get_model("programmes", "Programme")
    for programme in Programme.objects.all():
        if programme.photo.name == '/static/radio/images/default-programme-photo.jpg':
            programme.photo = static('radio/images/default-programme-photo.jpg')
            programme.save() 
Example 26
Project: weibo-analysis-system   Author: Superbsco   File: util.py    License: MIT License 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 27
Project: online-judge   Author: DMOJ   File: lazy_load.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def lazy_load(tree):
    blank = static('blank.gif')
    for img in tree.xpath('.//img'):
        src = img.get('src', '')
        if src.startswith('data') or '-math' in img.get('class', ''):
            continue
        noscript = html.Element('noscript')
        copy = deepcopy(img)
        copy.tail = ''
        noscript.append(copy)
        img.addprevious(noscript)
        img.set('data-src', src)
        img.set('src', blank)
        img.set('class', img.get('class') + ' unveil' if img.get('class') else 'unveil') 
Example 28
Project: myblog   Author: myminwang   File: util.py    License: GNU Affero General Public License v3.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 29
Project: CTF_AWD_Platform   Author: xuchaoa   File: util.py    License: MIT License 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 30
Project: django_OA   Author: abaoMAO   File: util.py    License: GNU General Public License v3.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]