Python django.contrib.staticfiles.templatetags.staticfiles.static() Examples

The following are 30 code examples of django.contrib.staticfiles.templatetags.staticfiles.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.contrib.staticfiles.templatetags.staticfiles , or try the search function .
Example #1
Source File: wagtail_hooks.py    From wagtailcolourpicker with MIT License 6 votes vote down vote up
def insert_editor_js():
    js_files = [
        # We require this file here to make sure it is loaded before the other.
        'wagtailadmin/js/draftail.js',
        'colourpicker/js/colourpicker.js',
    ]
    js_includes = format_html_join(
        '\n',
        '<script src="{0}"></script>',
        ((static(filename), ) for filename in js_files)
    )
    js_includes += format_html(
        "<script>window.chooserUrls.colourChooser = '{0}';</script>",
        reverse('wagtailcolourpicker:chooser')
    )
    return js_includes 
Example #2
Source File: views.py    From sfm-ui with MIT License 6 votes vote down vote up
def render_column(self, row, column):
        # We want to render user as a custom column
        if column == 'link':
            platform_type = self.collection.harvest_type.split('_')[0]
            return mark_safe(u'<a target="_blank" href="{0}"> <img src="{1}" alt="Link to {2} account for {3}" height="35" width="35"/></a>'.format(
                row.social_url(), static('ui/img/{}_logo.png'.format(platform_type)), platform_type, row.token))
        elif column == 'messages':
            msg_seed = ""
            for msg in self.seed_infos.get(row.seed_id, []):
                msg_seed += u'<li><p>{}</p></li>'.format(msg)
            for msg in self.seed_warnings.get(row.seed_id, []):
                msg_seed += u'<li><p>{}</p></li>'.format(msg)
            for msg in self.seed_errors.get(row.seed_id, []):
                msg_seed += u'<li><p>{}</p></li>'.format(msg)
            return mark_safe(u'<ul>{}</ul>'.format(msg_seed)) if msg_seed else ""

        elif column == 'uid':
            return mark_safe(u'<a href="{}">{}</a>'.format(reverse('seed_detail', args=[row.pk]),
                                                           row.uid)) if row.uid else ""
        elif column == 'token':
            return mark_safe(u'<a href="{}">{}</a>'.format(reverse('seed_detail', args=[row.pk]),
                                                           ui_extras.json_list(row.token))) if row.token else "" 
Example #3
Source File: forms.py    From wagtail-personalisation with MIT License 6 votes vote down vote up
def count_matching_users(self, rules, match_any):
        """ Calculates how many users match the given static rules
        """
        count = 0

        static_rules = [rule for rule in rules if rule.static]

        if not static_rules:
            return count

        User = get_user_model()
        users = User.objects.filter(is_active=True, is_staff=False)

        for user in users.iterator():
            if match_any:
                if any(rule.test_user(None, user) for rule in static_rules):
                    count += 1
            elif all(rule.test_user(None, user) for rule in static_rules):
                count += 1

        return count 
Example #4
Source File: forms.py    From wagtail-personalisation with MIT License 6 votes vote down vote up
def clean(self):
        cleaned_data = super(SegmentAdminForm, self).clean()
        Segment = self._meta.model

        rules = [
            form.instance for formset in self.formsets.values()
            for form in formset
            if form not in formset.deleted_forms
        ]
        consistent = rules and Segment.all_static(rules)

        if cleaned_data.get('type') == Segment.TYPE_STATIC and not cleaned_data.get('count') and not consistent:
            self.add_error('count', _('Static segments with non-static compatible rules must include a count.'))

        if self.instance.id and self.instance.is_static:
            if self.has_changed():
                self.add_error_to_fields(self, excluded=['name', 'enabled'])

            for formset in self.formsets.values():
                if formset.has_changed():
                    for form in formset:
                        if form not in formset.deleted_forms:
                            self.add_error_to_fields(form)

        return cleaned_data 
Example #5
Source File: views.py    From wordbank with GNU General Public License v2.0 6 votes vote down vote up
def get(self, request):

        blog_id = "4368769871770527749"
        blogger_service = gdata.blogger.client.BloggerClient()
        feed = blogger_service.GetFeed('http://www.blogger.com/feeds/' + blog_id + '/posts/default')
        entries = [{'title': entry.title.text,
                    'contents': mark_safe(entry.content.text),
                    'time': self.format_datetime(entry.published.text),
                    'author': entry.author[0].name.text
                    #'author_link': entry.author[0].uri.text
                   } for entry in feed.entry]

        events = json.loads(urllib2.urlopen(static('json/events.json')).read())

        resources = json.loads(urllib2.urlopen(static('json/resources.json')).read())

        return render(request, 'blog.html', {'entries': entries, 'events': events, 'resources': resources}) 
