Python django.utils.safestring 模块,mark_safe() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.safestring.mark_safe()

项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def json_context(context, raise_error=False):
    """Generate a JS <script> tag from context

    Serializes ``context["json_context"]`` into JSON and generates a JS
    script to attach it to ``window.context``

    If ``raise_error`` is False, values in context that are not
    JSON serialisable will be converted to string. Otherwise, it
    raises TypeError

    :param context: Current view context
    :param raise_error: Control whether to raise an error on non-JSON serialisable values
    :return: ``<script>window.context = {<context["json_context"]>}</script>``
    """
    if not context.get("json_context"):
        return ""

    json_default = None if raise_error else lambda obj: str(obj)

    json_dump = json.dumps(context["json_context"], default=json_default)
    return mark_safe("<script>window.context = %s;</script>" % json_dump)
项目:django-admin-reports    作者:simplyopen-it    | 项目源码 | 文件源码
def _items(self, record):
        for field_name, _ in self.get_fields():
            # Does the field_name refer to an aggregation column or is
            # it an attribute of this instance?
            try:
                attr_field = getattr(self, field_name)
            except AttributeError:
                # The field is a record element
                ret = record.get(field_name)
                formatting_func = self.get_formatting().get(field_name)
                if formatting_func is not None:
                    try:
                        ret = formatting_func(ret)
                    except (TypeError, ValueError):
                        pass
            else:
                # The view class has an attribute with this field_name
                if callable(attr_field):
                    ret = attr_field(record)
                    if getattr(attr_field, 'allow_tags', False):
                        ret = mark_safe(ret)
            yield ret
项目:django-powerpages    作者:Open-E-WEB    | 项目源码 | 文件源码
def website_link(page):
    """Link to the Page on website"""
    if not page:
        return None
    url = page.url
    url_parts = url.split('/')
    if len(url_parts) <= 1:
        styled_url = page.url
    else:
        for i in (-1, -2):
            if url_parts[i]:
                url_parts[i] = \
                    '<span style="font-weight: bold">{0}</span>'.format(
                        url_parts[i]
                    )
                break
        styled_url = '/'.join(url_parts)
    return mark_safe(
        '<a href="{url}" style="font-weight: normal;">{text}</a>'.format(
            url=url, text='{url} &raquo;'.format(url=styled_url)
        )
    )
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def format_user(user, format='full'):
    if format == 'full':
        full_name = conditional_escape(user.get_full_name())
        username = conditional_escape(user.username)
        result = u'{0} <span class="user-username">({1})</span>'.format(
                full_name, username)
    elif format == 'name':
        result = conditional_escape(user.get_full_name())
    elif format == 'username':
        result = conditional_escape(user.username)
    elif format == 'email':
        return u'{0} ({1})'.format(user.get_full_name(), user.username)
    else:
        raise ValueError("Invalid format for format_user")

    return mark_safe(result)
项目:wagtail-systemtext    作者:Frojd    | 项目源码 | 文件源码
def render(self, context):
        self.filter_expression.var.translate = not self.noop
        if self.message_context:
            self.filter_expression.var.message_context = (
                self.message_context.resolve(context))
        output = self.filter_expression.resolve(context)

        value = render_value_in_context(output, context)

        # Restore percent signs. Percent signs in template text are doubled
        # so they are not interpreted as string format flags.
        is_safe = isinstance(value, SafeData)
        value = value.replace('%%', '%')
        value = systemtext(value, group=self.group, default=self.default)
        value = mark_safe(value) if is_safe else value
        if self.asvar:
            context[self.asvar] = value
            return ''
        else:
            return value
项目:django-bootstrap4    作者:zostera    | 项目源码 | 文件源码
def render_alert(content, alert_type=None, dismissable=True):
    """
    Render a Bootstrap alert
    """
    button = ''
    if not alert_type:
        alert_type = 'info'
    css_classes = ['alert', 'alert-' + text_value(alert_type)]
    if dismissable:
        css_classes.append('alert-dismissable')
        button = '<button type="button" class="close" ' + \
                 'data-dismiss="alert" aria-hidden="true">&times;</button>'
    button_placeholder = '__BUTTON__'
    return mark_safe(render_tag(
        'div',
        attrs={'class': ' '.join(css_classes)},
        content=button_placeholder + text_value(content),
    ).replace(button_placeholder, button))
