python类format_html()的实例源码

wagtail_hooks.py 文件源码 项目:dprr-django 作者: kingsdigitallab 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def editor_js():
    js_files = [
        'javascripts/hallo.js',
    ]

    js_includes = format_html_join('\n', '<script src="{0}{1}"></script>',
                                   ((settings.STATIC_URL, filename)
                                    for filename in js_files)
                                   )

    return js_includes + format_html("""
        <script>
            registerHalloPlugin('blockQuoteButton');
            registerHalloPlugin('editHtmlButton');
        </script>
        """)
forms.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 52 收藏 0 点赞 0 评论 0
def render(self, name, value, attrs):
        encoded = value
        final_attrs = self.build_attrs(attrs)

        if not encoded or encoded.startswith(UNUSABLE_PASSWORD_PREFIX):
            summary = mark_safe("<strong>%s</strong>" % ugettext("No password set."))
        else:
            try:
                hasher = identify_hasher(encoded)
            except ValueError:
                summary = mark_safe("<strong>%s</strong>" % ugettext(
                    "Invalid password format or unknown hashing algorithm."))
            else:
                summary = format_html_join('',
                                           "<strong>{}</strong>: {} ",
                                           ((ugettext(key), value)
                                            for key, value in hasher.safe_summary(encoded).items())
                                           )

        return format_html("<div{}>{}</div>", flatatt(final_attrs), summary)
defaulttags.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def render(self, context):
        csrf_token = context.get('csrf_token')
        if csrf_token:
            if csrf_token == 'NOTPROVIDED':
                return format_html("")
            else:
                return format_html("<input type='hidden' name='csrfmiddlewaretoken' value='{}' />", csrf_token)
        else:
            # It's very probable that the token is missing because of
            # misconfiguration, so we raise a warning
            if settings.DEBUG:
                warnings.warn(
                    "A {% csrf_token %} was used in a template, but the context "
                    "did not provide the value.  This is usually caused by not "
                    "using RequestContext."
                )
            return ''
forms.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def render(self, name, value, attrs):
        encoded = value
        final_attrs = self.build_attrs(attrs)

        if not encoded or encoded.startswith(UNUSABLE_PASSWORD_PREFIX):
            summary = mark_safe("<strong>%s</strong>" % ugettext("No password set."))
        else:
            try:
                hasher = identify_hasher(encoded)
            except ValueError:
                summary = mark_safe("<strong>%s</strong>" % ugettext(
                    "Invalid password format or unknown hashing algorithm."
                ))
            else:
                summary = format_html_join(
                    '', '<strong>{}</strong>: {} ',
                    ((ugettext(key), value) for key, value in hasher.safe_summary(encoded).items())
                )

        return format_html("<div{}>{}</div>", flatatt(final_attrs), summary)
widgets.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def label_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):
            return ''

        label = '&nbsp;<strong>{}</strong>'
        text = Truncator(obj).words(14, truncate='...')
        try:
            change_url = reverse(
                '%s:%s_%s_change' % (
                    self.admin_site.name,
                    obj._meta.app_label,
                    obj._meta.object_name.lower(),
                ),
                args=(obj.pk,)
            )
        except NoReverseMatch:
            pass  # Admin not registered for target model.
        else:
            text = format_html('<a href="{}">{}</a>', change_url, text)

        return format_html(label, text)
utils.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display)
edit_handlers.py 文件源码 项目:wagtailmodelchooser 作者: Naeka 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def get_editor_js_for_registration(cls):
        js_files = cls.get_editor_js_files()

        js_includes = format_html_join(
            '\n', '<script src="{0}{1}"></script>',
            ((settings.STATIC_URL, filename) for filename in js_files)
        )
        return js_includes + format_html(
            """
            <script>
                window.chooserUrls.{0}Chooser = '{1}';
            </script>
            """,
            cls.model._meta.object_name,
            urlresolvers.reverse('{}_chooser'.format(cls.model._meta.model_name))
        )
relfield.py 文件源码 项目:blog_django 作者: chnpmy 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def build_attrs(self, attrs={}, **kwargs):
        to_opts = self.rel.to._meta
        if "class" not in attrs:
            attrs['class'] = 'select-search'
        else:
            attrs['class'] = attrs['class'] + ' select-search'
        attrs['data-search-url'] = self.admin_view.get_admin_url(
            '%s_%s_changelist' % (to_opts.app_label, to_opts.model_name))
        attrs['data-placeholder'] = _('Search %s') % to_opts.verbose_name
        attrs['data-choices'] = '?'
        if self.rel.limit_choices_to:
            for i in list(self.rel.limit_choices_to):
                attrs['data-choices'] += "&_p_%s=%s" % (i, self.rel.limit_choices_to[i])
            attrs['data-choices'] = format_html(attrs['data-choices'])

        return super(ForeignKeySearchWidget, self).build_attrs(attrs, **kwargs)
