Esempio n. 1
0
    def render(self, name, value, attrs=None, ):

        substitutions = {
            'initial_text': u'Currently',
            'input_text': self.input_text,
            'clear_template': '',
            'clear_checkbox_label': self.clear_checkbox_label,
        }
        template = '<p class="file-input">' + u'%(input)s' + \
                   ('<a href="javascript:FileBrowser.show(\'id_productimage_set-0-image\', \'/admin/filebrowser/browse/?pop=1&dir=images/products\');" class="fb_show"><img src="/static/filebrowser/img/filebrowser_icon_show.gif" alt=""></a><br><img class="preupload_thumbnail" width="%s"></p>' % self.image_width)
        if 'class' in attrs:
            attrs['class'] += ' advancedfileinput'
        else:
            attrs['class'] = 'advancedfileinput'
        substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)

        if value and hasattr(value, "url"):

            template = '<p class="file-input"> %(initial_text)s: %(initial)s<span style="display:inline-block;margin-left: 7px;">%(clear_template)s</span> <br>%(input_text)s: %(input)s <br> %(thumbnail)s </p>'
            if self.preview:
                substitutions['initial'] = (u'<a href="{0}">{1}</a>'.format(escape(value.url), '...' + escape(force_unicode(value))[-self.url_length:]))
                substitutions['thumbnail'] = (u'<a href="{0}" target="_blank"><img src="{1}" width="{2}"></a>'.format(escape(value.url), escape(value.url), self.image_width))
            else:
                substitutions['initial'] = (u'<a href="{0}">{1}</a>'.format(escape(value.url), '...' + escape(force_unicode(value))[-self.url_length:]))
            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, 'style': 'margin-top: 2px; margin-left: 1px;'})
                substitutions['clear_template'] = self.template_with_clear % substitutions
        return mark_safe(template % substitutions)
Esempio n. 2
0
    def test_render(self):
        band = models.Band.objects.create(name='Linkin Park')
        band.album_set.create(
            name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
        )

        m1 = models.Member.objects.create(name='Chester')
        m2 = models.Member.objects.create(name='Mike')
        band.members.add(m1, m2)
        rel = models.Band._meta.get_field('members').rel

        w = ManyToManyRawIdWidget(rel)
        self.assertEqual(
            conditional_escape(w.render('test', [m1.pk, m2.pk], attrs={})),
            '<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField" /><a href="../../../admin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_MEDIA_PREFIX)simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX, "m1pk": m1.pk, "m2pk": m2.pk},
        )

        self.assertEqual(
            conditional_escape(w.render('test', [m1.pk])),
            '<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField" /><a href="../../../admin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_MEDIA_PREFIX)simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX, "m1pk": m1.pk},
        )

        self.assertEqual(w._has_changed(None, None), False)
        self.assertEqual(w._has_changed([], None), False)
        self.assertEqual(w._has_changed(None, [u'1']), True)
        self.assertEqual(w._has_changed([1, 2], [u'1', u'2']), False)
        self.assertEqual(w._has_changed([1, 2], [u'1']), True)
        self.assertEqual(w._has_changed([1, 2], [u'1', u'3']), True)
 def render(self, name, value, attrs=None):
     if value is None:
         value = ''
     input_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
     if value != '':
         # Only add the 'value' attribute if a value is non-empty.
         input_attrs['value'] = force_text(self._format_value(value))
     input_attrs = dict([(key, conditional_escape(val)) for key, val in input_attrs.items()])  # python2.6 compatible
     if not self.picker_id:
          self.picker_id = (input_attrs.get('id', '') +
                            '_pickers').replace(' ', '_')
     self.div_attrs['id'] = self.picker_id
     picker_id = conditional_escape(self.picker_id)
     div_attrs = dict(
         [(key, conditional_escape(val)) for key, val in self.div_attrs.items()])  # python2.6 compatible
     icon_attrs = dict([(key, conditional_escape(val)) for key, val in self.icon_attrs.items()])
     html = self.html_template % dict(div_attrs=flatatt(div_attrs),
                                      input_attrs=flatatt(input_attrs),
                                      icon_attrs=flatatt(icon_attrs))
     if self.options:
         self.options['language'] = translation.get_language()
         js = self.js_template % dict(picker_id=picker_id,
                                      options=json.dumps(self.options or {}))
     else:
         js = ''
     return mark_safe(force_text(html + js))