项目:django-bootstrap4    作者:zostera    | 项目源码 | 文件源码
def render_field_and_label(
        field, label, field_class='', label_for=None, label_class='',
        layout='', **kwargs):
    """
    Render a field with its label
    """
    if layout == 'horizontal':
        if not label_class:
            label_class = get_bootstrap_setting('horizontal_label_class')
        if not field_class:
            field_class = get_bootstrap_setting('horizontal_field_class')
        if not label:
            label = mark_safe('&#160;')
        label_class = add_css_class(label_class, 'control-label')
    html = field
    if field_class:
        html = '<div class="{klass}">{html}</div>'.format(
            klass=field_class, html=html)
    if label:
        html = render_label(
            label, label_for=label_for, label_class=label_class) + html
    return html
项目:django-bootstrap4    作者:zostera    | 项目源码 | 文件源码
def url_replace_param(url, name, value):
    """
    Replace a GET parameter in an URL
    """
    url_components = urlparse(force_str(url))

    params = parse_qs(url_components.query)

    if value is None:
        del params[name]
    else:
        params[name] = value

    return mark_safe(urlunparse([
        url_components.scheme,
        url_components.netloc,
        url_components.path,
        url_components.params,
        urlencode(params, doseq=True),
        url_components.fragment,
    ]))
项目:ProductAnalysis    作者:Jasonhy    | 项目源码 | 文件源码
def get_search_result_list(product_list):
    """
    ????????
    :param product_list:
    :return:
    """
    res = ""
    if product_list:
        for index in range(len(product_list)):
            if index == 0:
                res = ' <li class="active"><a id="set_click" href="javascript:;" onclick="get_plot(%s,this)">%s</a></li>' % (product_list[index].object.p_id,product_list[index].object.p_title)
            else:
                res += ' <li><a href="javascript:;" onclick="get_plot(%s,this)">%s</a></li>' % (product_list[index].object.p_id,product_list[index].object.p_title)
    else:
        res = '<li><a href="javascript:void(0);">????????</a></>'

    return mark_safe(res)
项目:ecs_sclm    作者:meaningful    | 项目源码 | 文件源码
def _format_callback(self, obj, user, admin_site, perms_needed):
        has_admin = obj.__class__ in admin_site._registry
        opts = obj._meta
        if has_admin:
            admin_url = reverse('%s:%s_%s_change'
                                % (admin_site.name,
                                   opts.app_label,
                                   opts.object_name.lower()),
                                None, (quote(obj._get_pk_val()),))
            p = get_delete_permission(opts)
            if not user.has_perm(p):
                perms_needed.add(opts.verbose_name)
            # Display a link to the admin page.
            return mark_safe('%s: <a href="%s">%s</a>' %
                             (escape(capfirst(opts.verbose_name)),
                              admin_url,
                              escape(obj)))
        else:
            # Don't display link to edit, because it either has no
            # admin or is edited inline.
            return '%s: %s' % (capfirst(opts.verbose_name), force_text(obj))
项目:ecs_sclm    作者:meaningful    | 项目源码 | 文件源码
def paginator_number(cl, i):
    """
    Generates an individual page index link in a paginated list.
    """
    if i == DOT:
        return mark_safe(
                '<li class="disabled"><a href="#" onclick="return false;">..'
                '.</a></li>')
    elif i == cl.page_num:
        return mark_safe(
            '<li class="active"><a href="">%d</a></li> ' % (i + 1))
    else:
        return mark_safe('<li><a href="%s"%s>%d</a></li> ' % (
            escape(cl.get_query_string({PAGE_VAR: i})),
            (i == cl.paginator.num_pages - 1 and ' class="end"' or ''),
            i + 1))
