Python django.forms.utils.flatatt() Examples

The following are 30 code examples of django.forms.utils.flatatt(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.forms.utils , or try the search function .
Example #1
Source File: modeladmin_tags.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def result_row_display(context, index):
    obj = context['object_list'][index]
    view = context['view']
    row_attrs_dict = view.model_admin.get_extra_attrs_for_row(obj, context)
    row_attrs_dict['data-object-pk'] = obj.pk
    odd_or_even = 'odd' if (index % 2 == 0) else 'even'
    if 'class' in row_attrs_dict:
        row_attrs_dict['class'] += ' %s' % odd_or_even
    else:
        row_attrs_dict['class'] = odd_or_even

    context.update({
        'obj': obj,
        'row_attrs': mark_safe(flatatt(row_attrs_dict)),
        'action_buttons': view.get_buttons_for_obj(obj),
    })
    return context 
Example #2
Source File: dashboard.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        if DJANGO_11:
            final_attrs = self.build_attrs(attrs, extra_attrs={'name': name})
        else:
            final_attrs = self.build_attrs(attrs, name=name)
        final_attrs['class'] = 'nav nav-pills nav-stacked'
        output = [u'<ul%s>' % flatatt(final_attrs)]
        options = self.render_options(force_text(value), final_attrs['id'])
        if options:
            output.append(options)
        output.append(u'</ul>')
        output.append('<input type="hidden" id="%s_input" name="%s" value="%s"/>' %
                      (final_attrs['id'], name, force_text(value)))
        return mark_safe(u'\n'.join(output)) 
Example #3
Source File: base.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def render(self, name, value, attrs=None):

        date_format = "yyyy-MM-dd hh:mm"

        if "data-format" not in self.attrs:
            attrs['data-format'] = date_format
        if "class" not in self.attrs:
            attrs['class'] = 'input-medium'

        field = super(DateTimePickerInput, self).render(name, value, attrs)
        final_attrs = self.build_attrs(attrs)

        output = format_html(u'''
         <div class="input-append date datetimepicker" {0}>
            {1}
            <span class="add-on">
                <i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
            </span>
        </div>
        ''', flatatt(final_attrs), field)

        return mark_safe(output) 
Example #4
Source File: base.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def render(self, name, value, attrs=None):

        date_format = "yyyy-MM-dd"

        if "format" not in self.attrs:
            attrs['format'] = date_format

        if "data-format" not in self.attrs:
            attrs['data-format'] = date_format

        field = super(DatepickerInput, self).render(name, value, attrs)
        final_attrs = self.build_attrs(attrs)

        output = format_html(u'''
         <div class="input-append date datepicker" data-provide="datepicker" {0}>
            {1}
            <span class="add-on">
                <i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
            </span>
        </div>
        ''', flatatt(final_attrs), field)

        return mark_safe(output) 
Example #5
Source File: forms.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def render(self, name, value, attrs):
        encoded = value
        final_attrs = self.build_attrs(attrs)

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

        return format_html("<div{}>{}</div>", flatatt(final_attrs), summary) 
Example #6
Source File: widgets.py    From online-judge with GNU Affero General Public License v3.0 6 votes vote down vote up
def render(self, name, value, attrs=None, renderer=None):
        attrs = attrs or {}

        ace_attrs = {
            'class': 'django-ace-widget loading',
            'style': 'width:%s; height:%s' % (self.width, self.height),
            'id': 'ace_%s' % name,
        }
        if self.mode:
            ace_attrs['data-mode'] = self.mode
        if self.theme:
            ace_attrs['data-theme'] = self.theme
        if self.wordwrap:
            ace_attrs['data-wordwrap'] = 'true'

        attrs.update(style='width: 100%; min-width: 100%; max-width: 100%; resize: none')
        textarea = super(AceWidget, self).render(name, value, attrs)

        html = '<div%s><div></div></div>%s' % (flatatt(ace_attrs), textarea)

        # add toolbar
        html = ('<div class="django-ace-editor"><div style="width: 100%%" class="django-ace-toolbar">'
                '<a href="./" class="django-ace-max_min"></a></div>%s</div>') % html

        return mark_safe(html) 
Example #7
Source File: mixins.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def admin_thumb(self, obj):
        try:
            image = getattr(obj, self.thumb_image_field_name, None)
        except AttributeError:
            raise ImproperlyConfigured(
                u"The `thumb_image_field_name` attribute on your `%s` class "
                "must name a field on your model." % self.__class__.__name__
            )

        img_attrs = {
            'src': self.thumb_default,
            'width': self.thumb_image_width,
            'class': self.thumb_classname,
        }
        if not image:
            if self.thumb_default:
                return mark_safe('<img{}>'.format(flatatt(img_attrs)))
            return ''

        # try to get a rendition of the image to use
        from wagtail.images.shortcuts import get_rendition_or_not_found
        spec = self.thumb_image_filter_spec
        rendition = get_rendition_or_not_found(image, spec)
        img_attrs.update({'src': rendition.url})
        return mark_safe('<img{}>'.format(flatatt(img_attrs))) 
Example #8
Source File: forms.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def render(self, name, value, attrs):
        encoded = value
        final_attrs = self.build_attrs(attrs)

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

        return format_html("<div{}>{}</div>", flatatt(final_attrs), summary) 
Example #9
Source File: dashboard.py    From imoocc with GNU General Public License v2.0 6 votes vote down vote up
def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        if DJANGO_11:
            final_attrs = self.build_attrs(attrs, extra_attrs={'name': name})
        else:
            final_attrs = self.build_attrs(attrs, name=name)
        final_attrs['class'] = 'nav nav-pills nav-stacked'
        output = [u'<ul%s>' % flatatt(final_attrs)]
        options = self.render_options(force_text(value), final_attrs['id'])
        if options:
            output.append(options)
        output.append(u'</ul>')
        output.append('<input type="hidden" id="%s_input" name="%s" value="%s"/>' %
                      (final_attrs['id'], name, force_text(value)))
        return mark_safe(u'\n'.join(output)) 
Example #10
Source File: factory.py    From Wooey with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def mutli_render(render_func, appender_data_dict=None):
    def render(name, value=None, attrs=None, renderer=None):
        if not isinstance(value, (list, tuple)):
            value = [value]
        values = value
        widget_renderer = partial(render_func, renderer=renderer) if renderer else partial(render_func)
        # The tag is a marker for our javascript to reshuffle the elements. This is because some widgets have complex rendering with multiple fields
        pieces = ['<{tag} {multi_attr}>{widget}</{tag}>'.format(tag='div', multi_attr=config.WOOEY_MULTI_WIDGET_ATTR,
                                                                widget=widget_renderer(name, value, attrs)) for value in values]

        # we add a final piece that is our button to click for adding. It's useful to have it here instead of the template so we don't
        # have to reverse-engineer who goes with what

        # build the attribute dict
        data_attrs = flatatt(appender_data_dict if appender_data_dict is not None else {})
        pieces.append(format_html('<a href="#{anchor}"{data}><span class="glyphicon glyphicon-plus"></span></a>', anchor=config.WOOEY_MULTI_WIDGET_ANCHOR
                                  , data=data_attrs))
        return mark_safe('\n'.join(pieces))
    return render 
Example #11
Source File: columns.py    From sal with Apache License 2.0 6 votes vote down vote up
def attributes(self):
        """
        Returns a dictionary of initial state data for sorting, sort direction, and visibility.

        The default attributes include ``data-config-sortable``, ``data-config-visible``, and (if
        applicable) ``data-config-sorting`` to hold information about the initial sorting state.
        """
        attributes = {
            'data-config-sortable': 'true' if self.sortable else 'false',
            'data-config-visible': 'true' if self.visible else 'false',
        }

        if self.sort_priority is not None:
            attributes['data-config-sorting'] = ','.join(map(six.text_type, [
                self.sort_priority,
                self.index,
                self.sort_direction,
            ]))

        return flatatt(attributes) 
Example #12
Source File: test_utils.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_flatatt(self):
        ###########
        # flatatt #
        ###########

        self.assertEqual(flatatt({'id': "header"}), ' id="header"')
        self.assertEqual(flatatt({'class': "news", 'title': "Read this"}), ' class="news" title="Read this"')
        self.assertEqual(
            flatatt({'class': "news", 'title': "Read this", 'required': "required"}),
            ' class="news" required="required" title="Read this"'
        )
        self.assertEqual(
            flatatt({'class': "news", 'title': "Read this", 'required': True}),
            ' class="news" title="Read this" required'
        )
        self.assertEqual(
            flatatt({'class': "news", 'title': "Read this", 'required': False}),
            ' class="news" title="Read this"'
        )
        self.assertEqual(flatatt({'class': None}), '')
        self.assertEqual(flatatt({}), '') 
Example #13
Source File: test_utils.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_flatatt_no_side_effects(self):
        """
        flatatt() does not modify the dict passed in.
        """
        attrs = {'foo': 'bar', 'true': True, 'false': False}
        attrs_copy = copy.copy(attrs)
        self.assertEqual(attrs, attrs_copy)

        first_run = flatatt(attrs)
        self.assertEqual(attrs, attrs_copy)
        self.assertEqual(first_run, ' foo="bar" true')

        second_run = flatatt(attrs)
        self.assertEqual(attrs, attrs_copy)

        self.assertEqual(first_run, second_run) 
Example #14
Source File: dashboard.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, extra_attrs={'name': name})
        final_attrs['class'] = 'nav nav-pills nav-stacked'
        output = [u'<ul%s>' % flatatt(final_attrs)]
        options = self.render_options(force_text(value), final_attrs['id'])
        if options:
            output.append(options)
        output.append(u'</ul>')
        output.append('<input type="hidden" id="%s_input" name="%s" value="%s"/>' %
                      (final_attrs['id'], name, force_text(value)))
        return mark_safe(u'\n'.join(output)) 