Esempio n. 4
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 = '%(input)s'
        substitutions['input'] = self.input_render(name, value, attrs)

        if value:
            template = self.template_with_initial
            substitutions['initial'] = format_html(self.url_markup_template,
                                                   # url
                                                   absolute_media_path(value),
                                                   force_text(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'] = forms.CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id})
                substitutions['clear_template'] = self.template_with_clear % substitutions

        return mark_safe(template % substitutions)
Esempio n. 5
0
File: api.py Progetto: abellina/hue
def massage_doc_for_json(doc, user):
  read_perms = doc.list_permissions(perm='read')
  write_perms = doc.list_permissions(perm='write')
  return {
      'id': doc.id,
      'contentType': doc.content_type.name,
      'icon': doc.icon,
      'name': html.conditional_escape(doc.name),
      'url': html.conditional_escape(doc.content_object.get_absolute_url()),
      'description': html.conditional_escape(doc.description),
      'tags': [{'id': tag.id, 'name': html.conditional_escape(tag.tag)} \
               for tag in doc.tags.all()],
      'perms': {
        'read': {
          'users': [{'id': perm_user.id, 'username': perm_user.username} for perm_user in read_perms.users.all()],
          'groups': [{'id': perm_group.id, 'name': perm_group.name} for perm_group in read_perms.groups.all()]
        },
        'write': {
          'users': [{'id': perm_user.id, 'username': perm_user.username} for perm_user in write_perms.users.all()],
          'groups': [{'id': perm_group.id, 'name': perm_group.name} for perm_group in write_perms.groups.all()]
        }
      },
      'owner': doc.owner.username,
      'isMine': doc.owner.username == user.username,
      'lastModified': doc.last_modified.strftime("%x %X"),
      'lastModifiedInMillis': time.mktime(doc.last_modified.timetuple())
    }
Esempio n. 6
0
def mungify(email, text=None, autoescape=None):
    text = text or email
    
    if autoescape:
        email = conditional_escape(email)
        text = conditional_escape(text)

    emailArrayContent = ''
    textArrayContent = ''
    r = lambda c: '"' + str(ord(c)) + '",'

    for c in email: emailArrayContent += r(c)
    for c in text: textArrayContent += r(c)

    result = """<script>
                var _tyjsdf = [%s], _qplmks = [%s];
                document.write('<a
href="&#x6d;&#97;&#105;&#x6c;&#000116;&#111;&#x3a;');
                for(_i=0;_i<_tyjsdf.length;_i++){document.write('&#'+_tyjsdf[_i]+';');}
                document.write('">');
                for(_i=0;_i<_qplmks.length;_i++){document.write('&#'+_qplmks[_i]+';');}
                document.write('</a>');
                </script>""" % (re.sub(r',$', '', emailArrayContent),
                                re.sub(r',$', '', textArrayContent))
    
    return mark_safe(result)
Esempio n. 7
0
    def render(self, name, value, attrs=None):
        """Render the custom widget."""
        substitutions = {
            'input_text': self.input_text,
            'clear_template': '',
            'clear_checkbox_label': self.clear_checkbox_label,
            }
        template = '%(input)s'
        substitutions['input'] = Input.render(self, name, value, attrs)

        if value and hasattr(value, "url"):
            template = ('%(initial)s %(clear_template)s<br />%(input_text)s: '
                        '%(input)s')
            substitutions['initial'] = (
                '<img class="img-responsive" src="%s" alt="%s"/>' % (
                    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)
Esempio n. 8
0
    def render_data(self, state, review_request):
        summary = conditional_escape(review_request.summary)
        labels = {}

        if review_request.submitter_id == state.datagrid.request.user.id:
            if review_request.draft_summary is not None:
                summary = conditional_escape(review_request.draft_summary)
                labels.update({_('Draft'): 'label-draft'})
            elif (not review_request.public and
                  review_request.status == ReviewRequest.PENDING_REVIEW):
                labels.update({_('Draft'): 'label-draft'})

        if review_request.status == ReviewRequest.SUBMITTED:
            labels.update({_('Submitted'): 'label-submitted'})
        elif review_request.status == ReviewRequest.DISCARDED:
            labels.update({_('Discarded'): 'label-discarded'})

        display_data = ''

        if not summary:
            summary = '&nbsp;<i>%s</i>' % _('No Summary')

        for label in labels:
            display_data += '<span class="%s">[%s] </span>' % (
                labels[label], label)
        display_data += summary
        return display_data
Esempio n. 9
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
            if self.preview:
                substitutions['initial'] = (u'<a href="{0}">{1}</a><br /><br />\
                <a href="{0}" target="_blank"><img src="{0}" alt="" width="{2}" /></a><br /><br />'.format
                    (escape(value.url),'...'+escape(force_unicode(value))[-self.url_length:],
                     self.image_width))
            else:
                substitutions['initial'] = (u'<a href="{0}">{1}</a>'.format
                    (escape(value.url),'...'+escape(force_unicode(value))[-self.url_length:]))
            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)
Esempio n. 10
0
    def render(self, name, value, attrs=None):
        '''Same render method as ClearableFileInput has except that it wraps
        displayed file name with os.path.basename for nicer output.'''
        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 value and hasattr(value, "url"):
            template = self.template_with_initial
            substitutions['initial'] = format_html(u'<a href="{0}">{1}</a>',
                                                   value.url,
                                                   basename(force_text(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)
Esempio n. 11
0
def syntaxhilight(value, arg="diff", autoescape=None):
    """
    Returns a syntax-hilighted version of Code;
    requires code/language arguments
    """

    if autoescape:
        value = conditional_escape(value)
        arg = conditional_escape(arg)

    if colorize:
        try:
            output = (
                u_str('<style  type="text/css">')
                + smart_unicode(HtmlFormatter().get_style_defs(".highlight"))
                + u_str("</style>")
            )

            lexer = get_lexer_by_name(arg)
            output += highlight(value, lexer, HtmlFormatter())
            return mark_safe(output)
        except:
            return value
    else:
        return mark_safe(
            u_str('<div class="note-box">Tip: Install pygments ' "for highlighting</div><pre>%s</pre>") % value
        )
Esempio n. 12
0
    def __str__(self):
        s = ''

        for name, field in self.fields.items():
            bf = self[name]

            if isinstance(field.widget, CheckboxInput):
                s += '<div class="checkbox{}">'.format(' has-error' if bf.errors else '')
                s += '<label>'
                s += str(bf)

                if bf.label:
                    s += ' ' + force_text(bf.label)
                if bf.errors:
                    s += '<p class="help-block">{}</p>'.format(
                        ', '.join([conditional_escape(error) for error in bf.errors]))

                s += '</label>'
            else:
                s += '<div class="form-group{}">'.format(' has-error' if bf.errors else '')

                if bf.label:
                    label = conditional_escape(force_text(bf.label))
                    s += force_text(bf.label_tag(label) or '')

                s += str(bf)

                if bf.errors:
                    s += '<p class="help-block">{}</p>'.format(
                        ', '.join([conditional_escape(error) for error in bf.errors]))

                s += '</div>'

        return mark_safe(s)
Esempio n. 13
0
def wiki_links(text, group=None):
    """Replaces CamelCase words to wiki-links."""
    from BeautifulSoup import BeautifulSoup

    autoescape = False
    safe_input = isinstance(text, SafeData)
    conditional_escape(text)
    soup = BeautifulSoup(text)

    for url in soup.findAll(text=wikiword_link):
        if url.parent.name == 'a':
            continue
        new_str = wikiword_link.sub(curry(_re_callback, inside=False, group=group), url)
        url.replaceWith(BeautifulSoup(new_str))

    soup = BeautifulSoup(str(soup))  # Fixed for bug in some versions of BS
    for a in soup.findAll('a'):
        url = a.get('href')
        if not url:
            continue
        new_str = wikiword_link_href.sub(curry(_re_callback, inside=True, group=group), url)
        if new_str != url:
            a['href'] = new_str

    result = force_unicode(soup)
    if safe_input:
        result = mark_safe(result)
    elif autoescape:
        result = escape(result)
    return result
Esempio n. 14
0
    def test_render(self):
        band = models.Band.objects.create(name='Linkin Park')

        m1 = models.Member.objects.create(name='Chester')
        m2 = models.Member.objects.create(name='Mike')
        band.members.add(m1, m2)
        rel = models.Band._meta.get_field('members').rel

        w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site)
        self.assertHTMLEqual(
            conditional_escape(w.render('test', [m1.pk, m2.pk], attrs={})),
            '<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField" /><a href="/widget_admin/admin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="/static/admin/img/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % dict(admin_static_prefix(), m1pk=m1.pk, m2pk=m2.pk)
        )

        self.assertHTMLEqual(
            conditional_escape(w.render('test', [m1.pk])),
            '<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField" /><a href="/widget_admin/admin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % dict(admin_static_prefix(), m1pk=m1.pk)
        )

        self.assertEqual(w._has_changed(None, None), False)
        self.assertEqual(w._has_changed([], None), False)
        self.assertEqual(w._has_changed(None, [u'1']), True)
        self.assertEqual(w._has_changed([1, 2], [u'1', u'2']), False)
        self.assertEqual(w._has_changed([1, 2], [u'1']), True)
        self.assertEqual(w._has_changed([1, 2], [u'1', u'3']), True)
Esempio n. 15
0
def display_for_field(value, field):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon
    from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # 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_CHANGELIST_VALUE
    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.FloatField):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return mark_safe('<a href="%s">%s</a>' % (
            conditional_escape(value.url),
            conditional_escape(value),
        ))
    else:
        return smart_text(value)
Esempio n. 16
0
def render_mail_as_js(dom_id, email, text=None, autoescape=None):
    text = text or email
    if autoescape:
        email = conditional_escape(email)
        text = conditional_escape(text)

    emailArrayContent = ''
    textArrayContent = ''
    r = lambda c: '"' + str(ord(c)) + '",'

    for c in email: emailArrayContent += r(c)
    for c in text: textArrayContent += r(c)

    result = """
             var _tyjsdf=[%s], _qplmks=[%s];
             var content='<a href="&#x6d;&#97;&#105;&#x6c;&#000116;&#111;&#x3a;';
             for(_i=0;_i<_tyjsdf.length;_i++){content+=('&#'+_tyjsdf[_i]+';');}
             content+='">';
             for(_i=0;_i<_qplmks.length;_i++){content+=('&#'+_qplmks[_i]+';');}
             content+='</a>';
             document.getElementById('%s').innerHTML=content;
             """ % (re.sub(r',$', '', emailArrayContent),
                    re.sub(r',$', '', textArrayContent),
                    dom_id)
    result = ''.join(result.replace('  ', '').splitlines())
    return mark_safe(result)
Esempio n. 17
0
    def render(self, name, value, size=(100, 100), attrs=None):
        substitutions = {
            'initial_text': self.initial_text,
            'preview': self.get_preview(value, size),
            'input_text': self.input_text,
            'clear_template': u'',
            'clear_checkbox_label': self.clear_checkbox_label,
        }
        template = '%(input)s'
        substitutions['input'] = super(PreviewImageFileInput, self).\
            render(name, value, attrs)

        if value and hasattr(value, "url"):
            template = self.template_with_initial
            substitutions['initial'] = format_html(
                self.url_markup_template,
                value.url,
                force_text(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'] = forms.CheckboxInput().render(
                    checkbox_name,
                    False,
                    attrs={'id': checkbox_id}
                )
                substitutions['clear_template'] =\
                    self.template_with_clear % substitutions

        return mark_safe(template % substitutions)
 def render(self, name, value, attrs=None):
     if value is None:
         value = ""
     input_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
     if value != "":
         # Only add the 'value' attribute if a value is non-empty.
         input_attrs["value"] = force_text(self._format_value(value))
     input_attrs = dict([(key, conditional_escape(val)) for key, val in input_attrs.items()])  # python2.6 compatible
     if not self.picker_id:
         self.picker_id = (input_attrs.get("id", "") + "_pickers").replace(" ", "_")
     self.div_attrs["id"] = self.picker_id
     picker_id = conditional_escape(self.picker_id)
     div_attrs = dict(
         [(key, conditional_escape(val)) for key, val in self.div_attrs.items()]
     )  # python2.6 compatible
     icon_attrs = dict([(key, conditional_escape(val)) for key, val in self.icon_attrs.items()])
     html = self.html_template % dict(
         div_attrs=flatatt(div_attrs), input_attrs=flatatt(input_attrs), icon_attrs=flatatt(icon_attrs)
     )
     if self.options != False:
         lang = translation.get_language()
         self.options["locale"] = lang_map.get(lang, lang)
         js = self.js_template % dict(picker_id=picker_id, options=json.dumps(self.options or {}))
     else:
         js = ""
     return mark_safe(force_text(html + js))
Esempio n. 19
0
def xml_parser(node, parsed_xml=""):
    """
    Analyze a xml node and replace allowed tags by html tags. Any other text will be escaped.
    :param node: a xml node from a xml tree generated by lxml.
    :param parsed_xml: For a recursive use, when there is a string yet parsed to insert between tags.
    :return : html_result, a html string
    :rtype : str
    """

    # If parsed_xml is empty, we get the tag text and tail (see lxml documentation for more information)
    if not parsed_xml:
        # text is the text between the right and left tag
        if node.text is None:
            text = ""
        else:
            text = conditional_escape(node.text)
        # tail is the text after the tag , e.g. "<bold>Hello</bold> Michel" (" Michel" is the tail)
        if node.tail is None:
            tail = ""
        else:
            tail = conditional_escape(node.tail)
    else:
        text = parsed_xml
        tail = ""

    # Tag recognition and substitution
    try:
        # Allowed tag are saved in a dictionary outside of the function for external use
        tag_dictionary = get_allowed_tags()
        html_result = tag_dictionary[node.tag][0] + text + tag_dictionary[node.tag][1] + tail
    except KeyError:
        # If the tag does not exist in the dictionary, a xml string is generated from the node
        html_result = conditional_escape(etree.tostring(node))

    return html_result
Esempio n. 20
0
def emailprotect(email):
    if u'@' not in email:
        return email
    local_part, domain = email.split(u'@', 1)
    xhtml = u'{0}<span class="at-sign"></span>{1}'.format(
            conditional_escape(local_part), conditional_escape(domain))
    return mark_safe(xhtml)
Esempio n. 21
0
File: api2.py Progetto: antbell/hue
def _massage_doc_for_json(document, user, with_data=False):

  massaged_doc = {
    'id': document.id,
    'uuid': document.uuid,

    'owner': document.owner.username,
    'type': html.conditional_escape(document.type),
    'name': html.conditional_escape(document.name),
    'description': html.conditional_escape(document.description),

    'isMine': document.owner == user,
    'lastModified': document.last_modified.strftime("%x %X"),
    'lastModifiedInMillis': time.mktime(document.last_modified.timetuple()),
    'version': document.version,
    'is_history': document.is_history,

    # tags
    # dependencies
  }

  if with_data:
    massaged_doc['data'] = document.data_dict

  return massaged_doc
Esempio n. 22
0
 def label_from_instance(self, obj):
     return mark_safe(u"<span class='val role_desc'>%s</span>" \
         u"<span class='description role_desc'>%s</span>" % (
             conditional_escape(obj.name),
             conditional_escape(obj.description)
         )
     )
 def render(self, name, value, attrs=None):
     if value is None:
         value = ''
     input_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
     if value != '':
         # Only add the 'value' attribute if a value is non-empty.
         input_attrs['value'] = force_text(self._format_value(value))
     input_attrs = dict([(key, conditional_escape(val)) for key, val in input_attrs.items()]) # python2.6 compatible
     if not self.picker_id:
         self.picker_id = input_attrs.get('id', '') + '_picker'
     self.div_attrs['id'] = self.picker_id
     picker_id = conditional_escape(self.picker_id)
     div_attrs = dict([(key, conditional_escape(val)) for key, val in self.div_attrs.items()]) # python2.6 compatible
     html = '''
             <div%(div_attrs)s>
                 <input%(input_attrs)s/>
                 <span class="input-group-addon">
                     <span class="glyphicon glyphicon-calendar"></span>
                 </span>
             </div>''' % dict(div_attrs=flatatt(div_attrs),
                              input_attrs=flatatt(input_attrs))
     if self.options == False:
         js = ''
     else:
         js = '''
             <script>
                 $(function() {
                     $("#%(picker_id)s").datetimepicker(%(options)s);
                 });
             </script>''' % dict(picker_id=picker_id, 
                                 options=json.dumps(self.options or {}))
     return mark_safe(force_text(html + js))
Esempio n. 24
0
File: forms.py Progetto: boar/boar
    def render(self, name, value, attrs=None, choices=()):
        mailing_lists = dict((ml.id, ml) for ml in MailingList.objects.all())
        if value is None:
            value = []
        has_id = attrs and 'id' in attrs
        final_attrs = self.build_attrs(attrs, name=name)
        output = [u'<ol>']
        # Normalize to strings
        str_values = set([force_unicode(v) for v in value])
        for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
            # If an ID attribute was given, add a numeric index as a suffix,
            # so that the checkboxes don't all have the same ID attribute.
            if has_id:
                final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
                label_for = u' for="%s"' % final_attrs['id']
            else:
                label_for = ''
 
            cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
            ml = mailing_lists[option_value]
            output.append(u'<li>%s <div class="label"><label%s>%s</label> <p>%s</p></div></li>' % (
                cb.render(name, force_unicode(option_value)),
                label_for,
                conditional_escape(typogrify(ml.name)),
                conditional_escape(typogrify(ml.description)),
            ))
        output.append(u'</ol>')
        return mark_safe(u'\n'.join(output))
Esempio n. 25
0
 def render(self, name, value, attrs=None):
     if not value:
         value = ''
         title = ''
         noliaison = 'inline'
         deselect = 'none'
     else:
         liaison = LiaisonStatement.objects.get(pk=value)
         title = liaison.title
         if not title:
             attachments = liaison.attachments.all()
             if attachments:
                 title = attachments[0].title
             else:
                 title = 'Liaison #%s' % liaison.pk
         noliaison = 'none'
         deselect = 'inline'
     html = u'<span class="noRelated" style="display: %s;">No liaison selected</span>' % conditional_escape(noliaison)
     html += u'<span class="relatedLiaisonWidgetTitle">%s</span>' % conditional_escape(title)
     html += u'<input type="hidden" name="%s" class="relatedLiaisonWidgetValue" value="%s" /> ' % (conditional_escape(name), conditional_escape(value))
     html += u'<span style="display: none;" class="listURL">%s</span> ' % urlreverse('ajax_liaison_list')
     html += u'<div style="display: none;" class="relatedLiaisonWidgetDialog" id="related-dialog" title="Select a liaison"></div> '
     html += '<input type="button" id="id_%s" value="Select liaison" /> ' % conditional_escape(name)
     html += '<input type="button" style="display: %s;" id="id_no_%s" value="Deselect liaison" />' % (conditional_escape(deselect), conditional_escape(name))
     return mark_safe(html)
Esempio n. 26
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,
            'pretty_input_start': self.pretty_input_start,
            'pretty_input_end': self.pretty_input_end,
        }
        template = u'%(pretty_input_start)s%(input)s%(pretty_input_end)s'
        substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)

        if value and hasattr(value, "url"):
            template = self.template_with_initial
            substitutions['initial'] = (u'<audio src="%s" controls></audio>'
                                        % (escape(value.url),))
            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)