项目:ecs_sclm    作者:meaningful    | 项目源码 | 文件源码
def headers_handler(result_headers, cl):
    """
    Adds field name to css class, so we can style specific columns
    """
    # field = cl.list_display.get()
    attrib_key = 'class_attrib'
    for i, header in enumerate(result_headers):
        field_name = cl.list_display[i]
        if field_name == 'action_checkbox':
            continue
        if not attrib_key in header:
            header[attrib_key] = mark_safe(' class=""')

        pattern = 'class="'
        if pattern in header[attrib_key]:
            replacement = '%s%s-column ' % (pattern, field_name)
            header[attrib_key] = mark_safe(
                header[attrib_key].replace(pattern, replacement))

    return result_headers
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def render(self, name, value, attrs=None):
        substitutions = {
            'initial_text': self.initial_text,
            'input_text': self.input_text,
            'clear_template': '',
            'clear_checkbox_label': self.clear_checkbox_label,
        }
        template = '%(input)s'
        substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)

        if self.is_initial(value):
            template = self.template_with_initial
            substitutions.update(self.get_template_substitution_values(value))
            if not self.is_required:
                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.template_with_clear % substitutions

        return mark_safe(template % substitutions)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def render(self, name, value, attrs=None):
        if self.is_localized:
            for widget in self.widgets:
                widget.is_localized = self.is_localized
        # value is a list of values, each corresponding to a widget
        # in self.widgets.
        if not isinstance(value, list):
            value = self.decompress(value)
        output = []
        final_attrs = self.build_attrs(attrs)
        id_ = final_attrs.get('id')
        for i, widget in enumerate(self.widgets):
            try:
                widget_value = value[i]
            except IndexError:
                widget_value = None
            if id_:
                final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
            output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
        return mark_safe(self.format_output(output))
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def render_flatpage(request, f):
    """
    Internal interface to the flat page view.
    """
    # If registration is required for accessing this page, and the user isn't
    # logged in, redirect to the login page.
    if f.registration_required and not request.user.is_authenticated():
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)
    if f.template_name:
        template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
    else:
        template = loader.get_template(DEFAULT_TEMPLATE)

    # To avoid having to always use the "|safe" filter in flatpage templates,
    # mark the title and content as already safe (since they are raw HTML
    # content in the first place).
    f.title = mark_safe(f.title)
    f.content = mark_safe(f.content)

    response = HttpResponse(template.render({'flatpage': f}, request))
    return response
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def load_map_js(self):
        """
        Returns JavaScript containing all of the loading routines for each
        map in this set.
        """
        result = []
        for dom_id, gmap in zip(self.dom_ids, self.maps):
            # Backup copies the GoogleMap DOM id and template attributes.
            # They are overridden on each GoogleMap instance in the set so
            # that only the loading JavaScript (and not the header variables)
            # is used with the generated DOM ids.
            tmp = (gmap.template, gmap.dom_id)
            gmap.template = self.map_template
            gmap.dom_id = dom_id
            result.append(gmap.js)
            # Restoring the backup values.
            gmap.template, gmap.dom_id = tmp
        return mark_safe(''.join(result))
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def render(self, name, value, attrs=None):
        if self.is_localized:
            self.widget.is_localized = self.is_localized
        value = value or []
        output = []
        final_attrs = self.build_attrs(attrs)
        id_ = final_attrs.get('id')
        for i in range(max(len(value), self.size)):
            try:
                widget_value = value[i]
            except IndexError:
                widget_value = None
            if id_:
                final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
            output.append(self.widget.render(name + '_%s' % i, widget_value, final_attrs))
        return mark_safe(self.format_output(output))
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def localize(value, use_l10n=None):
    """
    Checks if value is a localizable type (date, number...) and returns it
    formatted as a string using current locale format.

    If use_l10n is provided and is not None, that will force the value to
    be localized (or not), overriding the value of settings.USE_L10N.
    """
    if isinstance(value, bool):
        return mark_safe(six.text_type(value))
    elif isinstance(value, (decimal.Decimal, float) + six.integer_types):
        return number_format(value, use_l10n=use_l10n)
    elif isinstance(value, datetime.datetime):
        return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n)
    elif isinstance(value, datetime.date):
        return date_format(value, use_l10n=use_l10n)
    elif isinstance(value, datetime.time):
        return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n)
    else:
        return value
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def format_html_join(sep, format_string, args_generator):
    """
    A wrapper of format_html, for the common case of a group of arguments that
    need to be formatted using the same format string, and then joined using
    'sep'. 'sep' is also passed through conditional_escape.

    'args_generator' should be an iterator that returns the sequence of 'args'
    that will be passed to format_html.

    Example:

      format_html_join('\n', "<li>{} {}</li>", ((u.first_name, u.last_name)
                                                  for u in users))
    """
    return mark_safe(conditional_escape(sep).join(
        format_html(format_string, *tuple(args))
        for args in args_generator))
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def render(self, name, value, attrs=None):
        substitutions = {
            'initial_text': self.initial_text,
            'input_text': self.input_text,
            'clear_template': '',
            'clear_checkbox_label': self.clear_checkbox_label,
        }
        template = '%(input)s'
        substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)

        if self.is_initial(value):
            template = self.template_with_initial
            substitutions.update(self.get_template_substitution_values(value))
            if not self.is_required:
                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.template_with_clear % substitutions

        return mark_safe(template % substitutions)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def render(self, name, value, attrs=None):
        if self.is_localized:
            for widget in self.widgets:
                widget.is_localized = self.is_localized
        # value is a list of values, each corresponding to a widget
        # in self.widgets.
        if not isinstance(value, list):
            value = self.decompress(value)
        output = []
        final_attrs = self.build_attrs(attrs)
        id_ = final_attrs.get('id')
        for i, widget in enumerate(self.widgets):
            try:
                widget_value = value[i]
            except IndexError:
                widget_value = None
            if id_:
                final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
            output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
        return mark_safe(self.format_output(output))
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
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)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def render_flatpage(request, f):
    """
    Internal interface to the flat page view.
    """
    # If registration is required for accessing this page, and the user isn't
    # logged in, redirect to the login page.
    if f.registration_required and not request.user.is_authenticated:
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)
    if f.template_name:
        template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
    else:
        template = loader.get_template(DEFAULT_TEMPLATE)

    # To avoid having to always use the "|safe" filter in flatpage templates,
    # mark the title and content as already safe (since they are raw HTML
    # content in the first place).
    f.title = mark_safe(f.title)
    f.content = mark_safe(f.content)

    response = HttpResponse(template.render({'flatpage': f}, request))
    return response
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def load_map_js(self):
        """
        Returns JavaScript containing all of the loading routines for each
        map in this set.
        """
        result = []
        for dom_id, gmap in zip(self.dom_ids, self.maps):
            # Backup copies the GoogleMap DOM id and template attributes.
            # They are overridden on each GoogleMap instance in the set so
            # that only the loading JavaScript (and not the header variables)
            # is used with the generated DOM ids.
            tmp = (gmap.template, gmap.dom_id)
            gmap.template = self.map_template
            gmap.dom_id = dom_id
            result.append(gmap.js)
            # Restoring the backup values.
            gmap.template, gmap.dom_id = tmp
        return mark_safe(''.join(result))
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def render(self, name, value, attrs=None):
        if self.is_localized:
            self.widget.is_localized = self.is_localized
        value = value or []
        output = []
        final_attrs = self.build_attrs(attrs)
        id_ = final_attrs.get('id')
        for i in range(max(len(value), self.size)):
            try:
                widget_value = value[i]
            except IndexError:
                widget_value = None
            if id_:
                final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
            output.append(self.widget.render(name + '_%s' % i, widget_value, final_attrs))
        return mark_safe(self.format_output(output))
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def label_tag(self):
        classes = []
        contents = conditional_escape(force_text(self.field.label))
        if self.is_checkbox:
            classes.append('vCheckboxLabel')

        if self.field.field.required:
            classes.append('required')
        if not self.is_first:
            classes.append('inline')
        attrs = {'class': ' '.join(classes)} if classes else {}
        # checkboxes should not have a label suffix as the checkbox appears
        # to the left of the label.
        return self.field.label_tag(
            contents=mark_safe(contents), attrs=attrs,
            label_suffix='' if self.is_checkbox else None,
        )
