コード例 #1
0
def force_escape(value):
    """
    Escapes a string's HTML. This returns a new string containing the escaped
    characters (as opposed to "escape", which marks the content for later
    possible escaping).
    """
    return mark_safe(escape(value))
コード例 #2
0
 def label_for_value(self, value):
     key = self.rel.get_related_field().name
     try:
         obj = self.rel.to._default_manager.using(
             self.db).get(**{key: value})
         return '&nbsp;<strong>%s</strong>' % escape(
             Truncator(obj).words(14, truncate='...'))
     except (ValueError, self.rel.to.DoesNotExist):
         return ''
コード例 #3
0
def linebreaksbr(value, autoescape=None):
    """
    Converts all newlines in a piece of plain text to HTML line breaks
    (``<br />``).
    """
    autoescape = autoescape and not isinstance(value, SafeData)
    value = normalize_newlines(value)
    if autoescape:
        value = escape(value)
    return mark_safe(value.replace('\n', '<br />'))
コード例 #4
0
 def label_tag(self):
     attrs = {}
     if not self.is_first:
         attrs["class"] = "inline"
     label = self.field['label']
     contents = capfirst(force_unicode(escape(label))) + u":"
     return mark_safe('<label%(attrs)s>%(contents)s</label>' % {
         "attrs": flatatt(attrs),
         "contents": contents,
     })
コード例 #5
0
 def humanize_tester(self, test_list, result_list, method):
     # Using max below ensures we go through both lists
     # However, if the lists are not equal length, this raises an exception
     for test_content, result in zip(test_list, result_list):
         t = Template('{%% load humanize %%}{{ test_content|%s }}' % method)
         rendered = t.render(Context(locals())).strip()
         self.assertEqual(
             rendered,
             escape(result),
             msg="%s test failed, produced '%s', should've produced '%s'" %
             (method, rendered, result))
コード例 #6
0
    def format_callback(obj):
        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 = '%s.%s' % (opts.app_label, opts.get_delete_permission())
            if not user.has_perm(p):
                perms_needed.add(opts.verbose_name)
            # Display a link to the admin page.
            return mark_safe(
                u'%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 u'%s: %s' % (capfirst(
                opts.verbose_name), force_unicode(obj))
コード例 #7
0
 def render_option(self, selected_choices, option_value, option_label):
     option_value = force_unicode(option_value)
     if option_value in selected_choices:
         selected_html = u' selected="selected"'
         if not self.allow_multiple_selected:
             # Only allow for a single selection.
             selected_choices.remove(option_value)
     else:
         selected_html = ''
     return u'<option value="%s"%s>%s</option>' % (
         escape(option_value), selected_html,
         conditional_escape(force_unicode(option_label)))
コード例 #8
0
 def render_options(self, choices, selected_choices):
     # Normalize to strings.
     selected_choices = set(force_unicode(v) for v in selected_choices)
     output = []
     for option_value, option_label in chain(self.choices, choices):
         if isinstance(option_label, (list, tuple)):
             output.append(u'<optgroup label="%s">' % escape(force_unicode(option_value)))
             for option in option_label:
                 output.append(self.render_option(selected_choices, *option))
             output.append(u'</optgroup>')
         else:
             output.append(self.render_option(selected_choices, option_value, option_label))
     return u'\n'.join(output)
コード例 #9
0
    def get_template_exception_info(self):
        origin, (start, end) = self.exc_value.django_template_source
        template_source = origin.reload()
        context_lines = 10
        line = 0
        upto = 0
        source_lines = []
        before = during = after = ""
        for num, next in enumerate(linebreak_iter(template_source)):
            if start >= upto and end <= next:
                line = num
                before = escape(template_source[upto:start])
                during = escape(template_source[start:end])
                after = escape(template_source[end:next])
            source_lines.append((num, escape(template_source[upto:next])))
            upto = next
        total = len(source_lines)

        top = max(1, line - context_lines)
        bottom = min(total, line + 1 + context_lines)

        # In some rare cases, exc_value.args might be empty.
        try:
            message = self.exc_value.args[0]
        except IndexError:
            message = '(Could not get exception message)'

        self.template_info = {
            'message': message,
            'source_lines': source_lines[top:bottom],
            'before': before,
            'during': during,
            'after': after,
            'top': top,
            'bottom': bottom,
            'total': total,
            'line': line,
            'name': origin.name,
        }
コード例 #10
0
def paginator_number(cl, i):
    """
    Generates an individual page index link in a paginated list.
    """
    if i == DOT:
        return u'... '
    elif i == cl.page_num:
        return mark_safe(u'<span class="this-page">%d</span> ' % (i + 1))
    else:
        return mark_safe(u'<a href="%s"%s>%d</a> ' %
                         (escape(cl.get_query_string({PAGE_VAR: i})),
                          (i == cl.paginator.num_pages - 1 and ' class="end"'
                           or ''), i + 1))