Example #15
Source File: sniplates.py    From django-sniplates with MIT License 5 votes vote down vote up
def flatattrs(attrs):
    return flatatt(attrs) 
Example #16
Source File: relfield.py    From Mxonline3 with Apache License 2.0 5 votes vote down vote up
def render(self, name, value, attrs=None, renderer=None):
        final_attrs = self.build_attrs(attrs, extra_attrs={'name': name})
        output = [format_html('<select{0}>', flatatt(final_attrs))]
        if value:
            output.append(format_html('<option selected="selected" value="{0}">{1}</option>', value, self.label_for_value(value)))
        output.append('</select>')
        return mark_safe('\n'.join(output)) 
Example #17
Source File: dashboard.py    From Mxonline3 with Apache License 2.0 5 votes vote down vote up
def render(self, name, value, attrs=None, renderer=None):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, extra_attrs={'name': name})
        final_attrs['class'] = 'nav nav-pills nav-stacked'
        output = [u'<ul%s>' % flatatt(final_attrs)]
        options = self.render_options(force_text(value), final_attrs['id'])
        if options:
            output.append(options)
        output.append(u'</ul>')
        output.append('<input type="hidden" id="%s_input" name="%s" value="%s"/>' %
                      (final_attrs['id'], name, force_text(value)))
        return mark_safe(u'\n'.join(output)) 