项目:django-happenings    作者:natgeosociety    | 项目源码 | 文件源码
def render(self, name, value, attrs=None):
        if attrs is None:
            attrs = {}
        # it's called "original" because it will be replaced by a copy
        attrs['class'] = 'hstore-original-textarea'

        # get default HTML from AdminTextareaWidget
        html = super(BaseAdminHStoreWidget, self).render(name, value, attrs)

        # prepare template context
        template_context = Context({
            'field_name': name,
            'STATIC_URL': settings.STATIC_URL,
            'use_svg': django.VERSION >= (1, 9),  # use svg icons if django >= 1.9
        })
        # get template object
        template = get_template('happenings/hstore_%s_widget.html' % self.admin_style)
        # render additional html
        additional_html = template.render(template_context)

        # append additional HTML and mark as safe
        html = html + additional_html
        html = mark_safe(html)

        return html
项目:django-happenings    作者:natgeosociety    | 项目源码 | 文件源码
def render(self, name, value, attrs=None):
        # get default HTML from AdminTextareaWidget
        html = super(RecurringEventWidget, self).render(name, value, attrs)

        if '__prefix__' in name:
            return mark_safe(html)

        data = {
            "url": reverse('admin:happenings_get_occurrences'),
            "field_id": attrs['id'],
            "date_field": attrs['id'].replace(self.text_field, self.start_date_field)
        }
        additional_html = self.js_tmpl % data

        # append additional HTML and mark as safe
        html = html + additional_html
        html = mark_safe(html)

        return html