Example #6
Source File: items.py    From swarfarm with Apache License 2.0 5 votes vote down vote up
def image_url(self):
        if self.icon_filename:
            return mark_safe('<img src="%s" height="42" width="42"/>' % static('herders/images/buildings/' + self.icon_filename))
        else:
            return 'No Image' 
Example #7
Source File: wagtail_hooks.py    From wagtailcolourpicker with MIT License 5 votes vote down vote up
def editor_css():
    css_files = [
        'colourpicker/css/colourpicker.css',
    ]
    css_includes = format_html_join(
        '\n',
        '<link rel="stylesheet" href="{0}">',
        ((static(filename), ) for filename in css_files)
    )
    return css_includes 
Example #8
Source File: views.py    From 2buntu-blog with Apache License 2.0 5 votes vote down vote up
def opensearch(request):
    """
    Return OpenSearch XML file.
    """
    return render(request, 'xml/opensearch.xml', {
        'image_url': request.build_absolute_uri(static('img/favicon.png')),
        'search_url': request.build_absolute_uri(reverse('articles:search')),
    }, content_type='text/xml') 
Example #9
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 #10
Source File: models.py    From pyconapac-2016 with MIT License 5 votes vote down vote up
def get_image_url(self):
        if self.image:
            return self.image.url

        return static('image/anonymous.png') 
Example #11
Source File: models.py    From pyconkr-2014 with MIT License 5 votes vote down vote up
def get_image_url(self):
        if self.image:
            return self.image.url

        return static('image/anonymous.png') 
Example #12
Source File: util.py    From online with 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 #13
Source File: util.py    From Dailyfresh-B2C 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 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 #14
Source File: wagtail_hooks.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def editor_css():
    link = '<link rel="stylesheet" href="{}">\n'
    path = static('css/apply/wagtail_editor.css')
    return link.format(path) 
Example #15
Source File: wagtail_hooks.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def editor_js():
    return mark_safe(
        '<script src="%s"></script>' % static('people/admin/js/update_person_title.js')
    ) 
Example #16
Source File: monsters.py    From swarfarm with Apache License 2.0 5 votes vote down vote up
def image_url(self):
        if self.image_filename:
            return mark_safe('<img src="%s" height="42" width="42"/>' % static('herders/images/monsters/' + self.image_filename))
        else:
            return 'No Image' 
Example #17
Source File: items.py    From swarfarm with Apache License 2.0 5 votes vote down vote up
def image_tag(self):
        if self.icon:
            path = static('herders/images/items/' + self.icon)
            return mark_safe(f'<img src="{path}" height="42" width="42"/>')
        else:
            return 'No Image' 
Example #18
Source File: wagtail_hooks.py    From developer-portal with Mozilla Public License 2.0 5 votes vote down vote up
def global_admin_css():
    """Slot in custom CMS CSS to render the above button-block element nicely."""
    return format_html(
        '<link rel="stylesheet" href="{}">', static("css/admin_extras.css")
    ) 
Example #19
Source File: items.py    From swarfarm with Apache License 2.0 5 votes vote down vote up
def image_url(self):
        if self.icon_filename:
            return mark_safe('<img src="%s" height="42" width="42"/>' % static('herders/images/icons/' + self.icon_filename))
        else:
            return 'No Image' 
Example #20
Source File: skills.py    From swarfarm with Apache License 2.0 5 votes vote down vote up
def image_url(self):
        if self.icon_filename:
            return mark_safe('<img src="%s" height="42" width="42"/>' % static('herders/images/skills/' + self.icon_filename))
        else:
            return 'No Image' 
Example #21
Source File: skills.py    From swarfarm with Apache License 2.0 5 votes vote down vote up
def image_url(self):
        if self.icon_filename:
            return mark_safe('<img src="%s" height="42" width="42"/>' % static('herders/images/buffs/' + self.icon_filename))
        else:
            return 'No Image' 
Example #22
Source File: test_templatetag_deprecation.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_templatetag_deprecated(self):
        msg = '{% load staticfiles %} is deprecated in favor of {% load static %}.'
        template = "{% load staticfiles %}{% static 'main.js' %}"
        with self.assertWarnsMessage(RemovedInDjango30Warning, msg):
            template = Template(template)
        rendered = template.render(Context())
        self.assertEqual(rendered, 'https://example.com/assets/main.js') 