def user_display(user):
    try:
        # Use django-user-accounts display function if available
        from account.utils import user_display as account_user_display
        return conditional_escape(account_user_display(user))
    except ImportError:
        return conditional_escape(user.username)
Esempio n. 28
0
    def render_data(self, review_request):
        summary = conditional_escape(review_request.summary)
        labels = {}

        if not summary:
            summary = "&nbsp;<i>%s</i>" % _("No Summary")

        if review_request.submitter_id == self.datagrid.request.user.id:

            if review_request.draft_summary is not None:
                summary = conditional_escape(review_request.draft_summary)
                labels.update({_("Draft"): "label-draft"})
            elif not review_request.public and review_request.status == ReviewRequest.PENDING_REVIEW:
                labels.update({_("Draft"): "label-draft"})

        if review_request.status == ReviewRequest.SUBMITTED:
            labels.update({_("Submitted"): "label-submitted"})
        elif review_request.status == ReviewRequest.DISCARDED:
            labels.update({_("Discarded"): "label-discarded"})

        display_data = ""

        for label in labels:
            display_data += u'<span class="%s">[%s] </span>' % (labels[label], label)
        display_data += u"%s" % summary
        return display_data
Esempio n. 29
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 = (
            '<div class="select_file"> '
            '  <div class="input-group"> '
            '    <span class="input-group-btn"> '
            '      <span class="btn btn-primary btn-file form-control"> '
            '        %(input_text)s %(input)s '
            '      </span> '
            '    </span> '
            '    <input type="text" class="form-control" readonly="readonly"> '
            '  </div> '
            '</div> '
        )

        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)