项目:zing    作者:evernote    | 项目源码 | 文件源码
def reset_captcha(self):
        """Generate new question and valid token for it, reset previous answer
        if any.
        """
        q, a = self._generate_captcha()
        expires = time.time() + \
            getattr(settings, 'CAPTCHA_EXPIRES_SECONDS', 60*60)
        token = self._make_token(q, a, expires)
        self.initial['captcha_token'] = token
        self._plain_question = q
        # reset captcha fields for bound form
        if self.data:
            def _reset():
                self.data['captcha_token'] = token
                self.data['captcha_answer'] = ''
            if hasattr(self.data, '_mutable') and not self.data._mutable:
                self.data._mutable = True
                _reset()
                self.data._mutable = False
            else:
                _reset()

        self.fields['captcha_answer'].label = mark_safe(self.knotty_question)
项目:zing    作者:evernote    | 项目源码 | 文件源码
def edit(request, template, model_class, ctx=None,
         link=None, linkfield='code', queryset=None, **kwargs):
    formset, msg, objects = process_modelformset(request, model_class,
                                                 queryset=queryset, **kwargs)
    if ctx is None:
        ctx = {}

    ctx.update({
        'formset_text': mark_safe(form_set_as_table(formset, link, linkfield)),
        'formset': formset,
        'objects': objects,
        'error_msg': msg,
        'can_add': kwargs.get('extra', 1) != 0,
    })

    return render(request, template, ctx)
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def wikilink(value):
    """
    Produce wiki style links to other pages within the database, for use in
    comments fields: {{ a_note|wikilink|truncatewords_html:5 }}
    Note that it's better to use truncatewords_html with this filter, rather
    than plain truncatewords
    """
    WIKILINK_RE = re.compile(r"""
            (?P<lead>\s|^)  # possible leading whitespace
            (?P<wikilink>/  # an initial /
              (\w+/)+       # multiples of any number of identifier chars + /
            )
            """,
                             re.VERBOSE)

    def wikilink_sub_callback(match_obj):
        link = match_obj.group("wikilink")
        lead = match_obj.group("lead")
        return '%s<a href="%s">%s</a>' % (lead, escape(link), escape(link))
    return mark_safe(WIKILINK_RE.sub(wikilink_sub_callback, value))
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def smart_personal_names(self, value):
        names_lst = []
        for pn in value.split(' and '):
            try:
                last_name, first_name = pn.split(', ')
                name = "<span class='name'><span class='lastName'>%s</span>" \
                       ", <span class='firstName'>%s</span></span>" \
                       % (last_name, first_name)
                names_lst.append(name)
            except ValueError:
                names_lst.append(pn)
        if len(names_lst) > 2:
            return mark_safe('%s and %s' %
                             (', '.join(names_lst[:-1]),
                              names_lst[-1]))
        return mark_safe(' and '.join(names_lst))