Example #18
Source File: widgets.py    From adhocracy4 with GNU Affero General Public License v3.0 5 votes vote down vote up
def render(self, name, value, attrs=None, choices=(), renderer=None):
        all_choices = list(chain(self.choices, choices))

        if len(all_choices) <= 1:
            return ''

        if value is None:
            value = all_choices[0][0]

        _id = attrs.pop('id')
        final_attrs = flatatt(self.build_attrs(attrs))
        value_label = self.get_option_label(value, choices=choices)

        options = super().render(name, value, attrs={
            'class': 'dropdown-menu',
            'aria-labelledby': _id,
        }, choices=choices)

        return render_to_string(self.template, {
            'options': options,
            'id': _id,
            'attrs': final_attrs,
            'value_label': value_label,
            'label': self.label,
            'right': self.right,
        }) 
Example #19
Source File: widgets.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            final_attrs['value'] = force_text(self._format_value(value))
        return format_html('<input{} />', flatatt(final_attrs)) 
Example #20
Source File: widgets.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def render(self, name, value, attrs=None):
        html = super(AdminURLFieldWidget, self).render(name, value, attrs)
        if value:
            value = force_text(self._format_value(value))
            final_attrs = {'href': smart_urlquote(value)}
            html = format_html(
                '<p class="url">{} <a{}>{}</a><br />{} {}</p>',
                _('Currently:'), flatatt(final_attrs), value,
                _('Change:'), html
            )
        return html 
Example #21
Source File: widgets.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def render(self):
        """Outputs a <ul> for this set of radio fields."""
        return format_html('<ul{}>\n{}\n</ul>',
                           flatatt(self.attrs),
                           format_html_join('\n', '<li>{}</li>',
                                            ((force_text(w),) for w in self))) 
Example #22
Source File: boundfield.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def label_tag(self, contents=None, attrs=None, label_suffix=None):
        """
        Wraps the given contents in a <label>, if the field has an ID attribute.
        contents should be 'mark_safe'd to avoid HTML escaping. If contents
        aren't given, uses the field's HTML-escaped label.

        If attrs are given, they're used as HTML attributes on the <label> tag.

        label_suffix allows overriding the form's label_suffix.
        """
        contents = contents or self.label
        if label_suffix is None:
            label_suffix = (self.field.label_suffix if self.field.label_suffix is not None
                            else self.form.label_suffix)
        # Only add the suffix if the label does not end in punctuation.
        # Translators: If found as last label character, these punctuation
        # characters will prevent the default label_suffix to be appended to the label
        if label_suffix and contents and contents[-1] not in _(':?.!'):
            contents = format_html('{}{}', contents, label_suffix)
        widget = self.field.widget
        id_ = widget.attrs.get('id') or self.auto_id
        if id_:
            id_for_label = widget.id_for_label(id_)
            if id_for_label:
                attrs = dict(attrs or {}, **{'for': id_for_label})
            if self.field.required and hasattr(self.form, 'required_css_class'):
                attrs = attrs or {}
                if 'class' in attrs:
                    attrs['class'] += ' ' + self.form.required_css_class
                else:
                    attrs['class'] = self.form.required_css_class
            attrs = flatatt(attrs) if attrs else ''
            contents = format_html('<label{}>{}</label>', attrs, contents)
        else:
            contents = conditional_escape(contents)
        return mark_safe(contents) 