Esempio n. 30
0
 def render(self, name, value, attrs=None, choices=()):
     if value is None: value = []
     has_id = attrs and 'id' in attrs
     final_attrs = self.build_attrs(attrs, name=name)
     output = [u'<table class="existing_objects_list">']
     str_values = set([force_unicode(v) for v in value])  # Normalize to strings.
     output.append(u'<tr><th>%s</th>' % conditional_escape(self.checkbox_label))
     for label, attr in self.item_attrs:
         output.append(u'<th>%s</th>' % conditional_escape(label))
     output.append(u'</tr>')
     for i, (option_value, item) in enumerate(self.choices):
         # If an ID attribute was given, add a numeric index as a suffix,
         # so that the checkboxes don't all have the same ID attribute.
         if has_id:
             final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
         cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
         option_value = force_unicode(option_value)
         rendered_cb = cb.render(name, option_value)
         output.append(u'<tr><td>%s</td>' % rendered_cb)
         for label, attr in self.item_attrs:
             if callable(attr):
                 content = attr(item)
             elif callable(getattr(item, attr)):
                 content = getattr(item, attr)()
             else:
                 content = getattr(item, attr)
             output.append(u'<td>%s</td>' % conditional_escape(content))
         output.append(u'</tr>')
     output.append(u'</table>')
     return mark_safe(u'\n'.join(output))
Esempio n. 31
0
 def test_conditional_escape(self):
     s = '<h1>interop</h1>'
     self.assertEqual(conditional_escape(s), '&lt;h1&gt;interop&lt;/h1&gt;')
     self.assertEqual(conditional_escape(mark_safe(s)), s)
     self.assertEqual(conditional_escape(lazystr(mark_safe(s))), s)
Esempio n. 32
0
    def _html_output(self, normal_row, error_row, row_ender, help_text_html,
                     errors_on_separate_row):
        "Output HTML. Used by as_table(), as_ul(), as_p()."
        top_errors = self.non_field_errors(
        )  # Errors that should be displayed above all fields.
        output, hidden_fields = [], []

        for name, field in self.fields.items():
            html_class_attr = ''
            bf = self[name]
            # Escape and cache in local variable.
            bf_errors = self.error_class(
                [conditional_escape(error) for error in bf.errors])
            if bf.is_hidden:
                if bf_errors:
                    top_errors.extend([
                        _('(Hidden field %(name)s) %(error)s') % {
                            'name': name,
                            'error': str(e)
                        } for e in bf_errors
                    ])
                hidden_fields.append(str(bf))
            else:
                # Create a 'class="..."' attribute if the row should have any
                # CSS classes applied.
                css_classes = bf.css_classes()
                if css_classes:
                    has_errors = ''

                    if bf_errors or (self.errors and '__all__' in self.errors):
                        has_errors = self.error_css_class

                    html_class_attr = u'class="%s %s"' % (css_classes,
                                                          has_errors)

                if errors_on_separate_row and bf_errors:
                    output.append(error_row % str(bf_errors))

                if bf.label:
                    label = conditional_escape(bf.label)
                    #label = bf.label_tag(label) or ''
                    label = u'<label class="control-label" for="id_%s"> %s </label>' % (
                        label.lower(), label)
                else:
                    label = ''

                if field.help_text:
                    help_text = help_text_html % field.help_text
                else:
                    help_text = ''

                output.append(
                    normal_row % {
                        'errors': bf_errors,
                        'label': label,
                        'field': bf,
                        'help_text': help_text,
                        'html_class_attr': html_class_attr,
                        'css_classes': css_classes,
                        'field_name': bf.html_name,
                    })

        if top_errors:
            output.insert(0, error_row % top_errors)

        if hidden_fields:  # Insert any hidden fields in the last row.
            str_hidden = ''.join(hidden_fields)
            if output:
                last_row = output[-1]
                # Chop off the trailing row_ender (e.g. '</td></tr>') and
                # insert the hidden fields.
                if not last_row.endswith(row_ender):
                    # This can happen in the as_p() case (and possibly others
                    # that users write): if there are only top errors, we may
                    # not be able to conscript the last row for our purposes,
                    # so insert a new, empty row.
                    last_row = (normal_row % {
                        'errors': '',
                        'label': '',
                        'field': '',
                        'help_text': '',
                        'html_class_attr': html_class_attr,
                        'css_classes': '',
                        'field_name': '',
                    })
                    output.append(last_row)
                output[
                    -1] = last_row[:-len(row_ender)] + str_hidden + row_ender
            else:
                # If there aren't any rows in the output, just append the
                # hidden fields.
                output.append(str_hidden)
        return mark_safe('\n'.join(output))