项目:blog_django    作者:chnpmy    | 项目源码 | 文件源码
def get_form_params(self, new_params=None, remove=None):
        if new_params is None:
            new_params = {}
        if remove is None:
            remove = []
        p = dict(self.request.GET.items()).copy()
        arr_keys = list(p.keys())
        for r in remove:
            for k in arr_keys:
                if k.startswith(r):
                    del p[k]
        for k, v in new_params.items():
            if v is None:
                if k in p:
                    del p[k]
            else:
                p[k] = v
        return mark_safe(''.join(
            '<input type="hidden" name="%s" value="%s"/>' % (k, v) for k, v in p.items() if v))
项目:blog_django    作者:chnpmy    | 项目源码 | 文件源码
def view_block(context, block_name, *args, **kwargs):
    if 'admin_view' not in context:
        return ""

    admin_view = context['admin_view']
    nodes = []
    method_name = 'block_%s' % block_name

    for view in [admin_view] + admin_view.plugins:
        if hasattr(view, method_name) and callable(getattr(view, method_name)):
            block_func = getattr(view, method_name)
            result = block_func(context, nodes, *args, **kwargs)
            if result and (
                    isinstance(result, str)
                    or sys.version_info.major < 3 and isinstance(result, unicode)
                    ):
                nodes.append(result)
    if nodes:
        return mark_safe(''.join(nodes))
    else:
        return ""
项目:blog_django    作者:chnpmy    | 项目源码 | 文件源码
def _get_new_field_html(self, field_name):
        try:
            f, attr, value = lookup_field(field_name, self.org_obj, self)
        except (AttributeError, ObjectDoesNotExist):
            return EMPTY_CHANGELIST_VALUE
        else:
            allow_tags = False
            if f is None:
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean:
                    allow_tags = True
                    text = boolean_icon(value)
                else:
                    text = smart_text(value)
            else:
                if isinstance(f.rel, models.ManyToOneRel):
                    field_val = getattr(self.org_obj, f.name)
                    if field_val is None:
                        text = EMPTY_CHANGELIST_VALUE
                    else:
                        text = field_val
                else:
                    text = display_for_field(value, f)
            return mark_safe(text) if allow_tags else conditional_escape(text)
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def render_flatpage(request, f):
    """
    Internal interface to the flat page view.
    """
    # If registration is required for accessing this page, and the user isn't
    # logged in, redirect to the login page.
    if f.registration_required and not request.user.is_authenticated:
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)
    if f.template_name:
        template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
    else:
        template = loader.get_template(DEFAULT_TEMPLATE)

    # To avoid having to always use the "|safe" filter in flatpage templates,
    # mark the title and content as already safe (since they are raw HTML
    # content in the first place).
    f.title = mark_safe(f.title)
    f.content = mark_safe(f.content)

    response = HttpResponse(template.render({'flatpage': f}, request))
    return response
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def get_context(self, name, value, attrs):
        context = super(ForeignKeyRawIdWidget, self).get_context(name, value, attrs)
        rel_to = self.rel.model
        if rel_to in self.admin_site._registry:
            # The related object is registered with the same AdminSite
            related_url = reverse(
                'admin:%s_%s_changelist' % (
                    rel_to._meta.app_label,
                    rel_to._meta.model_name,
                ),
                current_app=self.admin_site.name,
            )

            params = self.url_parameters()
            if params:
                related_url += '?' + '&amp;'.join(
                    '%s=%s' % (k, v) for k, v in params.items(),
                )
            context['related_url'] = mark_safe(related_url)
            context['link_title'] = _('Lookup')
            # The JavaScript code looks for this class.
            context['widget']['attrs'].setdefault('class', 'vForeignKeyRawIdAdminField')
        if context['widget']['value']:
            context['link_label'], context['link_url'] = self.label_and_url_for_value(value)
        return context
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def label_tag(self):
        classes = []
        contents = conditional_escape(force_text(self.field.label))
        if self.is_checkbox:
            classes.append('vCheckboxLabel')

        if self.field.field.required:
            classes.append('required')
        if not self.is_first:
            classes.append('inline')
        attrs = {'class': ' '.join(classes)} if classes else {}
        # checkboxes should not have a label suffix as the checkbox appears
        # to the left of the label.
        return self.field.label_tag(
            contents=mark_safe(contents), attrs=attrs,
            label_suffix='' if self.is_checkbox else None,
        )