Example #23
Source File: widgets.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def tag(self, attrs=None):
        attrs = attrs or self.attrs
        final_attrs = dict(attrs, type=self.input_type, name=self.name, value=self.choice_value)
        if self.is_checked():
            final_attrs['checked'] = 'checked'
        return format_html('<input{} />', flatatt(final_attrs)) 
Example #24
Source File: widgets.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def render(self, name, value, attrs=None, choices=()):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, name=name)
        output = [format_html('<select{}>', flatatt(final_attrs))]
        options = self.render_options(choices, [value])
        if options:
            output.append(options)
        output.append('</select>')
        return mark_safe('\n'.join(output)) 
Example #25
Source File: widgets.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def render(self, name, value, attrs=None):
        final_attrs = self.build_attrs(attrs, type='checkbox', name=name)
        if self.check_test(value):
            final_attrs['checked'] = 'checked'
        if not (value is True or value is False or value is None or value == ''):
            # Only add the 'value' attribute if a value is non-empty.
            final_attrs['value'] = force_text(value)
        return format_html('<input{} />', flatatt(final_attrs)) 
Example #26
Source File: widgets.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, name=name)
        return format_html('<textarea{}>\r\n{}</textarea>',
                           flatatt(final_attrs),
                           force_text(value)) 
Example #27
Source File: widgets.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def render(self, name, value, attrs=None, choices=()):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, name=name)
        output = [format_html('<select{}>', flatatt(final_attrs))]
        options = self.render_options(choices, [value])
        if options:
            output.append(options)
        output.append('</select>')
        return mark_safe('\n'.join(output)) 
Example #28
Source File: widgets.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            final_attrs['value'] = force_text(self._format_value(value))
        return format_html('<input{} />', flatatt(final_attrs)) 
Example #29
Source File: widgets.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def render(self, name, value, attrs=None, choices=()):
        if value is None:
            value = []
        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        id_ = final_attrs.get('id')
        inputs = []
        for i, v in enumerate(value):
            input_attrs = dict(value=force_text(v), **final_attrs)
            if id_:
                # An ID attribute was given. Add a numeric index as a suffix
                # so that the inputs don't all have the same ID attribute.
                input_attrs['id'] = '%s_%s' % (id_, i)
            inputs.append(format_html('<input{} />', flatatt(input_attrs)))
        return mark_safe('\n'.join(inputs)) 
Example #30
Source File: boundfield.py    From python with Apache License 2.0 5 votes vote down vote up
def label_tag(self, contents=None, attrs=None, label_suffix=None):
        """
        Wraps the given contents in a <label>, if the field has an ID attribute.
        contents should be 'mark_safe'd to avoid HTML escaping. If contents
        aren't given, uses the field's HTML-escaped label.

        If attrs are given, they're used as HTML attributes on the <label> tag.

        label_suffix allows overriding the form's label_suffix.
        """
        contents = contents or self.label
        if label_suffix is None:
            label_suffix = (self.field.label_suffix if self.field.label_suffix is not None
                            else self.form.label_suffix)
        # Only add the suffix if the label does not end in punctuation.
        # Translators: If found as last label character, these punctuation
        # characters will prevent the default label_suffix to be appended to the label
        if label_suffix and contents and contents[-1] not in _(':?.!'):
            contents = format_html('{}{}', contents, label_suffix)
        widget = self.field.widget
        id_ = widget.attrs.get('id') or self.auto_id
        if id_:
            id_for_label = widget.id_for_label(id_)
            if id_for_label:
                attrs = dict(attrs or {}, **{'for': id_for_label})
            if self.field.required and hasattr(self.form, 'required_css_class'):
                attrs = attrs or {}
                if 'class' in attrs:
                    attrs['class'] += ' ' + self.form.required_css_class
                else:
                    attrs['class'] = self.form.required_css_class
            attrs = flatatt(attrs) if attrs else ''
            contents = format_html('<label{}>{}</label>', attrs, contents)
        else:
            contents = conditional_escape(contents)
        return mark_safe(contents)