Esempio n. 33
0
def object_html_output(self, ODM=None):
    ''' Helper function for outputting HTML formatted objects (intended for DetailViews).

        Used by as_table(), as_ul(), as_p(), as_br().

        an object display mode (ODM) can be specified to override the one in self.format if desired
        as this is what as_table etc do (providing compatible entry points with the Django Generic Forms).

        self is an instance of DetailViewExtended or DeleteViewExtended (or any view that wants HTML
        rendering of an object.

        Relies on:
             self.fields
             self.fields_bucketed

        which are attributes created by collect_rich_object_fields which should have run earlier
        when the view's get_object() method was called. When the object is delivered the view is
        updated with these (and other) attributes.

        Notably, each field in self.fields and variants carries a "value" attribvute which is what
        we try to render in HTML here. We rely on privacy constraints having already been applied
        by collect_rich_object_fields and that values affected by provacy are suitably masked
        (overwritten).
    '''
    # TODO: This should really support CSS classes like BaseForm._html_output, so that a class can be specified

    ODF = self.format
    if not ODM is None:
        ODF.mode.object = ODM

    # Define the standard HTML strings for supported formats
    if ODF.mode.object == odm.as_table:
        header_row = "<tr><th valign='top'>{header:s} {line1:s}</th><td>{line2:s}</td></tr>"
        normal_row = "<tr><th valign='top'>{label:s}</th><td>{value:s}{help_text:s}</td></tr>"
        help_text_html = '<br /><span class="helptext">%s</span>'
    elif ODF.mode.object == odm.as_ul:
        header_row = "<li><b>{header:s}</b> {line1:s}</li>"
        normal_row = "<li><b>{label:s}:</b> {value:s}{help_text:s}</li>"
        help_text_html = ' <span class="helptext">%s</span>'
    elif ODF.mode.object == odm.as_p:
        header_row = "<p><b>{header:s}</b> {line1:s}</p>"
        normal_row = "<p><b>{label:s}:</b> {value:s}{help_text:s}</p>"
        help_text_html = ' <span class="helptext">%s</span>'
    elif ODF.mode.object == odm.as_br:
        header_row = "<b>{header:s}</b> {line1:s}<br>"
        normal_row = '<b>{label:s}:</b> {value:s}{help_text:s}<br>'
        help_text_html = ' <span class="helptext">%s</span>'
    else:
        raise ValueError(
            "Internal Error: format must always contain one of the object layout modes."
        )

    # Collect output lines in a list
    output = []

    for bucket in self.fields_bucketed:
        # Define a label for this bucket
        bucket_label = ('Internal fields' if bucket == odf.internal else
                        'Related fields' if bucket == odf.related else
                        'Properties' if bucket == odf.properties else 'Methods'
                        if bucket == odf.methods else 'Summaries' if bucket ==
                        odf.summaries else 'Standard fields' if bucket == odf.
                        model and ODF.flags & odf.header else None if bucket ==
                        odf.model else 'Unknown ... [internal error]')

        # Output a separator for this bucket if needed
        # Will depend on the object display mode
        if bucket_label and (ODF.flags
                             & odf.separated) and self.fields_bucketed[bucket]:
            label = bucket_label if ODF.flags & odf.header else ""

            if ODF.flags & odf.line:
                if ODF.mode.object == odm.as_table:
                    line = "<hr style='display:inline-block; width:60%;' />"
                else:
                    label_width = int(
                        round(
                            getApproximateArialStringWidth(bucket_label) /
                            getApproximateArialStringWidth('M')))
                    line = "&mdash;" * (ODF.mode.line_width - label_width - 1)

            if ODF.mode.object == odm.as_table:
                label_format = '<span style="float:left;">{}</span>'
            else:
                label_format = '{}'

            row = header_row.format(header=label_format.format(label),
                                    line1=line,
                                    line2=line)

            if ODF.mode.object == odm.as_ul:
                row_format = '{}<ul>'
            elif ODF.mode.object == odm.as_br:
                row_format = '{}</p><p style="padding-left:' + str(
                    ODF.mode.indent) + 'ch">'
            else:
                row_format = '{}'

            output.append(row_format.format(row))

        # Output a the fields in this bucket
        for name in self.fields_bucketed[bucket]:
            field = self.fields_bucketed[bucket][name]
            value = field.value

            if hasattr(field, 'label') and field.label:
                label = conditional_escape(force_text(field.label))
            else:
                label = ''

            # self.format specifies how we'll render the field, i.e. build our row.
            #
            # normal_row has been specified above in accord with the as_ format specified.
            #
            # The object display mode defines where the value lands.
            # The long list display mode defines how a list value is rendered in that spot
            # short lists are rendered as CSV values in situ
            br_fix = False

            if field.is_list:
                proposed_value = value if value == NONE else ", ".join(value)

                is_short = (len(proposed_value) <= ODF.mode.char_limit
                            ) and not ("\n" in proposed_value)

                if is_short:
                    value = proposed_value
                else:
                    # as_br is special as many fields are in one P with BRs between them. This P cannot contain
                    # block elements so there is only one sensible rendering (which is to conserve the intended
                    # paragraph and just put long list values one one BR terminated line each, indenting with
                    # a SPAN that is permitted in a P.
                    if ODF.mode.object == odm.as_br:
                        value = indentVAL("<br>".join(value), ODF.mode.indent)
                        br_fix = ODF.mode.object == odm.as_br
                    else:
                        if ODF.mode.list_values == odm.as_table:
                            strindent = ''
                            if ODF.mode.object == odm.as_p and ODF.mode.indent > 0:
                                strindent = " style='padding-left: {}ch'".format(
                                    ODF.mode.indent)
                            value = "<table{}><tr><td>".format(
                                strindent) + "</td></tr><tr><td>".join(
                                    value) + "</td></tr></table>"
                        elif ODF.mode.list_values == odm.as_ul:
                            strindent = ''
                            if ODF.mode.object == odm.as_p and ODF.mode.indent > 0:
                                strindent = " style='padding-left: {}ch'".format(
                                    ODF.mode.indent)
                            value = "<ul{}><li>".format(
                                strindent) + "</li><li>".join(
                                    value) + "</li></ul>"
                        elif ODF.mode.list_values == odm.as_p:
                            strindent = ''
                            if ODF.mode.object == odm.as_p and ODF.mode.indent > 0:
                                strindent = " style='padding-left: {}ch'".format(
                                    ODF.mode.indent)
                            value = "<p{}>".format(
                                strindent) + "</p><p{}>".format(
                                    strindent).join(value) + "</p>"
                        elif ODF.mode.list_values == odm.as_br:
                            strindent = ''
                            if ODF.mode.object == odm.as_p and ODF.mode.indent > 0:
                                strindent = " style='padding-left: {}ch'".format(
                                    ODF.mode.indent)
                            value = "<p{}>".format(strindent) + "<br>".join(
                                value) + "</p>"
                        else:
                            raise ValueError(
                                "Internal Error: self.format must always contain one of the list layouts."
                            )
            else:
                proposed_value = value
                is_short = (len(proposed_value) <= ODF.mode.char_limit
                            ) and not ("\n" in proposed_value)

                if is_short:
                    value = proposed_value
                else:
                    indent = ODF.mode.indent if ODF.mode.object != odm.as_table else 0
                    if isPRE(value):
                        value = emulatePRE(value, indent)
                        br_fix = ODF.mode.object == odm.as_br
                    else:
                        value = indentVAL(value, indent)

            if hasattr(field, 'help_text') and field.help_text:
                help_text = help_text_html % force_text(field.help_text)
            else:
                help_text = ''

            # Indent the label only for tables with headed separators.
            # The other object display modes render best without an indent on the label.
            if ODF.mode.object == odm.as_table and ODF.flags & odf.separated and ODF.flags & odf.header:
                label_format = indentVAL("{}", ODF.mode.indent)
            else:
                label_format = '{}'

            html_label = label_format.format(force_text(label))
            html_value = six.text_type(value)
            html_help = help_text

            if settings.DEBUG:
                if field.is_list:
                    html_label = "<span style='color:red;'>" + html_label + "</span>"
                if is_short:
                    html_value = "<span style='color:red;'>" + html_value + "</span>"

            row = normal_row.format(label=html_label,
                                    value=html_value,
                                    help_text=html_help)

            # FIXME: This works. But we should consider a cleaner way to put the br inside
            # the span that goes round the whole list in as_br mode. The fix needs a consideration
            # of normal_row and indentVAL() the later wrapping in a SPAN the former terminating with
            # BR at present. And in that order an unwanted blank line appears. If we swap them and
            # bring the BR inside of the SPAN the render is cleaner.
            if br_fix:
                row = re.sub(r"</span><br>$", r"<br></span>", row, 0,
                             ref.IGNORECASE)

            # Finally, indent the whole "field: value" row if needed
            if ODF.mode.object == odm.as_p and ODF.flags & odf.separated and ODF.flags & odf.header:
                row_format = indentVAL("{}", ODF.mode.indent)
            else:
                row_format = '{}'

            output.append(row_format.format(row))

        # End the UL sublist (the one with label: value pairs on it, being sub to the header/separator list) if needed
        if bucket_label and (ODF.flags
                             & odf.separated) and self.fields_bucketed[bucket]:
            if ODF.mode.object == odm.as_ul:
                output.append('</ul>')
            elif ODF.mode.object == odm.as_br:
                output.append('</p><p>')

    return mark_safe('\n'.join(output))