コード例 #11
0
def linenumbers(value, autoescape=None):
    """Displays text with line numbers."""
    lines = value.split(u'\n')
    # Find the maximum width of the line count, for use with zero padding
    # string format command
    width = unicode(len(unicode(len(lines))))
    if not autoescape or isinstance(value, SafeData):
        for i, line in enumerate(lines):
            lines[i] = (u"%0" + width + u"d. %s") % (i + 1, line)
    else:
        for i, line in enumerate(lines):
            lines[i] = (u"%0" + width + u"d. %s") % (i + 1, escape(line))
    return mark_safe(u'\n'.join(lines))
コード例 #12
0
def _render_value_in_context(value, context):
    """
    Converts any value to a string to become part of a rendered template. This
    means escaping, if required, and conversion to a unicode object. If value
    is a string, it is expected to have already been translated.
    """
    value = localtime(value, use_tz=context.use_tz)
    value = localize(value, use_l10n=context.use_l10n)
    value = force_unicode(value)
    if ((context.autoescape and not isinstance(value, SafeData))
            or isinstance(value, EscapeData)):
        return escape(value)
    else:
        return value
コード例 #13
0
    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 = u'%(input)s'
        substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)

        if value and hasattr(value, "url"):
            template = self.template_with_initial
            substitutions['initial'] = (u'<a href="%s">%s</a>'
                                        % (escape(value.url),
                                           escape(force_unicode(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)
コード例 #14
0
class DebugVariableNode(VariableNode):
    def render(self, context):
        try:
            output = self.filter_expression.resolve(context)
            output = localtime(output, use_tz=context.use_tz)
            output = localize(output, use_l10n=context.use_l10n)
            output = force_unicode(output)
        except UnicodeDecodeError:
            return ''
        except Exception, e:
            if not hasattr(e, 'django_template_source'):
                e.django_template_source = self.source
            raise
        if (context.autoescape and not isinstance(output, SafeData)) or isinstance(output, EscapeData):
            return escape(output)
        else:
            return output
コード例 #15
0
    def html(self):
        '''
        Возвращает HTML-текст статьи, полученный фильтрацией содержимого
        через указанный фильтр.
        '''
        if self.filter in filters:
            result = filters[self.filter](self.text)
        else:
            result = linebreaks(escape(self.text))

        return mark_safe(result)

        soup = BeautifulSoup(result)

        def urlify(s):
            s = re.sub(WWW_PATTERN, r'\1http://www.', s)
            s = re.sub(FTP_PATTERN, r'\1ftp://ftp.', s)
            s = re.sub(PROTOCOL_PATTERN, r'<a href="\1\2">\1\2</a>\3\4', s)
            return BeautifulSoup(s)

        def has_parents(node, tags):
            if node is None:
                return False
            return node.name in tags or has_parents(node.parent, tags)

        text_chunks = [
            c for c in soup.recursiveChildGenerator()
            if isinstance(c, unicode)
        ]
        for chunk in text_chunks:
            s = chunk
            if not has_parents(chunk.parent, ['code']):
                s = re.sub(ur'\B--\B', u'—', s)
            if not has_parents(chunk.parent, ['a', 'code']):
                s = urlify(s)
            chunk.replaceWith(s)

        for link in soup.findAll('a'):
            if 'rel' in link:
                link['rel'] += ' '
            else:
                link['rel'] = ''
            link['rel'] += 'nofollow'
        result = unicode(soup)
        return mark_safe(result)
コード例 #16
0
    def user_change_password(self, request, id, form_url=''):
        if not self.has_change_permission(request):
            raise PermissionDenied
        user = get_object_or_404(self.queryset(request), pk=id)
        if request.method == 'POST':
            form = self.change_password_form(user, request.POST)
            if form.is_valid():
                form.save()
                msg = ugettext('Password changed successfully.')
                messages.success(request, msg)
                return HttpResponseRedirect('..')
        else:
            form = self.change_password_form(user)

        fieldsets = [(None, {'fields': form.base_fields.keys()})]
        adminForm = admin.helpers.AdminForm(form, fieldsets, {})

        context = {
            'title': _('Change password: %s') % escape(user.username),
            'adminForm': adminForm,
            'form_url': mark_safe(form_url),
            'form': form,
            'is_popup': '_popup' in request.REQUEST,
            'add': True,
            'change': False,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_absolute_url': False,
            'opts': self.model._meta,
            'original': user,
            'save_as': False,
            'show_save': True,
        }
        return TemplateResponse(request, [
            self.change_user_password_template or
            'admin/auth/user/change_password.html'
        ], context, current_app=self.admin_site.name)
コード例 #17
0
def post_comment(request, next=None, using=None):
    """
    Post a comment.

    HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are
    errors a preview template, ``comments/preview.html``, will be rendered.
    """
    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name(
            ) or request.user.username
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Check to see if the POST data overrides the view's next argument.
    next = data.get("next", next)

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return CommentPostBadRequest(
            "Missing content_type or object_pk field.")
    try:
        model = models.get_model(*ctype.split(".", 1))
        target = model._default_manager.using(using).get(pk=object_pk)
    except TypeError:
        return CommentPostBadRequest("Invalid content_type value: %r" %
                                     escape(ctype))
    except AttributeError:
        return CommentPostBadRequest(
            "The given content-type %r does not resolve to a valid model." % \
                escape(ctype))
    except ObjectDoesNotExist:
        return CommentPostBadRequest(
            "No object matching content-type %r and object PK %r exists." % \
                (escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError), e:
        return CommentPostBadRequest(
            "Attempting go get content-type %r and object PK %r exists raised %s" % \
                (escape(ctype), escape(object_pk), e.__class__.__name__))
コード例 #18
0
def items_for_result(cl, result, form):
    """
    Generates the actual list of data.
    """
    first = True
    pk = cl.lookup_opts.pk.attname
    for field_name in cl.list_display:
        row_class = ''
        try:
            f, attr, value = lookup_field(field_name, result, cl.model_admin)
        except (AttributeError, ObjectDoesNotExist):
            result_repr = EMPTY_CHANGELIST_VALUE
        else:
            if f is None:
                if field_name == u'action_checkbox':
                    row_class = ' class="action-checkbox"'
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean:
                    allow_tags = True
                    result_repr = _boolean_icon(value)
                else:
                    result_repr = smart_unicode(value)
                # Strip HTML tags in the resulting text, except if the
                # function has an "allow_tags" attribute set to True.
                if not allow_tags:
                    result_repr = escape(result_repr)
                else:
                    result_repr = mark_safe(result_repr)
            else:
                if isinstance(f.rel, models.ManyToOneRel):
                    field_val = getattr(result, f.name)
                    if field_val is None:
                        result_repr = EMPTY_CHANGELIST_VALUE
                    else:
                        result_repr = escape(field_val)
                else:
                    result_repr = display_for_field(value, f)
                if isinstance(f, models.DateField)\
                or isinstance(f, models.TimeField)\
                or isinstance(f, models.ForeignKey):
                    row_class = ' class="nowrap"'
        if force_unicode(result_repr) == '':
            result_repr = mark_safe('&nbsp;')
        # If list_display_links not defined, add the link tag to the first field
        if (first and not cl.list_display_links
            ) or field_name in cl.list_display_links:
            table_tag = {True: 'th', False: 'td'}[first]
            first = False
            url = cl.url_for_result(result)
            # Convert the pk to something that can be used in Javascript.
            # Problem cases are long ints (23L) and non-ASCII strings.
            if cl.to_field:
                attr = str(cl.to_field)
            else:
                attr = pk
            value = result.serializable_value(attr)
            result_id = repr(force_unicode(value))[1:]
            yield mark_safe(u'<%s%s><a href="%s"%s>%s</a></%s>' % \
                (table_tag, row_class, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag))
        else:
            # By default the fields come from ModelAdmin.list_editable, but if we pull
            # the fields out of the form instead of list_editable custom admins
            # can provide fields on a per request basis
            if (form and field_name in form.fields
                    and not (field_name == cl.model._meta.pk.name
                             and form[cl.model._meta.pk.name].is_hidden)):
                bf = form[field_name]
                result_repr = mark_safe(
                    force_unicode(bf.errors) + force_unicode(bf))
            else:
                result_repr = conditional_escape(result_repr)
            yield mark_safe(u'<td%s>%s</td>' % (row_class, result_repr))
    if form and not form[cl.model._meta.pk.name].is_hidden:
        yield mark_safe(u'<td>%s</td>' %
                        force_unicode(form[cl.model._meta.pk.name]))
コード例 #19
0
    except (ValueError, ValidationError), e:
        return CommentPostBadRequest(
            "Attempting go get content-type %r and object PK %r exists raised %s" % \
                (escape(ctype), escape(object_pk), e.__class__.__name__))

    # Do we want to preview the comment?
    preview = "preview" in data

    # Construct the comment form
    form = comments.get_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest(
            "The comment form failed security verification: %s" % \
                escape(str(form.security_errors())))

    # If there are errors or if we requested a preview show the comment
    if form.errors or preview:
        template_list = [
            # These first two exist for purely historical reasons.
            # Django v1.0 and v1.1 allowed the underscore format for
            # preview templates, so we have to preserve that format.
            "comments/%s_%s_preview.html" %
            (model._meta.app_label, model._meta.module_name),
            "comments/%s_preview.html" % model._meta.app_label,
            # Now the usual directory based template hierarchy.
            "comments/%s/%s/preview.html" %
            (model._meta.app_label, model._meta.module_name),
            "comments/%s/preview.html" % model._meta.app_label,
            "comments/preview.html",
コード例 #20
0
 def test_no_textile(self):
     t = Template("{% load markup %}{{ textile_content|textile }}")
     rendered = t.render(Context({'textile_content':
                                  self.textile_content})).strip()
     self.assertEqual(rendered, escape(self.textile_content))
コード例 #21
0
 def item_title(self, item):
     # Titles should be double escaped by default (see #6533)
     return escape(force_unicode(item))