utils.py 文件源码 项目:Scrum 作者: prakharchoudhary 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display)
relfield.py 文件源码 项目:dream_blog 作者: fanlion 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def build_attrs(self, attrs={}, extra_attrs=None, **kwargs):
        to_opts = self.rel.to._meta
        if "class" not in attrs:
            attrs['class'] = 'select-search'
        else:
            attrs['class'] = attrs['class'] + ' select-search'
        attrs['data-search-url'] = self.admin_view.get_admin_url(
            '%s_%s_changelist' % (to_opts.app_label, to_opts.model_name))
        attrs['data-placeholder'] = _('Search %s') % to_opts.verbose_name
        attrs['data-choices'] = '?'
        if self.rel.limit_choices_to:
            for i in list(self.rel.limit_choices_to):
                attrs['data-choices'] += "&_p_%s=%s" % (i, self.rel.limit_choices_to[i])
            attrs['data-choices'] = format_html(attrs['data-choices'])
        if DJANGO_11:
            attrs.update(kwargs)
            return super(ForeignKeySearchWidget, self).build_attrs(attrs, extra_attrs=extra_attrs)
        else:
            if extra_attrs:
                attrs.update(extra_attrs)
            return super(ForeignKeySearchWidget, self).build_attrs(attrs, **kwargs)
relfield.py 文件源码 项目:MxOnline 作者: myTeemo 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def build_attrs(self, attrs={}, **kwargs):
        to_opts = self.rel.to._meta
        if "class" not in attrs:
            attrs['class'] = 'select-search'
        else:
            attrs['class'] = attrs['class'] + ' select-search'
        attrs['data-search-url'] = self.admin_view.get_admin_url(
            '%s_%s_changelist' % (to_opts.app_label, to_opts.model_name))
        attrs['data-placeholder'] = _('Search %s') % to_opts.verbose_name
        attrs['data-choices'] = '?'
        if self.rel.limit_choices_to:
            for i in list(self.rel.limit_choices_to):
                attrs['data-choices'] += "&_p_%s=%s" % (i, self.rel.limit_choices_to[i])
            attrs['data-choices'] = format_html(attrs['data-choices'])

        return super(ForeignKeySearchWidget, self).build_attrs(attrs, **kwargs)
views.py 文件源码 项目:SPBU-DBMS-Project 作者: Betekhtin 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def login(request):
    username = auth.get_user(request).username
    if (username):
        return redirect('/')
    else:
        args = {}
        args.update(csrf(request))
        if request.POST:
            username = request.POST.get('username','')
            password = request.POST.get('password','')
            user = auth.authenticate(username=username, password=password)
            if user is not None:
                if not request.POST.get('remember-me', ''):
                    request.session.set_expiry(0)
                auth.login(request, user)
                return redirect('/')
            else:
                args['login_error'] = format_html("<div class=\"main-error alert alert-error\">???????????? ??? ???????????? ??? ??????</div>")
                return render_to_response('login.html', args)
        else:
            return render_to_response('login.html', args)
views.py 文件源码 项目:SPBU-DBMS-Project 作者: Betekhtin 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def register(request):
    username = auth.get_user(request).username
    if not (username):
        args={}
        args.update(csrf(request))
        args['form']=UserCreationForm()
        if request.POST:
            newuser_form=UserCreationForm(request.POST)
            if newuser_form.is_valid():
                newuser_form.save()
                newuser = auth.authenticate(username=newuser_form.cleaned_data['username'],password=newuser_form.cleaned_data['password2'])
                auth.login(request, newuser)
                return redirect('/')
            else:
                args['errors'] = format_html('<div class="main-error alert alert-error">?????? ??? ???????????</div>')
                args['form'] = newuser_form
        return render_to_response('register.html',args)
    else:
        return redirect('/')
admin.py 文件源码 项目:feincms3 作者: matthiask 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def indented_title(self, instance):
        """
        Use Unicode box-drawing characters to visualize the tree hierarchy.
        """
        box_drawing = []
        for i in range(instance.depth - 2):
            box_drawing.append('<i class="l"></i>')
        if instance.depth > 1:
            box_drawing.append('<i class="a"></i>')

        return format_html(
            '<div class="box">'
            '<div class="box-drawing">{}</div>'
            '<div class="box-text" style="text-indent:{}px">{}</div>'
            '</div>',
            mark_safe(''.join(box_drawing)),
            (instance.depth - 1) * 30,
            instance,
        )