Esempio n. 34
0
 def status_display(self, instance):
     return '<span class="subm_admin subm_status subm_%s">%s</span>' % \
             (instance.status, conditional_escape(force_unicode(
                 instance.get_status_display())))
Esempio n. 35
0
 def get_url_anchor_tag(self):
     return mark_safe('<a href="{url}">{name}</a>'.format(
         url=self.get_absolute_url(),
         name=conditional_escape(self.name)))
Esempio n. 36
0
 def __html__(self):
     return mark_safe(avoid_wrapping(conditional_escape(str(self))))
Esempio n. 37
0
 def format_html(format_string, *args, **kwargs):
     args_safe = map(conditional_escape, args)
     kwargs_safe = dict((k, conditional_escape(v)) for (k, v) in kwargs.items())
     return mark_safe(format_string.format(*args_safe, **kwargs_safe))
Esempio n. 38
0
 def _format_value(self, value):
     return conditional_escape(force_text(value))
Esempio n. 39
0
def get_standpunt_tekst(text, autoescape=True):
    if autoescape: text = conditional_escape(text)
    text = "\n".join([s.strip() for s in text.strip().split("\n")])
    pieces = [render_tekst(s) for s in text.split("\n\n")]
    result = "".join([p for p in pieces])
    return mark_safe(result)
Esempio n. 40
0
def replace_page_param(query, page_number, page_key='p'):
    """
    Replaces ``page_key`` from query string with ``page_number``.
    """
    return conditional_escape(
        replace_page_in_query(query, page_number, page_key))
Esempio n. 41
0
def wrap_anonymous_output(html):
    return mark_safe('<div class="cp-editable-placeholder">' \
           '{html}' \
           '</div>\n'.format(
        html=conditional_escape(html),
    ))
Esempio n. 42
0
    def _html_output(self, normal_row, error_row, row_ender, help_text_html,
                     errors_on_separate_row):
        "Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()."
        top_errors = self.non_field_errors(
        )  # Errors that should be displayed above all fields.
        output, hidden_fields = [], []

        for name, field in self.fields.items():
            html_class_attr = ''
            bf = self[name]
            # Escape and cache in local variable.
            bf_errors = self.error_class(
                [conditional_escape(error) for error in bf.errors])
            if bf.is_hidden:
                if bf_errors:
                    top_errors.extend([
                        _('(Hidden field %(name)s) %(error)s') % {
                            'name': name,
                            'error': force_text(e)
                        } for e in bf_errors
                    ])
                hidden_fields.append(six.text_type(bf))
            else:
                # Create a 'class="..."' atribute if the row should have any
                # CSS classes applied.
                css_classes = bf.css_classes()
                if css_classes:
                    html_class_attr = ' class="%s"' % css_classes

                if errors_on_separate_row and bf_errors:
                    output.append(error_row % force_text(bf_errors))

                if bf.label:
                    label = conditional_escape(force_text(bf.label))
                    # Only add the suffix if the label does not end in
                    # punctuation.
                    if self.label_suffix:
                        if label[-1] not in ':?.!':
                            label = format_html('{0}{1}', label,
                                                self.label_suffix)
                    label = bf.label_tag(label) or ''
                else:
                    label = ''

                if field.help_text:
                    help_text = help_text_html % force_text(field.help_text)
                else:
                    help_text = ''

                output.append(
                    normal_row % {
                        'errors': force_text(bf_errors),
                        'label': force_text(label),
                        'field': six.text_type(bf),
                        'help_text': help_text,
                        'html_class_attr': html_class_attr
                    })

        if top_errors:
            output.insert(0, error_row % force_text(top_errors))

        if hidden_fields:  # Insert any hidden fields in the last row.
            str_hidden = ''.join(hidden_fields)
            if output:
                last_row = output[-1]
                # Chop off the trailing row_ender (e.g. '</td></tr>') and
                # insert the hidden fields.
                if not last_row.endswith(row_ender):
                    # This can happen in the as_p() case (and possibly others
                    # that users write): if there are only top errors, we may
                    # not be able to conscript the last row for our purposes,
                    # so insert a new, empty row.
                    last_row = (normal_row % {
                        'errors': '',
                        'label': '',
                        'field': '',
                        'help_text': '',
                        'html_class_attr': html_class_attr
                    })
                    output.append(last_row)
                output[
                    -1] = last_row[:-len(row_ender)] + str_hidden + row_ender
            else:
                # If there aren't any rows in the output, just append the
                # hidden fields.
                output.append(str_hidden)
        return mark_safe('\n'.join(output))