项目:decouvrez_django    作者:oc-courses    | 项目源码 | 文件源码
def contact_link(self, booking):
        url = self.get_admin_url(booking.contact)
        return mark_safe("<a href='{}'>{}</a>".format(url, booking.contact.name))
项目:decouvrez_django    作者:oc-courses    | 项目源码 | 文件源码
def album_link(self, booking):
        url = self.get_admin_url(booking.album)
        return mark_safe("<a href='{}'>{}</a>".format(url, booking.album.title))
项目:decouvrez_django    作者:oc-courses    | 项目源码 | 文件源码
def album_link(self, booking):
        url = self.get_admin_url(booking.album)
        return mark_safe("<a href='{}'>{}</a>".format(url, booking.album.title))
项目:plugs-mail    作者:solocompt    | 项目源码 | 文件源码
def button(url, txt):
    template = '<div style="padding: 30px;"><a target="_blank" href="{0}" style="{1}" class="button">{2}</a></div>'
    html = template.format(url, get_styles(), txt)
    return mark_safe(html)
项目:django-admin-reports    作者:simplyopen-it    | 项目源码 | 文件源码
def get_help_text(self):
        return mark_safe(self.help_text)
项目:django-admin-reports    作者:simplyopen-it    | 项目源码 | 文件源码
def get_description(self):
        return mark_safe(self.description)
项目:django-prosemirror    作者:zakdoek    | 项目源码 | 文件源码
def prosemirror(content, headingoffset=0):
    """
    Render prosemirror content as html with a specified header level.

    1 is h1, 2 is h2, ...
    """
    return mark_safe(render(content, headingoffset))
项目:django-powerpages    作者:Open-E-WEB    | 项目源码 | 文件源码
def validate(self, request=None):
        """Check validity of configuration and Page template"""
        self.config.validate()
        try:
            context = self.get_validation_context(request=request)
            self.render(context)
        except:
            tb_info = traceback.format_exc()
            msg = (
                'An error occurred trying to render the Page:\n'
                '<br/><pre>{0}</pre>'.format(tb_info)
            )
            raise ValidationError(mark_safe(msg))
项目:django-powerpages    作者:Open-E-WEB    | 项目源码 | 文件源码
def validate(self, request=None):
        try:
            self.get_redirect_location()
        except:
            tb_info = traceback.format_exc()
            msg = (
                'An error occurred trying to render the Page:\n'
                '<br/><pre>{0}</pre>'.format(tb_info)
            )
            raise ValidationError(mark_safe(msg))
项目:django-powerpages    作者:Open-E-WEB    | 项目源码 | 文件源码
def sync_status(page):
    """Synchronization status of the Page"""
    if not page:
        return None
    status_parts = []
    if page.is_dirty:
        status_parts.append(
            '<span style="color:black; font-weight:bold">'
            'Changed in Admin!'
            '</span>'
        )
    dump_status = PageFileDumper(page).status()
    if dump_status == SyncStatus.NO_CHANGES:
        dump_text = 'File is synced'
        dump_color = 'green'
    elif dump_status == SyncStatus.MODIFIED:
        dump_text = 'File content differs'
        dump_color = 'orange'
    elif dump_status == SyncStatus.ADDED:
        dump_text = 'File is missing'
        dump_color = 'red'
    else:  # Unknown sync status
        dump_text = '?'
        dump_color = 'black'
    status_parts.append(
        '<span style="color: {0}">{1}</span>'.format(
            dump_color, dump_text
        )
    )
    return mark_safe('<br>'.join(status_parts))
项目:tts-bug-bounty-dashboard    作者:18F    | 项目源码 | 文件源码
def get_bookmarklet_url(request):
    scheme = 'http' if settings.DEBUG else 'https'
    host = request.META['HTTP_HOST']
    return mark_safe('javascript:' + render_to_string(
        'bookmarklet.js',
        {
            'base_url': f'{scheme}://{host}'
        },
        request=request
    ).replace('\n', '').replace('"', '&quot;'))