relfield.py 文件源码 项目:djangoblog 作者: liuhuipy 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def build_attrs(self, attrs={}, **kwargs):
        to_opts = self.rel.to._meta
        if "class" not in attrs:
            attrs['class'] = 'select-search'
        else:
            attrs['class'] = attrs['class'] + ' select-search'
        attrs['data-search-url'] = self.admin_view.get_admin_url(
            '%s_%s_changelist' % (to_opts.app_label, to_opts.model_name))
        attrs['data-placeholder'] = _('Search %s') % to_opts.verbose_name
        attrs['data-choices'] = '?'
        if self.rel.limit_choices_to:
            for i in list(self.rel.limit_choices_to):
                attrs['data-choices'] += "&_p_%s=%s" % (i, self.rel.limit_choices_to[i])
            attrs['data-choices'] = format_html(attrs['data-choices'])

        return super(ForeignKeySearchWidget, self).build_attrs(attrs, **kwargs)
pubdocs.py 文件源码 项目:site 作者: alphageek-xyz 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def async_css(href):
    """
    Outputs a link and noscript tag, which will asynchronously load an external stylesheet.

    Sample usage::

        <head>
        ...
            {% async_css '/static/foo.css' %}
        ...
        </head>

    Results in::

        <head>
        ...
            <link rel="preload" href="/static/foo.css" onload="this.rel='stylesheet'">
            <noscript><link rel="stylesheet" href="/static/foo.css"></noscript>
        ...
        </head>
    """
    return format_html(''.join([
        '<link rel="preload" href="{0}" as="style" onload="this.rel=\'stylesheet\'">',
        '<noscript><link rel="stylesheet" href="{0}"></noscript>'
    ]), href)
landing_utils.py 文件源码 项目:site 作者: alphageek-xyz 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def async_css(href):
    """
    Outputs a link and noscript tag, which will asynchronously load an external stylesheet.

    Sample usage::

        <head>
        ...
            {% async_css '/static/foo.css' %}
        ...
        </head>

    Results in::

        <head>
        ...
            <link rel="preload" href="/static/foo.css" onload="this.rel='stylesheet'">
            <noscript><link rel="stylesheet" href="/static/foo.css"></noscript>
        ...
        </head>
    """
    return format_html(''.join([
        '<link rel="preload" href="{0}" as="style" onload="this.rel=\'stylesheet\'">',
        '<noscript><link rel="stylesheet" href="{0}"></noscript>'
    ]), href)
relfield.py 文件源码 项目:sdining 作者: Lurance 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def build_attrs(self, attrs={}, **kwargs):
        to_opts = self.rel.to._meta
        if "class" not in attrs:
            attrs['class'] = 'select-search'
        else:
            attrs['class'] = attrs['class'] + ' select-search'
        attrs['data-search-url'] = self.admin_view.get_admin_url(
            '%s_%s_changelist' % (to_opts.app_label, to_opts.model_name))
        attrs['data-placeholder'] = _('Search %s') % to_opts.verbose_name
        attrs['data-choices'] = '?'
        if self.rel.limit_choices_to:
            for i in list(self.rel.limit_choices_to):
                attrs['data-choices'] += "&_p_%s=%s" % (i, self.rel.limit_choices_to[i])
            attrs['data-choices'] = format_html(attrs['data-choices'])

        return super(ForeignKeySearchWidget, self).build_attrs(attrs, **kwargs)
spectator_core.py 文件源码 项目:django-spectator 作者: philgyford 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def domain_urlize(value):
    """
    Returns an HTML link to the supplied URL, but only using the domain as the
    text.

    e.g. if `my_url` is 'http://www.example.org/foo/' then:

        {{ my_url|domain_urlize }}

    returns:
        <a href="http://www.example.org/foo/" rel="nofollow">www.example.org</a>
    """
    parsed_uri = urlparse(value)
    domain = '{uri.netloc}'.format(uri=parsed_uri)
    return format_html('<a href="{}" rel="nofollow">{}</a>',
            value,
            domain
        )
common.py 文件源码 项目:django-driver27 作者: SRJ9 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def render_option(self, selected_choices, option_value, option_label):
        if option_value is None:
            option_value = ''
        option_value = force_text(option_value)
        if option_value in selected_choices:
            selected_html = mark_safe(' selected="selected"')
            if not self.allow_multiple_selected:
                # Only allow for a single selection.
                selected_choices.remove(option_value)
        else:
            selected_html = ''
        data_circuit_attr = ''
        if option_value:
            from driver27.models import GrandPrix
            grand_prix = GrandPrix.objects.filter(pk=option_value)
            if grand_prix.count() and grand_prix.first().default_circuit:
                data_circuit_attr = getattr(grand_prix.first().default_circuit, 'pk', '')

        return format_html('<option value="{}"{} data-circuit="{}">{}</option>',
                           option_value, selected_html,
                           data_circuit_attr, force_text(option_label))