Esempio n. 43
0
    def _html_output(self,
                     normal_row,
                     error_row,
                     row_ender,
                     help_text_html,
                     errors_on_separate_row,
                     flag=False):
        "Output HTML. Used by as_table(), as_ul(), as_p()."
        top_errors = self.non_field_errors(
        )  # Errors that should be displayed above all fields.
        output, hidden_fields = [], []

        for name, field in self.fields.items():
            html_class_attr = ''
            bf = self[name]
            if flag:
                bf.field.widget.flag = True
            bf_errors = self.error_class(bf.errors)
            if bf.is_hidden:
                if bf_errors:
                    top_errors.extend([
                        _('(Hidden field %(name)s) %(error)s') % {
                            'name': name,
                            'error': str(e)
                        } for e in bf_errors
                    ])
                hidden_fields.append(str(bf))
            else:
                # Create a 'class="..."' attribute if the row should have any
                # CSS classes applied.
                css_classes = bf.css_classes()
                if css_classes:
                    html_class_attr = ' class="%s"' % css_classes

                if errors_on_separate_row and bf_errors:
                    output.append(error_row % str(bf_errors))

                if bf.label:
                    label = conditional_escape(bf.label)
                    label = bf.label_tag(label) or ''
                else:
                    label = ''

                if field.help_text:
                    help_text = help_text_html % field.help_text
                else:
                    help_text = ''

                output.append(
                    normal_row % {
                        'errors': bf_errors,
                        'label': label,
                        'field': bf,
                        'help_text': help_text,
                        'html_class_attr': html_class_attr,
                        'css_classes': css_classes,
                        'field_name': bf.html_name,
                    })

        if top_errors:
            output.insert(0, error_row % top_errors)
        if hidden_fields:  # Insert any hidden fields in the last row.
            str_hidden = ''.join(hidden_fields)
            if output:
                last_row = output[-1]
                # Chop off the trailing row_ender (e.g. '</td></tr>') and
                # insert the hidden fields.
                if not last_row.endswith(row_ender):
                    # This can happen in the as_p() case (and possibly others
                    # that users write): if there are only top errors, we may
                    # not be able to conscript the last row for our purposes,
                    # so insert a new, empty row.
                    last_row = (normal_row % {
                        'errors': '',
                        'label': '',
                        'field': '',
                        'help_text': '',
                        'html_class_attr': html_class_attr,
                        'css_classes': '',
                        'field_name': '',
                    })
                    output.append(last_row)
                output[
                    -1] = last_row[:-len(row_ender)] + str_hidden + row_ender
            else:
                # If there aren't any rows in the output, just append the
                # hidden fields.
                output.append(str_hidden)
        if flag:
            app_id = "x" + str(uuid.uuid4())[0:5]
            output.insert(0, "<div id='%s'>" % app_id)
            output.append('</div>')
            output.append(self.get_vue_app_js(app_id))
        return mark_safe('\n'.join(output))
Esempio n. 44
0
def render_tekst_filter(line, autoescape=True):
    if autoescape: line = conditional_escape(line)
    return mark_safe(render_tekst(line))
Esempio n. 45
0
 def test_render_idn(self):
     w = widgets.AdminURLFieldWidget()
     self.assertHTMLEqual(
         conditional_escape(w.render('test', 'http://example-äüö.com')),
         '<p class="url">Currently:<a href="http://xn--example--7za4pnc.com">http://example-äüö.com</a><br />Change:<input class="vURLField" name="test" type="text" value="http://example-äüö.com" /></p>'
     )
Esempio n. 46
0
def escape_filter(value):
    """Mark the value as a string that should be auto-escaped."""
    return conditional_escape(value)
Esempio n. 47
0
 def test_stacked_render(self):
     w = widgets.FilteredSelectMultiple('test', True)
     self.assertHTMLEqual(
         conditional_escape(w.render('test', 'test')),
         '<select multiple="multiple" name="test" class="selectfilterstacked">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 1, "%(ADMIN_STATIC_PREFIX)s"); });</script>\n'
         % admin_static_prefix())
Esempio n. 48
0
 def _get_level_indicator(self, obj):
     level = getattr(obj, obj._mptt_meta.level_attr)
     return mark_safe(conditional_escape(self.level_indicator) * level)