Example #23
Source File: test_templatetag_deprecation.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_static_deprecated(self):
        msg = (
            'django.contrib.staticfiles.templatetags.static() is deprecated in '
            'favor of django.templatetags.static.static().'
        )
        with self.assertWarnsMessage(RemovedInDjango30Warning, msg):
            url = static('main.js')
        self.assertEqual(url, 'https://example.com/assets/main.js') 
Example #24
Source File: utils.py    From mapstory with GNU General Public License v3.0 5 votes vote down vote up
def render(self, width=None, height=None, css_class=None):
        '''width and height are just hints - ignored for images'''

        ctx = dict(href=self.href, link_content=self.name or self.href,
                   css_class=css_class, width='', height='')
        if self.is_image():
            return '<img class="%(css_class)s" src="%(href)s" title="%(link_content)s"></img>' % ctx

        video = self.get_youtube_video()
        if video:
            ctx['video'] = video
            ctx['width'] = 'width="%s"' % width
            ctx['height'] = 'height="%s"' % height
            return ('<iframe class="youtube-player" type="text/html"'
                    ' %(width)s %(height)s frameborder="0"'
                    ' src="http://www.youtube.com/embed/%(video)s">'
                    '</iframe>') % ctx

        known_links = [
            (self.get_twitter_link, staticfiles.static('img/twitter.png')),
            (self.get_facebook_link, staticfiles.static('img/facebook.png')),
        ]
        for fun, icon in known_links:
            if fun():
                ctx['link_content'] = '<img src="%s" border=0>' % icon
                break

        return '<a target="_" href="%(href)s">%(link_content)s</a>' % ctx 
Example #25
Source File: models.py    From astrobin with GNU Affero General Public License v3.0 5 votes vote down vote up
def build_catalog_and_name(obj, name):
    split = name.split(' ')
    if len(split) > 1:
        cat = split[0]
        del (split[0])
        name = ' '.join(split)

        setattr(obj, 'catalog', cat)
    setattr(obj, 'name', name)


# TODO: unify Image and ImageRevision
# TODO: remember that thumbnails must return 'final' version
# TODO: notifications for gear and subjects after upload
# TODO: this makes animated gifs static :-( 
Example #26
Source File: wagtail_hooks.py    From digihel with MIT License 5 votes vote down vote up
def editor_css():
    return format_html(
        '<link rel="stylesheet" type="text/css" href="{}">',
        static('css/editor.css')
    )

  # <link rel="stylesheet" type="text/x-scss" href="{% static "css/digihel.scss" %}" /> 
Example #27
Source File: wagtail_hooks.py    From wagtailmodelchoosers with MIT License 5 votes vote down vote up
def wagtailmodelchoosers_admin_css():
    return format_html(
        '<link rel="stylesheet" href="{}">',
        static('wagtailmodelchoosers/wagtailmodelchoosers.css')
    ) 
Example #28
Source File: wagtail_hooks.py    From wagtailmodelchoosers with MIT License 5 votes vote down vote up
def wagtailmodelchoosers_admin_js():
    js_files = (
        'wagtailmodelchoosers/wagtailmodelchoosers.js',
        'wagtailmodelchoosers/polyfills.js',
    )
    js_includes = format_html_join(
        '\n',
        '<script src="{}"></script>',
        ((static(filename),) for filename in js_files)
    )
    return js_includes 
Example #29
Source File: models.py    From rocket-league-replays with GNU General Public License v3.0 5 votes vote down vote up
def get_rating_data(self):
        from ..users.models import LeagueRating
        from ..users.templatetags.ratings import tier_name

        if self.replay.playlist not in settings.RANKED_PLAYLISTS:
            return

        try:
            rating = LeagueRating.objects.get_or_request(
                platform=self.platform,
                online_id=self.online_id if PLATFORMS_MAPPINGS[self.platform] == PLATFORM_STEAM else self.player_name,
                playlist=self.replay.playlist,
            )

            if not rating:
                return {
                    'image': static('img/tiers/icons/0.png'),
                    'tier_name': tier_name(0)
                }

            return {
                'image': static('img/tiers/icons/{}.png'.format(rating.tier)),
                'tier_name': tier_name(rating.tier)
            }
        except LeagueRating.DoesNotExist:
            pass

        return {
            'image': static('img/tiers/icons/0.png'),
            'tier_name': 'Unranked'
        } 
Example #30
Source File: posters.py    From mangaki with GNU Affero General Public License v3.0 5 votes vote down vote up
def poster_url(context, work, bypass_nsfw_settings=None):
    if work is None:
        return static('img/chiro.gif')
    if bypass_nsfw_settings:
        return work.poster_url
    return work.safe_poster(context.request.user)