widgets.py 文件源码 项目:tumanov_castleoaks 作者: Roamdev 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def render(self, name, value, attrs=None):
        if value is None:
            return format_html(
                '<p class="text-error">{text}</p>',
                text=_('Populate form fields above'),
            )

        final_attrs = self.build_attrs(attrs)
        href = smart_urlquote(value)
        text = self.text or href
        return format_html(
            '<p><a href="{href}" {attrs}>{text}</a></p>',
            href=href,
            attrs=flatatt(final_attrs),
            text=force_str(text),
        )
renderers.py 文件源码 项目:pretalx 作者: pretalx 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def render_label(content, label_for=None, label_class=None, label_title='', optional=False):
    """
    Render a label with content
    """
    attrs = {}
    if label_for:
        attrs['for'] = label_for
    if label_class:
        attrs['class'] = label_class
    if label_title:
        attrs['title'] = label_title
    builder = '<{tag}{attrs}>{content}{opt}</{tag}>'
    return format_html(
        builder,
        tag='label',
        attrs=mark_safe(flatatt(attrs)) if attrs else '',
        opt=mark_safe('<br><span class="optional">{}</span>'.format(pgettext('form', 'Optional'))) if optional else '',
        content=text_value(content),
    )
forms.py 文件源码 项目:Gypsy 作者: benticarlos 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def render(self, name, value, attrs):
        encoded = value
        final_attrs = self.build_attrs(attrs)

        if not encoded or encoded.startswith(UNUSABLE_PASSWORD_PREFIX):
            summary = mark_safe("<strong>%s</strong>" % ugettext("No password set."))
        else:
            try:
                hasher = identify_hasher(encoded)
            except ValueError:
                summary = mark_safe("<strong>%s</strong>" % ugettext(
                    "Invalid password format or unknown hashing algorithm."
                ))
            else:
                summary = format_html_join(
                    '', '<strong>{}</strong>: {} ',
                    ((ugettext(key), value) for key, value in hasher.safe_summary(encoded).items())
                )

        return format_html("<div{}>{}</div>", flatatt(final_attrs), summary)
widgets.py 文件源码 项目:Gypsy 作者: benticarlos 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def label_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):
            return ''

        label = '&nbsp;<strong>{}</strong>'
        text = Truncator(obj).words(14, truncate='...')
        try:
            change_url = reverse(
                '%s:%s_%s_change' % (
                    self.admin_site.name,
                    obj._meta.app_label,
                    obj._meta.object_name.lower(),
                ),
                args=(obj.pk,)
            )
        except NoReverseMatch:
            pass  # Admin not registered for target model.
        else:
            text = format_html('<a href="{}">{}</a>', change_url, text)

        return format_html(label, text)
utils.py 文件源码 项目:Gypsy 作者: benticarlos 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display)
wagtail_hooks.py 文件源码 项目:oscar-wagtail-demo 作者: pgovers 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def editor_css():
    return format_html(
        '<link rel="stylesheet" href="%(static_url)sdemo/css/'
        'admin-streamfield-styles.css">' % {'static_url': settings.STATIC_URL}
    )
admin.py 文件源码 项目:jakniedojade 作者: hackerspace-silesia 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def image_tag(url):
    return format_html(
        "<img src='{root}{url}' />".format(
            root=settings.MEDIA_URL or '',
            url=url,
        )
    )
admin.py 文件源码 项目:django-letsencrypt 作者: urda 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def format_acme_url(self, acme_object):
        """Format the ACME url from the ACME challenge object"""
        object_url = acme_object.get_acme_url()

        if object_url:
            return format_html(
                "<a href='{}'>ACME Challenge Link</a>",
                object_url,
            )

        return '-'
admin.py 文件源码 项目:django-letsencrypt 作者: urda 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def format_acme_url(self, acme_object):
        """Format the ACME url from the ACME challenge object"""
        object_url = acme_object.get_acme_url()

        if object_url:
            return format_html(
                "<a href='{}'>ACME Challenge Link</a>",
                object_url,
            )

        return '-'
utils.py 文件源码 项目:django-bootstrap4 作者: zostera 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def render_tag(tag, attrs=None, content=None, close=True):
    """
    Render a HTML tag
    """
    builder = '<{tag}{attrs}>{content}'
    if content or close:
        builder += '</{tag}>'
    return format_html(
        builder,
        tag=tag,
        attrs=mark_safe(flatatt(attrs)) if attrs else '',
        content=text_value(content),
    )


问题


面经


文章

微信
公众号

扫码关注公众号