Esempio n. 49
0
    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        cssclass = 'ckeditorwidget'
        if 'class' in attrs:
            cssclass += ' ' + attrs['class']
        attrs['class'] = cssclass
        final_attrs = self.build_attrs(attrs, name=name)

        id_pieces = attrs['id'].split("-")
        group_name = u"%s-%s" % (id_pieces[0], id_pieces[2])

        #NOTE -- for inline editors: Inline forms will be assigned an ID after render is called. SO what we do is assign a data attribute here so we can re-look it up.
        script = (
            '\n<script type="text/javascript">\n'
            'var inited_editors = {{}};'
            'grp.jQuery.extend( grp.jQuery.fn, {{\n'
            '    hasParent: function( p ) {{\n'
            '        return this.filter(function () {{\n'
            '            return grp.jQuery(p).find(this).length;\n'
            '        }}).length>0;\n'
            '    }}\n'
            '}});\n'
            '//Set up group config settings\n'
            'if(typeof CKEDITOR_INLINE_CONFIGS == "undefined"){{CKEDITOR_INLINE_CONFIGS = {{}};}}\n'
            'var element_id = "{id}";\n'
            'var inline_group_name = "{group_name}";\n'
            '//console.log("element_id "+element_id+" inline_group_name: "+inline_group_name);\n'
            'CKEDITOR_INLINE_CONFIGS["{group_name}"] = {config};\n'
            'function replaceCKEditor(editor_id, replace, config){{\n'
            '//console.log("Replace editor: "+editor_id);'
            'if(typeof replace == "undefined"){{replace = true;}}\n'
            'var editor = CKEDITOR.instances[editor_id];\n'
            'if(editor){{ try{{editor.destroy(true);}}catch(error){{console.log("Error destroying editor: "+error);}} }}\n'
            'if(document.getElementById("cke_"+editor_id)){{ try{{var element = document.getElementById("cke_"+editor_id);element.parentNode.removeChild(element);}}catch(error){{console.log("Error removing container: "+error);}} }}\n'
            'if(replace==true){{\n'
            'CKEDITOR.replace(editor_id, config);\n'
            '}}\n'
            '}}\n'
            'function getCKEditorContent(editor_id){{\n'
            'try{{\n'
            'var iframe = grp.jQuery("#"+editor_id).parent().find("iframe");\n'
            'var iframedoc = iframe[0].contentWindow.document;\n'
            'var body = grp.jQuery(iframedoc).find("body");\n'
            'return grp.jQuery(body).html()\n'
            '}}catch(e){{return "";}}\n'
            '}}\n'
            'function setTextAreaContent(editor_id, content){{\n'
            'try{{\n'
            'grp.jQuery("#"+editor_id).html(content);\n'
            '}}catch(e){{return '
            ';}}\n'
            '}}\n'
            'function initEditors(){{\n'
            'var textareas = grp.jQuery.find("textarea.ckeditorwidget:not(.ckinited)");\n'
            '//console.log("Found: "+textareas.length+" editrors not inited");\n'
            'for(var k=0; k<textareas.length; k++){{\n'
            '   var textarea = textareas[k];\n'
            '   var textarea_id = grp.jQuery(textarea).attr("id");\n'
            '   var group_name = textarea_id.split("-")[0]+"-"+textarea_id.split("-")[2];\n'
            '   initEditor(textarea, group_name);\n'
            '}}\n'
            '}}\n'
            'function initEditor(textarea, group_name){{\n'
            '    var textarea_id = grp.jQuery(textarea).attr("id");\n'
            '    //console.log("init "+textarea_id+" of "+group_name);\n'
            '    var isInEmptyForm = grp.jQuery(textarea).hasParent(".grp-empty-form");\n'
            '    var has_inline_config = (typeof CKEDITOR_INLINE_CONFIGS != "undefined") && (group_name in CKEDITOR_INLINE_CONFIGS);\n'
            '    var use_config = has_inline_config? CKEDITOR_INLINE_CONFIGS[group_name] : {config};\n'
            '    //console.log("has has_inline_config for: "+group_name+" ? "+has_inline_config+" width? "+use_config["width"]);\n'
            '    if(isInEmptyForm==false){{\n'
            '       grp.jQuery(textarea).addClass("ckinited");\n'
            '       replaceCKEditor(textarea_id, true, use_config);\n'
            '       var parent_containers = grp.jQuery(textarea).parents(".grp-dynamic-form");\n'
            '       var dragging_editor_content = "";\n'
            '       grp.jQuery(parent_containers).find(".grp-drag-handler").bind("mousedown", {{id:textarea_id}}, function(event ){{\n'
            '           dragging_editor_content = getCKEditorContent(event.data.id);\n'
            '           replaceCKEditor(event.data.id, false);\n'
            '           if(dragging_editor_content!=""){{setTextAreaContent(event.data.id, dragging_editor_content);}}\n'
            '       }});\n'
            '       grp.jQuery(parent_containers).find(".grp-drag-handler").bind("mouseup", {{id:textarea_id}}, function(event ){{\n'
            '           setTimeout(function(){{replaceCKEditor(event.data.id, true, use_config);}},500);\n'
            '       }});\n'
            '    }}\n'
            '}}\n'
            'setTimeout(function(){{initEditors();}},500);\n'
            'grp.jQuery( document ).ready(function() {{\n'
            '   grp.jQuery(".grp-add-handler").bind("click", function(event){{\n'
            '       setTimeout(function(){{initEditors();}},500);\n'
            '   }});\n'
            '}});\n'
            '</script>\n').format(id=attrs['id'],
                                  config=json.dumps(self.config, indent=2),
                                  group_name=group_name)
        return mark_safe(u'<textarea{attrs}>{value}</textarea>{script}'.format(
            attrs=flatatt(final_attrs),
            value=conditional_escape(force_unicode(value)),
            script=script))
Esempio n. 50
0
 def test_render(self):
     w = widgets.AdminSplitDateTime()
     self.assertHTMLEqual(
         conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))),
         '<p class="datetime">Date: <input value="2007-12-01" type="text" class="vDateField" name="test_0" size="10" /><br />Time: <input value="09:30:00" type="text" class="vTimeField" name="test_1" size="8" /></p>',
     )
Esempio n. 51
0
 def render_label(self):
     bits = []
     if self.icon:
         bits.append('<i class="%s"></i>&nbsp;' % self.icon)
     bits.append(conditional_escape(self.text))
     return "".join(force_text(bit) for bit in bits)
Esempio n. 52
0
 def render(self, name, value, attrs=None):
     if value is None: value = ''
     final_attrs = self.build_attrs(attrs, name=name)
     return mark_safe(
         u'<textarea%s>%s</textarea>' %
         (flatatt(final_attrs), conditional_escape(force_unicode(value))))
Esempio n. 53
0
 def render_option(option_value, option_label):
     option_value = force_unicode(option_value)
     selected_html = (option_value in selected_choices) and u' selected="selected"' or ''
     return u'<option value="%s"%s>%s</option>' % (
         escape(option_value), selected_html,
         conditional_escape(force_unicode(option_label)))
Esempio n. 54
0
 def save(self, **kwargs):
     self.content_html = conditional_escape(
         settings.AGORA_PARSER(self.content))
     super(ForumPost, self).save(**kwargs)
Esempio n. 55
0
def items_for_tree_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 django.VERSION[1] >= 4:
                    if field_name == 'action_checkbox':
                        row_class = ' class="action-checkbox disclosure"'
                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 value is None:
                    result_repr = EMPTY_CHANGELIST_VALUE
                if isinstance(f.rel, models.ManyToOneRel):
                    result_repr = escape(getattr(result, f.name))
                else:
                    result_repr = display_for_field(value, f)
                if isinstance(f, models.DateField) or isinstance(
                        f, models.TimeField):
                    row_class = ' class="nowrap"'
            if first:
                if django.VERSION[1] < 4:
                    try:
                        f, attr, checkbox_value = lookup_field(
                            'action_checkbox', result, cl.model_admin)
                        #result_repr = mark_safe("%s%s" % (value, result_repr))
                        if row_class:
                            row_class = "%s%s" % (row_class[:-1],
                                                  ' disclosure"')
                        else:
                            row_class = ' class="disclosure"'
                    except (AttributeError, ObjectDoesNotExist):
                        pass

        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:
            if django.VERSION[1] < 4:
                table_tag = 'td'  # {True:'th', False:'td'}[first]
            else:
                table_tag = {True: 'th', False: 'td'}[first]

            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:]
            first = False
            if django.VERSION[1] < 4:
                yield mark_safe(u'<%s%s>%s<a href="%s"%s>%s</a></%s>' % \
                    (table_tag, row_class, checkbox_value, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag))
            else:
                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:
                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]))
Esempio n. 56
0
 def transform_option_label(self, option_label):
     if (not isinstance(option_label, (six.string_types, Promise))
             and callable(self.transform)):
         option_label = self.transform(option_label)
     return html.conditional_escape(force_text(option_label))
Esempio n. 57
0
 def test_conditional_escape(self):
     s = '<h1>interop</h1>'
     self.assertEqual(html.conditional_escape(s),
                      '&lt;h1&gt;interop&lt;/h1&gt;')
     self.assertEqual(html.conditional_escape(safestring.mark_safe(s)), s)
Esempio n. 58
0
 def __unicode__(self):
     return mark_safe(
         u'<label>%s %s</label>' %
         (self.tag(), conditional_escape(force_unicode(self.choice_label))))
Esempio n. 59
0
 def render_data(self, state, review):
     """Return the rendered contents of the column."""
     return conditional_escape(review.review_request.summary)
Esempio n. 60
0
 def label_from_instance(self, obj):
     return mark_safe(conditional_escape(smart_text('/'.join([x['name'] for x in obj.get_ancestors(include_self=True).values()]))))