Example #1
0
    def rows(self):
        """Returns a generator with table rows"""
        for x_value in self.x_values:
            tds = []

            # Info fields
            for name, field in self.info_fields:
                field = BoundField(self, field, name)
                tds.append(u'<td>%s</td>' % unicode(field))

            # Cross fields
            for y_value in self.y_values:
                field_prefix = self._meta.cross_fields_template % (
                    self.get_x_value(x_value),
                    self.get_y_value(y_value),
                )

                for field_name, field in self.fields.items():
                    if field_name.startswith(field_prefix):
                        errors = ''  # TODO
                        bfield = BoundField(self, field, field_name)

                        tds.append(u'<td>%s %s</td>' %
                                   (errors, unicode(bfield)))

            tds = u''.join(tds)

            yield u'<tr><th>%s</th>%s</tr>' % (x_value, tds)
Example #2
0
	def __iter__(self):
		for name, field in self.fields.items():
			bound_field = BoundField(self, field, name)
			bound_field.percent = field.percent
			bound_field.student_name = field.student_name
			
			yield bound_field
Example #3
0
    def __init__(self, *args, **kwargs):
        super(FindingForm, self).__init__(*args, **kwargs)
        # Dynamically add the fields for IM providers / external services
        self.service_fields = []
        for shortname, name, icon in SERVICES:
            field = forms.URLField(
                max_length=255, required=False, label=name
            )
            self.fields['service_' + shortname] = field
            self.service_fields.append({
                'label': name,
                'shortname': shortname,
                'id': 'service_' + shortname,
                'icon': icon,
                'field': BoundField(self, field, 'service_' + shortname),
            })

        self.improvider_fields = []
        for shortname, name, icon in IMPROVIDERS:
            field = forms.CharField(
                max_length=50, required=False, label=name
            )
            self.fields['im_' + shortname] = field
            self.improvider_fields.append({
                'label': name,
                'shortname': shortname,
                'id': 'im_' + shortname,
                'icon': icon,
                'field': BoundField(self, field, 'im_' + shortname),
            })
Example #4
0
    def __init__(self, *args, **kwargs):
        # Dynamically add the fields for IM providers / external services
        super(PortfolioForm, self).__init__(*args, **kwargs)
        self.portfolio_fields = []
        self.initial = {}
        num = 1
        for site in kwargs['instance'].portfoliosite_set.all():
            self.initial['title_%d' % num] = site.title
            self.initial['url_%d' % num] = site.url
            num += 1

        # Add fields
        for i in range(1, num + 3):
            url_field = forms.URLField(max_length=255,
                                       required=False,
                                       label=_('URL %d') % i)
            title_field = forms.CharField(max_length=100,
                                          required=False,
                                          label=_('Title %d') % i)
            self.fields['title_%d' % i] = title_field
            self.fields['url_%d' % i] = url_field
            self.portfolio_fields.append({
                'title_field':
                BoundField(self, title_field, 'title_%d' % i),
                'url_field':
                BoundField(self, url_field, 'url_%d' % i),
                'title_id':
                'id_title_%d' % i,
                'url_id':
                'id_url_%d' % i,
            })

        # Add custom validator for each url field
        for key in [k for k in self.fields if k.startswith('url_')]:
            setattr(self, 'clean_%s' % key, make_validator(key, self))
Example #5
0
    def __iter__(self):
        for name, field in self.fields.items():
            bound_field = BoundField(self, field, name)
            bound_field.percent = field.percent
            bound_field.student_name = field.student_name

            yield bound_field
Example #6
0
 def render(self, form, form_style, context, template_pack=TEMPLATE_PACK):
     extra = []
     for field in self.fields:
         field_instance = form.fields[field]
         bound_field = BoundField(form, field_instance, field)
         extra.append(bound_field.value())
     context["extra"] = mark_safe("\n".join(extra))
     return super(VisibleHiddenField, self).render(form, form_style, context, template_pack)
Example #7
0
    def as_hidden(self):
        """Returns this form rendered entirely as hidden fields."""
        output = []
        for name, field in self.fields.items():
            bf = BoundField(self, field, name)
            output.append(bf.as_hidden())

        return mark_safe(u'\n'.join(output))
Example #8
0
 def __iter__(self):
     for field in self.args:
         if isinstance(field, (list, tuple)):
             yield [
                 BoundField(self.form, self.form.fields[f], f)
                 for f in field
             ]
         else:
             yield BoundField(self.form, self.form.fields[field], field)
Example #9
0
def get_field_tuple(name, form_or_model):
    """Returns a tuple for the field, of given instance, identified by "name".
    
    Instance could be a model instance, a form instance or any arbitrary object.
    
    The returned tuple is in the form:
    
    (label, attrs, value)
    """
    name, sep, suffix = name.partition(':')

    label = ""
    value = ""
    td_attrs = {}
    field_list = get_fields(form_or_model)
    field = None

    if name in field_list:
        field = field_list[name]

    elif hasattr(form_or_model, name):
        field = getattr(form_or_model, name)
        if hasattr(field, 'short_description'):
            name = field.short_description

    if isinstance(field, models.Field):
        label = '%s:' % field.verbose_name
        value = '%s' % field_to_string(field, form_or_model)

    elif isinstance(field, forms.Field):
        bf = BoundField(form_or_model, field, name)
        label = '%s' % bf.label_tag()
        value = '%s' % bf
        if bf.help_text:
            value += '<br/><span title="%(help_text)s" class="helptext helppopup">%(help_text)s</span>' % {
                "help_text": '%s' % bf.help_text
            }
        errors = bf.errors
        if errors:
            value += '<br/>\n<ul class="errorlist">\n'
            for error in errors:
                value += '\t<li>%s</li>\n' % error
            value += '</ul>\n'
        css_classes = bf.css_classes()
        if css_classes:
            td_attrs['class'] = css_classes

    else:
        name = _(pretty_name(name).lower())
        label = '%s:' % name.capitalize()
        value = field() if callable(field) else field

    firstcap_label = label[:1].upper() + label[1:]
    if suffix:
        value += " " + suffix

    return mark_safe(firstcap_label), flatatt(td_attrs), mark_safe(value)
Example #10
0
 def render(self, form, form_style, context, template_pack=TEMPLATE_PACK):
     extra = []
     for field in self.fields:
         field_instance = form.fields[field]
         bound_field = BoundField(form, field_instance, field)
         extra.append(bound_field.value())
     context['extra'] = mark_safe("\n".join(extra))
     return super(VisibleHiddenField, self).render(form, form_style,
                                                   context, template_pack)
Example #11
0
    def _ul_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 = [], []

        ##########
        ### Main hack goes like this: we want children to be rendered as <ul> *inside* parent <li>
        ### Thus, we render special tree items not as usual, but using helper atribute that sorted it as tree for us
        ##########

        for name, field in self.fields.items():
            bf = BoundField(self, field, name)
            bf_errors = self.error_class([conditional_escape(error) for error in bf.errors]) # Escape and cache in local variable.
            if bf.is_hidden:
                if bf_errors:
                    top_errors.extend([u'(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors])
                hidden_fields.append(unicode(bf))
            else:
                if errors_on_separate_row and bf_errors:
                    output.append(error_row % force_unicode(bf_errors))
                if bf.label:
                    label = conditional_escape(force_unicode(bf.label))
                    # Only add the suffix if the label does not end in
                    # punctuation.
                    if self.label_suffix:
                        if label[-1] not in ':?.!':
                            label += self.label_suffix
                    label = bf.label_tag(label) or ''
                else:
                    label = ''
                if field.help_text:
                    help_text = help_text_html % force_unicode(field.help_text)
                else:
                    help_text = u''
                output.append(normal_row % {'errors': force_unicode(bf_errors), 'label': force_unicode(label), 'field': unicode(bf), 'help_text': help_text})
        if top_errors:
            output.insert(0, error_row % force_unicode(top_errors))
        if hidden_fields: # Insert any hidden fields in the last row.
            str_hidden = u''.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': ''}
                    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(u'\n'.join(output))
Example #12
0
	def __iter__(self):
		for name, field in self.fields.items():
			if name.endswith("-text"):
				continue
				
			score_field = BoundField(self, field, name)
			score_field.user = field.user
			comment_field = BoundField(self, self.fields[name + "-text"], name + "-text")
			
			yield (score_field, comment_field)
Example #13
0
def get_field_tuple(name, form_or_model):
    """Returns a tuple for the field, of given instance, identified by "name".
    
    Instance could be a model instance, a form instance or any arbitrary object.
    
    The returned tuple is in the form:
    
    (label, attrs, value)
    """    
    name, sep, suffix = name.partition(':')
    
    label = ""
    value = ""
    td_attrs = {}
    field_list = get_fields(form_or_model)
    field = None
    
    if name in field_list:
        field = field_list[name]
        
    elif hasattr(form_or_model, name):
        field = getattr(form_or_model, name)
        if hasattr(field, 'short_description'):
            name = field.short_description

    if isinstance(field, models.Field):
        label = '%s:' % field.verbose_name
        value = '%s' % field_to_string(field, form_or_model)

    elif isinstance(field, forms.Field):
        bf = BoundField(form_or_model, field, name)
        label = '%s' % bf.label_tag()
        value = '%s' % bf
        if bf.help_text:
            value += '<br/><span title="%(help_text)s" class="helptext helppopup">%(help_text)s</span>' % {"help_text": '%s' % bf.help_text}
        errors = bf.errors
        if errors:
            value += '<br/>\n<ul class="errorlist">\n'
            for error in errors:
                value += '\t<li>%s</li>\n' % error
            value += '</ul>\n'
        css_classes = bf.css_classes()
        if css_classes:
            td_attrs['class'] = css_classes

    else:
        name = _(pretty_name(name).lower())
        label = '%s:' % name.capitalize()
        value = field() if callable(field) else field

    firstcap_label = label[:1].upper() + label[1:]
    if suffix:
        value += " " + suffix

    return mark_safe(firstcap_label), flatatt(td_attrs), mark_safe(value)
Example #14
0
    def _html_output(self, normal_row, error_row, row_ender, help_text_html,
                     errors_on_separate_row):
        # Customized to handle special case for reCaptcha forms (not rendering remote_ip field)
        "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 = BoundField(self, field, name)
            bf_errors = self.error_class([
                conditional_escape(error) for error in bf.errors
            ])  # Escape and cache in local variable.
            if not bf.is_hidden:
                # 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_unicode(bf_errors))

                if bf.label:
                    label = conditional_escape(force_unicode(bf.label))
                    # Only add the suffix if the label does not end in
                    # punctuation.
                    if self.label_suffix:
                        if label[-1] not in ':?.!':
                            label += self.label_suffix
                    label = bf.label_tag(label) or ''
                else:
                    label = ''

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

                output.append(
                    normal_row % {
                        'errors': force_unicode(bf_errors),
                        'label': force_unicode(label),
                        'field': unicode(bf),
                        'help_text': help_text,
                        'html_class_attr': html_class_attr
                    })

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

        return mark_safe(u'\n'.join(output))
Example #15
0
    def as_div(self):
        text_row = """<div class="form-line">%(label)s %(field)s %(errors)s %(help_text)s</div>"""
        choice_row = """<div class="form-line-choice">%(field)s %(label)s %(errors)s %(help_text)s</div>"""
        hidden_row = """<div class="form-hidden">%(field)s</div>"""
        error_row = """<div class="form-error">%s</div>"""
        help_text_html = """<div class="form-note">%s</div>"""
        required_html = """<span class="reqicon">*</span>"""

        output, hidden_fields = [], []

        for name, field in self.fields.items():
            bf = BoundField(self, field, name)
            bf_errors = self.error_class([escape(error) for error in bf.errors])

            if bf.is_hidden:
                # Just output the widget row for a hidden field
                hidden = unicode(bf).replace(u" />", u">")
                hidden_fields.append(hidden_row % {"field": hidden})
            else:
                choice_field = isinstance(field.widget, CheckboxInput)

                # Build label HTML, with required * if appropriate
                if bf.label:
                    label = escape(force_unicode(bf.label))
                    required = required_html if field.required else u""
                    label_attrs = {}
                    if choice_field:
                        label_attrs["class"] = "choice"
                    label = bf.label_tag(label + required, attrs=label_attrs) or ""
                else:
                    label = ""

                # Build help text HTML
                if field.help_text:
                    help_text = help_text_html % force_unicode(field.help_text)
                else:
                    help_text = u""

                # Output the row
                if choice_field:
                    template = choice_row
                else:
                    template = text_row
                row_context = {
                    "errors":       force_unicode(bf_errors),
                    "label":        force_unicode(label),
                    "field":        unicode(bf).replace(u" />", u">"),
                    "help_text":    help_text,
                }
                output.append(template % row_context)
        
        return mark_safe(u"\n".join(hidden_fields) + u"\n".join(output))
Example #16
0
    def _html_output(self, normal_row, error_row, row_ender, help_text_html,
                     errors_on_separate_row):
        top_errors = self.non_field_errors(
        )  # Errors that should be displayed above all fields.
        output, hidden_fields = [], []
        for name in ('header', 'preview_all', 'validate', 'create_missing'):
            field = self.fields[name]
            bf = BoundField(self, field, name)
            bf_errors = self.error_class([
                conditional_escape(error) for error in bf.errors
            ])  # Escape and cache in local variable.
            if bf_errors:
                top_errors.extend([
                    u'(Hidden field %s) %s' % (name, force_unicode(e))
                    for e in bf_errors
                ])
            output.append(
                '<tr><td class="label" colspan="4">%s</td><td>%s</td></tr>' %
                (bf.label, unicode(bf)))

        output.append(
            u'<tr><th>%s</th><th>%s</th><th class="rex">%s</th><th class="lkf">%s</th><th class="key">%s</th></tr>'
            %
            (_('Column'), _('Field'), _('Regex'), _('Lookup Field'), _('pk')))

        for i, f in enumerate(self._fields):
            line = []
            error_line = []
            rowid = self.fields['col_%s' % i].label
            for n in ('col_%s', 'fld_%s', 'rex_%s', 'lkf_%s', 'key_%s'):
                name = n % i
                field = self.fields[name]
                bf = BoundField(self, field, name)
                bf_errors = self.error_class([
                    conditional_escape(error) for error in bf.errors
                ])  # Escape and cache in local variable.
                error_line.append(force_unicode(bf_errors), )
                line.append('<td class=%(class)s>%(field)s</td>' % {
                    'field': unicode(bf),
                    'class': n[:3]
                })
            output.append('<tr><td colspan="5">%s</td></tr>' %
                          ''.join(error_line))
            output.append('<tr>%(line)s</tr>' % {
                'line': ''.join(line),
                'rowid': rowid
            })

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

        return mark_safe(u'\n'.join(output))
Example #17
0
    def __init__(self, *args, **kwargs):
        from django.forms.forms import BoundField
        super(BatchUpdateForm, self).__init__(*args, **kwargs)
        for field_name in self.fields.keys():

            model_field = self._meta.model._meta.get_field(field_name)
            if isinstance(model_field, models.ManyToManyField):

                self.fields['%s%s' % (
                    M2M_REMOVE_PREFIX,
                    field_name,
                )] = copy(self.fields[field_name])
                self.fields['%s%s' % (
                    M2M_REMOVE_PREFIX,
                    field_name,
                )].label = _("Remove %s" % (field_name, ))
                self.fields['%s%s' % (
                    M2M_REMOVE_PREFIX,
                    field_name,
                )].update_checkbox = BoundField(
                    self, forms.BooleanField(required=False),
                    'updating-%s%s' % (
                        M2M_REMOVE_PREFIX,
                        field_name,
                    ))

                self.fields['%s%s' % (
                    M2M_ADD_PREFIX,
                    field_name,
                )] = copy(self.fields[field_name])
                self.fields['%s%s' % (
                    M2M_ADD_PREFIX,
                    field_name,
                )].label = _("Add %s" % (field_name, ))
                self.fields['%s%s' % (
                    M2M_ADD_PREFIX,
                    field_name,
                )].update_checkbox = BoundField(
                    self, forms.BooleanField(required=False),
                    'updating-%s%s' % (
                        M2M_ADD_PREFIX,
                        field_name,
                    ))

                self.fields.pop(field_name)
            else:
                self.fields[field_name].update_checkbox = BoundField(
                    self, forms.BooleanField(required=False),
                    'updating-' + field_name)
Example #18
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 section, fields in self.sections:
            if section:
                output.append(normal_row % {'errors': '', 'label': '&nbsp;', 'field': self.section_template%section, 'help_text': ''})

            for name, field in [i for i in self.fields.items() if i[0] in fields]:
                bf = BoundField(self, field, name)
                bf_errors = self.error_class([escape(error) for error in bf.errors]) # Escape and cache in local variable.
                if bf.is_hidden:
                    if bf_errors:
                        top_errors.extend([u'(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors])
                    hidden_fields.append(unicode(bf))
                else:
                    if errors_on_separate_row and bf_errors:
                        output.append(error_row % force_unicode(bf_errors))
                    if bf.label:
                        label = escape(force_unicode(bf.label))
                        # Only add the suffix if the label does not end in
                        # punctuation.
                        if self.label_suffix:
                            if label[-1] not in ':?.!':
                                label += self.label_suffix
                        label = bf.label_tag(label) or ''
                    else:
                        label = ''
                    if field.help_text:
                        help_text = help_text_html % force_unicode(field.help_text)
                    else:
                        help_text = u''
                    output.append(normal_row % {'errors': force_unicode(bf_errors), 'label': force_unicode(label), 'field': unicode(bf), 'help_text': help_text})

        if top_errors:
            output.insert(0, error_row % force_unicode(top_errors))
        if hidden_fields: # Insert any hidden fields in the last row.
            str_hidden = u''.join(hidden_fields)
            if output:
                last_row = output[-1]
                # Chop off the trailing row_ender (e.g. '</td></tr>') and
                # insert the hidden fields.
                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(u'\n'.join(output))
Example #19
0
    def render_label(self, form):
        if isinstance(self.label, tuple):
            contents, name = self.label
        else:
            contents, name = None, self.label

        try:
            field = form.fields[name]
        except KeyError:
            return ''

        bf = BoundField(form, field, name)
        self.required = bf.field.required

        return bf.label_tag(contents)
Example #20
0
    def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
        # Customized to handle special case for reCaptcha forms (not rendering remote_ip field)
        "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 = BoundField(self, field, name)
            bf_errors = self.error_class([conditional_escape(error) for error in bf.errors]) # Escape and cache in local variable.
            if not bf.is_hidden:
                # 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_unicode(bf_errors))

                if bf.label:
                    label = conditional_escape(force_unicode(bf.label))
                    # Only add the suffix if the label does not end in
                    # punctuation.
                    if self.label_suffix:
                        if label[-1] not in ':?.!':
                            label += self.label_suffix
                    label = bf.label_tag(label) or ''
                else:
                    label = ''

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

                output.append(normal_row % {
                    'errors': force_unicode(bf_errors),
                    'label': force_unicode(label),
                    'field': unicode(bf),
                    'help_text': help_text,
                    'html_class_attr': html_class_attr
                })

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

        return mark_safe(u'\n'.join(output))
Example #21
0
    def as_input_field(self):
        "Helper function for rendering each form field as submittable input element"
        if self.fields['answer'].required:
            self.fields['answer'].widget.attrs.update({'required': 'true'})
        bound_fields = [
            BoundField(self, field, name)
            for name, field in self.fields.items()
        ]
        c = Context(dict(form=self, bound_fields=bound_fields))
        t = Template('''
				<li id="bar_{{ form.question.id }}">
					<div class="item_header">
						<span id="qLabel_{{ form_pair.q_id }}" class="qlabel"> {{ form.answer.label_tag }}</span>
					</div>
					<div class="options">
						{{ form.answer }} 
						{% if form.errors %}<span>{{form.answer.errors}}</span>{% endif %}
						{% if form.question.hint %}
							<span class="helpText clear">Hint: {{ form.question.hint }}</span>
						{% else %}
							<br class="clear" />
						{% endif %}	
					</div>
				</li>
			''')
        return t.render(c)
Example #22
0
def render_field(field, form, template="uni_form/field.html", labelclass=None):
    if not isinstance(field, str):
        return field.render(form)

    try:
        field_instance = form.fields[field]
    except KeyError:
        if not FAIL_SILENTLY:
            raise Exception("Could not resolve form field '%s'." % field)
        else:
            field_instance = None
    if field_instance == None and FAIL_SILENTLY:
        bound_field = None
        html = ''
    else:
        bound_field = BoundField(form, field_instance, field)
        html = render_to_string(template, {
            'field': bound_field,
            'labelclass': labelclass
        })
    if not hasattr(form, 'rendered_fields'):
        form.rendered_fields = []
    if not field in form.rendered_fields:
        form.rendered_fields.append(field)
    else:
        if not FAIL_SILENTLY:
            raise Exception("A field should only be rendered once: %s" % field)
    return html
Example #23
0
    def repr(self):
        criteria = []

        header = ('%s' % self.options.urlname_prefix)

        for name, field in self.form.fields.items():
            bf = BoundField(self.form, field, name)

            repr = bf.field.repr(bf.data)
            if repr:
                repr = '%s %s' % (_(bf.label), repr)
                criteria.append(repr)

        if criteria:
            str = header + " with "
        else:
            return header + "."

        for c in criteria[:-1]:
            str += "%s, " % c

        for c in criteria[-1:]:
            str += c

        str += '.'

        return str
Example #24
0
def test_crispy_addon(settings):
    test_form = SampleForm()
    field_instance = test_form.fields['email']
    bound_field = BoundField(test_form, field_instance, 'email')

    if settings.CRISPY_TEMPLATE_PACK == 'bootstrap':
        # prepend tests
        assert "input-prepend" in crispy_addon(bound_field, prepend="Work")
        assert "input-append" not in crispy_addon(bound_field, prepend="Work")
        # append tests
        assert "input-prepend" not in crispy_addon(bound_field, append="Primary")
        assert "input-append" in crispy_addon(bound_field, append="Secondary")
        # prepend and append tests
        assert "input-append" in crispy_addon(bound_field, prepend="Work", append="Primary")
        assert "input-prepend" in crispy_addon(bound_field, prepend="Work", append="Secondary")
    elif settings.CRISPY_TEMPLATE_PACK == 'bootstrap3':
        assert "input-group-addon" in crispy_addon(bound_field, prepend="Work", append="Primary")
        assert "input-group-addon" in crispy_addon(bound_field, prepend="Work", append="Secondary")
    elif settings.CRISPY_TEMPLATE_PACK == 'bootstrap4':
        assert "input-group-text" in crispy_addon(bound_field, prepend="Work", append="Primary")
        assert "input-group-text" in crispy_addon(bound_field, prepend="Work", append="Secondary")

    # errors
    with pytest.raises(TypeError):
        crispy_addon()
    with pytest.raises(TypeError):
        crispy_addon(bound_field)
Example #25
0
    def render(self, form):
        fieldoutput = u''
        errors = u''
        helptext = u''
        count = 0
        for field in self.fields:
            fieldoutput += render_field(field, form,
                                        'uni_form/multifield.html',
                                        self.label_class)
            try:
                field_instance = form.fields[field]
            except KeyError:
                raise Exception("Could not resolve form field '%s'." % field)
            bound_field = BoundField(form, field_instance, field)
            auto_id = bound_field.auto_id
            for error in bound_field.errors:
                errors += u'<p id="error_%i_%s" class="errorField">%s</p>' % (
                    count, auto_id, error)
                count += 1
            if bound_field.help_text:
                helptext += u'<p id="hint_%s" class="formHint">%s</p>' % (
                    auto_id, bound_field.help_text)

        if errors:
            self.css += u' error'

        output = u'<div class="%s">\n' % self.div_class
        output += errors
        output += self.label_html
        output += u'<div class="multiField">\n'
        output += fieldoutput
        output += u'</div>\n'
        output += helptext
        output += u'</div>\n'
        return output
Example #26
0
    def test_crispy_addon(self):
        test_form = TestForm()
        field_instance = test_form.fields['email']
        bound_field = BoundField(test_form, field_instance, 'email')

        if self.current_template_pack == 'bootstrap':
            # prepend tests
            self.assertIn("input-prepend",
                          crispy_addon(bound_field, prepend="Work"))
            self.assertNotIn("input-append",
                             crispy_addon(bound_field, prepend="Work"))
            # append tests
            self.assertNotIn("input-prepend",
                             crispy_addon(bound_field, append="Primary"))
            self.assertIn("input-append",
                          crispy_addon(bound_field, append="Secondary"))
            # prepend and append tests
            self.assertIn(
                "input-append",
                crispy_addon(bound_field, prepend="Work", append="Primary"))
            self.assertIn(
                "input-prepend",
                crispy_addon(bound_field, prepend="Work", append="Secondary"))
        elif self.current_template_pack == 'bootsrap3':
            self.assertIn(
                "input-group-addon",
                crispy_addon(bound_field, prepend="Work", append="Primary"))
            self.assertIn(
                "input-group-addon",
                crispy_addon(bound_field, prepend="Work", append="Secondary"))

        # errors
        with self.assertRaises(TypeError):
            crispy_addon()
            crispy_addon(bound_field)
Example #27
0
    def formatted_fieldset(self):

        if not hasattr(self, '_formatted_fieldset'):

            fieldsets = self.fieldsets

            formatted_fieldsets = []

            for fieldset in fieldsets:

                formatted_fieldset = {
                    'title': fieldset[0],
                    'classes': fieldset[1].get('classes', None),
                }

                fields = SortedDict()

                for field in fieldset[1].get('fields', []):
                    field_cls = self.fields.get(field, None)

                    fields[field] = BoundField(form=self,
                                               field=field_cls,
                                               name=field)

                formatted_fieldset['fields'] = fields

                formatted_fieldsets.append(formatted_fieldset)

            self._formatted_fieldset = formatted_fieldsets

        return self._formatted_fieldset
Example #28
0
def fieldholder(context: Dict,
                field: forms.BoundField,
                fieldholder_class="",
                horizontal: Optional[bool] = None,
                label_tag: Optional[str] = None,
                label: Optional[str] = None,
                **kwargs):
    fieldholder_class = fieldholder_class.strip()
    if horizontal is None and context.get("horizontal") or horizontal:
        fieldholder_class = ("fieldholder--horizontal " +
                             fieldholder_class).strip()

    suppress_errors = kwargs["suppress_errors"] = kwargs.get(
        "suppress_errors", context.get("suppress_errors", False))
    classes = _add_error_class(fieldholder_class, field, suppress_errors)

    if label_tag is None and label is not None:
        label_tag = format_html(
            '<label for="{id_for_label}" title="{title_label}">{label}</label>',
            id_for_label=field.id_for_label,
            title_label=strip_tags(label),
            label=label,
        )
    return render_to_string(
        "form_tags/fieldholder.html",
        {
            "field":
            fieldwrapper(field, **kwargs),
            "label":
            label_tag if label_tag is not None else field.label_tag(
                attrs={"title": strip_tags(field.label)}),
            "fieldholder_class":
            classes,
        },
    )
Example #29
0
 def as_template(self):
     "Helper function for fieldsting fields data from form."
     bound_fields = [BoundField(self, field, name) \
                   for name, field in self.fields.items()]
     c = Context(dict(form=self, bound_fields=bound_fields))
     t = loader.get_template('forms/form.html')
     return t.render(c)
Example #30
0
    def as_template(self):
        bound_fields = [
            BoundField(self, field, name)
            for name, field in self.fields.items()
        ]
        ctxt_dict = dict(form=self, bound_fields=bound_fields)
        ctxt_dict.update(csrf(self.request))
        c = Context(ctxt_dict)
        t = Template('''
		<li class="sortable_item" id="bar_{{ form.question.id }}">
			<div class="item_header"> 
			<span id="qn_attr" class="icon">
			<a href="{% url update_field form_id=form.survey.id question_id=form.question.id %}" id="updlstItem{{ form.question.id }}" class="updField">
			<img class="icon_button" src="/form_media/images/edit.png"/></a>
			<form class="delete icon_button" method="POST" action="{% url delete_field form_id=form.survey.id %}" id="dellstItem{{ form.question.id }}" class="delField">
				<input type="hidden" name="question_id" value="{{form.question.id}}" />
				<input type="submit" name="delete" value="" style="border:none; background:url('/form_media/images/delete.gif') no-repeat scroll 0 0 transparent"/>
				{% csrf_token %}
			</form>
			<img src="/form_media/images/arrow.png" alt="move" width="16" height="16" class="icon_button handle" />
			</span>
			</div>
			<div class="section">
			<span class="title" >{{ form.answer.label_tag }}</span><br />
			<span class="sub-title">{{ form.question.hint }}</span>
			</div>
		</li>
			''')
        return t.render(c)
Example #31
0
 def as_hidden(self):
     output, hidden_fields = [], []
     for name, field in self.fields.items():
         field.widget = HiddenInput({'readonly': 'readonly'})
         bf = BoundField(self, field, name)
         output.append(unicode(bf))
     return mark_safe(u'\n'.join(output))
Example #32
0
    def __init__(self, *args, **kwargs):
        # Dynamically add the fields for IM providers / external services
        if 'openid' in kwargs:
            self.openid = True
            kwargs.pop('openid')
        else:
            self.openid = False

        super(SignupForm, self).__init__(*args, **kwargs)

        if not self.openid:
            self.fields['password1'].required = True
            self.fields['password2'].required = True

        self.service_fields = []
        for shortname, name, icon in SERVICES:
            field = forms.URLField(max_length=255, required=False, label=name)
            self.fields['service_' + shortname] = field
            self.service_fields.append({
                'label':
                name,
                'shortname':
                shortname,
                'id':
                'service_' + shortname,
                'icon':
                icon,
                'field':
                BoundField(self, field, 'service_' + shortname),
            })

        self.improvider_fields = []
        for shortname, name, icon in IMPROVIDERS:
            field = forms.CharField(max_length=50, required=False, label=name)
            self.fields['im_' + shortname] = field
            self.improvider_fields.append({
                'label':
                name,
                'shortname':
                shortname,
                'id':
                'im_' + shortname,
                'icon':
                icon,
                'field':
                BoundField(self, field, 'im_' + shortname),
            })
Example #33
0
 def __getitem__(self, name):
     "Returns a BoundField with the given name."
     try:
         field = self.fields[name]
     except KeyError:
         raise KeyError('Key %r not found in Form' % name)
     self._field_queryset(field, name)  # nouveau queryset
     return BoundField(self, field, name)
Example #34
0
 def _bind_field(self, name, field):
     bound = BoundField(self, field, name)
     bound.metadata = self._prepare_field_metadata(name, field)
     
     value = self._get_field_value(bound)
     if isinstance(field, forms.ModelMultipleChoiceField):
         if value:
             ref = [field.queryset.get(pk=val) for val in value if val]
         else:
             ref = []
     elif isinstance(field, forms.ModelChoiceField):
         ref = (field.queryset.get(pk=value) if value else None)
     else:
         ref = value
         
     bound.initial_value = {'value': value, 'ref': ref}
     return bound
Example #35
0
def format_as_pml(self):
    output = []
    for name,  field in self.fields.items():
        bf = BoundField(self, field, name)

        text_field_type = 'Text'

        if(isinstance(field, IntegerField)):
            text_field_type = 'num'

        field_str = ('<TEXT position="ABOVE">%(label_name)s</TEXT><FIELD name="%(field_name)s" type="%(text_field_type)s" default="%(field_value)s"/><br/>'
                % {
                  'label_name': conditional_escape(force_unicode(bf.label)),
                  'field_name': bf.html_name,
                  'field_value': bf.value()  if bf.value() != None  else '',
                  'text_field_type': text_field_type
                  })
        if(isinstance(field, BooleanField)):
            default = bf.value()  if bf.value() != None  else ''

            field_str = ('''<CHOICE-GROUP type="radio" name="%(field_name)s">
            <TEXT>%(label_name)s</TEXT>
            <CHOICE value="True" %(default_true)s>Yes</CHOICE>
            <CHOICE value="False" %(default_false)s>No</CHOICE>
            </CHOICE-GROUP>''' %
            {
                'default_true':  'checked="true"' if default else '',
                'default_false':  'checked="true"' if not default else '',
                'label_name': conditional_escape(force_unicode(bf.label)),
                'field_name': bf.html_name,
                'field_value': bf.value()  if bf.value() != None  else ''
            })

        output.append(field_str)
    return mark_safe(u'\n'.join(output))
Example #36
0
 def _convert_to_bound_fields(form, i18n_field_names):
     bound_fields = []
     for field_name in i18n_field_names:
         local_fields = field_mapping[field_name]
         for local_name in local_fields:
             local_field = form_instance.fields[local_name]
             bound_field = BoundField(form, local_field, local_name)
             bound_fields.append(bound_field)
     return bound_fields
Example #37
0
 def as_template(self):
     "Helper function for fieldsting fields data from form."
     bound_fields = [BoundField(self, field, name) for name, field in self.fields.items()]
     c = Context(dict(form = self, bound_fields = bound_fields))
     # TODO: check for template ... if template does not exist
     # we could just get_template_from_string to some default
     # or we could pass in the template name ... whatever we want
     # import pdb; pdb.set_trace()
     t = loader.get_template('forms/form.html')
     return t.render(c)
Example #38
0
def field_template(name, field, form_or_model, attrs={}, suffix=""):
    label = ""
    value = ""
    output = ""
    td_attrs = {}

    if isinstance(field, models.Field):
        label = u'%s' % field.verbose_name
        value = field_to_string(field, form_or_model)

    elif isinstance(field, forms.Field):
        bf = BoundField(form_or_model, field, name)
        label = u'%s' % bf.label_tag()
        value = u'%s' % bf
        if bf.help_text:
            value += '<br/>\n<span class="help_text">%s</span>' % (u'%s' % bf.help_text)
        if bf._errors():
            value += '<br/>\n<ul class="errorlist">\n'
            for error in bf._errors():
                value += '\t<li>%s</li>\n' % error
            value += '</ul>\n'
        css_classes = bf.css_classes()
        if css_classes:
            td_attrs['class'] = css_classes

    else:
        name = _(pretty_name(name).lower())
        label = u'%s' % name.capitalize()
        if callable(field):
            value = value_to_string(field())
        else:
            value = value_to_string(field)
    
    td_attrs.update(attrs)

    if label and value:
        output += ("\t\t<th>%s</th>\n" % (label[0].capitalize() + label[1:]))
        output += "\t\t<td%s>\n" % flatatt(td_attrs)
        output += "\t\t\t%s%s\n" % (value, suffix)
        output += "\t\t</td>\n"

    return output
Example #39
0
 def __getitem__(self, name):
     """
     Returns a BoundField or UploaderBoundField with the given name.
     """
     try:
         field = self.fields[name]
     except KeyError:
         raise KeyError('Key %r not found in Form' % name)
     if isinstance(field, UploaderField):
         return UploaderBoundField(self, field, name)
     return BoundField(self, field, name)
Example #40
0
def getfield(form, name):
    """
    Return the named boundfield from the form.

    Usage: {{ form|getfield:name }}
    """
    try:
        field = form.fields[name]
    except KeyError:
        raise KeyError('Key %r not found in Form' % name)
    return BoundField(form, field, name)
Example #41
0
 def as_dictionary(self):
     output = {}
     for field in self.fields.keys():
         bf = BoundField(self, self.fields[field], field)
         if not self.is_bound:
             data = self.initial.get(bf.name, bf.field.initial)
             if callable(data):
                 data = data()
         else:
             data = bf.data
         output[field] = data
     return output
Example #42
0
def uka_form_row_stacked(element, errors='', classes=''):
    class_margin_top = ''
    label = BoundField.label_tag(element, "", {'class': 'uk-form-label'})
    if errors:
        classes_tmp = classes + ' uk-form-danger'
        classes = classes_tmp
        class_margin_top = 'uk-margin-top'
    element = element.as_widget(attrs={'class': classes})  # to remove (be done in js)
    html_error = format_html('<div class="uk-text-danger {}">{}</div>', class_margin_top, errors)
    html = format_html(
        '<div class="uk-form-row">{}<div class="uk-form-controls">{}</div>{}</div>', label, element, html_error)
    return html
def field_(self, name):
    """
    Get a form field starting with _.
    Taken near directly from Djano > forms.
    Returns a BoundField with the given name.
    """
    try:
        field = self.fields[name]
    except KeyError:
        raise KeyError("Key %r not found in '%s'" %
                       (name, self.__class__.__name__))
    return BoundField(self, field, name)
Example #44
0
def test_crispy_field_and_class_converters():
    template = Template("""
        {% load crispy_forms_field %}
        {% crispy_field testField 'class' 'error' %}
    """)
    test_form = SampleForm()
    field_instance = test_form.fields['email']
    bound_field = BoundField(test_form, field_instance, 'email')

    c = Context({'testField': bound_field})
    html = template.render(c)
    assert 'error' in html
    assert 'inputtext' in html
Example #45
0
def bootstrapped3(self):
    top_errors = self.non_field_errors()
    output, hidden_fields = [], []

    for name, field in self.fields.items():
        bf = BoundField(self, field, name)
        
        bf_errors = self.error_class([conditional_escape(error) for error in bf.errors])
        
        error_text = bf.errors.as_text()[2:]
        
        if bf.is_hidden:
            if bf_errors:
                top_errors.extend([u'(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors])
            hidden_fields.append(unicode(bf))
        else:
            if bf.label:
                # Рендерялка label
                label = bf.label_tag(conditional_escape(force_unicode(bf.label)), attrs={'class': "control-label"}) or ''
            else:
                label = ''
    
            if field.help_text:
                help_text = help_text_html % force_unicode(field.help_text)
            else:
                help_text = u''
            
            self.bw_bf = bf
            self.bw_label = force_unicode(label)
            self.bw_help_text = help_text
            self.bw_css_classes = bf.css_classes()
            
            self.bw_error_text = force_unicode(error_text)
            self.bw_help_text = help_text
            
            output.append(bootstrap_widget(self, unicode(field.__class__.__name__)))
            
    return mark_safe(u'\n'.join(output))
Example #46
0
 def as_widget(self, widget=None, attrs=None, only_initial=False):
     """Renders a field and adds dlgi styles if appropriate."""
     if not widget:
         widget = self.field.widget
     if isinstance(widget, widgets.Input):
         if not attrs:
             # Maintain existing style classes:
             class_attrs = set((
                 self.field.widget.attrs.get('class') or '').split(' '))
             # anf add those for general layout:
             class_attrs.add('input-text')
             attrs = {'class': ' '.join(class_attrs)}
     return BaseBoundField.as_widget(self, widget=widget, attrs=attrs,
                                 only_initial=only_initial)
Example #47
0
def html_output(form, 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 = form.non_field_errors() # Errors that should be displayed above all fields.
    output, hidden_fields = [], []

    for name, field in form.fields.items():
        html_class_attr = ''
        bf = BoundField(form, field, name)
        bf_errors = form.error_class([conditional_escape(error) for error in bf.errors]) # Escape and cache in local variable.
        if bf.is_hidden:
            if bf_errors:
                top_errors.extend([u'(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors])
            hidden_fields.append(unicode(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:
                output.append(error_row % \
                              '{%% if form.%s.errors %%}{%% for error in form.%s.errors %%}{{ error }}{%% endfor %%}{%% endif %%}' \
                              % (name, name,))

            output.append(normal_row % {
                'errors': \
                  '{%% if form.%s.errors %%}{%% for error in form.%s.errors %%}{{ error }}{%% endfor %%}{%% endif %%}' \
                  % (name, name,),
                'label': '{{ form.%s.label_tag }}' % (name,),
                'field': '{{ form.%s }}' % (name,),
                'help_text': '',
                'html_class_attr': html_class_attr
            })

    if top_errors:
        output.insert(0,
                      r'{% if form.errors %}{% for field, error in form.errors %}(Hidden field {{ field }}) {{ error }}{% endfor %}{% end if %}'
        )

    if hidden_fields: # Insert any hidden fields in the last row.
        str_hidden = u'{%% for field in form.hidden_fields %%}{{ field }}{%% endfor %%}'
        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 u'\n'.join(output)
Example #48
0
def render_form(form, include=None, exclude=None, ordering=None):
    """
    Renders a form using easily stylable, valid XHTML.
    
    Can accept inclusion fields, exclusion fields, and field ordering arguments.
    
    <code>
    {{ myform|render_form(('my', 'fields', 'to', 'include')) }}
    </code>
    """
    kwargs = dict(include=include, exclude=exclude, ordering=ordering)
    normal_row = u'<div id="%(row_id)s" class="formRow %(class_names)s">%(label)s <span class="formField">%(field)s</span>%(help_text_wrapped)s%(errors)s</div>'        
    inline_row = u'<div id="%(row_id)s" class="formRow %(class_names)s"><label><span class="formField">%(field)s</span> %(help_text)s</label>%(errors)s</div>'
    error_row = u'<div class="formRow fInputErrorRow">%s</div>'
    class_prefix = 'f'
    row_ender = '</div>'

    top_errors = form.non_field_errors() # Errors that should be displayed above all fields.
    output, hidden_fields = [], []
    if kwargs['include']:
        if exclude:
            _fields = ((name, field) for name, field in form.fields.iteritems() if name in kwargs['include'] and name not in kwargs['exclude'])
        else:
            _fields = ((name, field) for name, field in form.fields.iteritems() if name in kwargs['include'])
    elif kwargs['exclude']:
        _fields = ((name, field) for name, field in form.fields.iteritems() if name not in kwargs['exclude'])
    else:
        _fields = form.fields.iteritems()
    # Set ordering to include fields if it doesn't exist.
    if not kwargs['ordering'] and include:
        kwargs['ordering'] = include
    if kwargs['ordering']:
        _fields = tuple(_fields)
        _fields_dict = dict(_fields)
        _fields = ((f, _fields_dict[f]) for f in kwargs['ordering'] if f in _fields_dict)

    for name, field in _fields:
        bf = BoundField(form, field, name)
        bf_errors = form.error_class(bf.errors) # Escape and cache in local variable.
        if bf.is_hidden:
            if bf_errors:
                top_errors.extend([u'(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors])
            hidden_fields.append(unicode(bf))
        else:
            if bf.label:
                label_text = escape(force_unicode(bf.label))
                # Only add the suffix if the label does not end in
                # punctuation.
                if form.label_suffix:
                    if label_text[-1] not in ':?.!':
                        label_text += form.label_suffix
            else:
                label_text = ''

            params = {
                'errors': force_unicode(bf_errors),
                'row_id': 'id_%s_wrap' % (name),
                'label': force_unicode(bf.label_tag(label_text) or ''),
                'field': bf,
                'help_text': force_unicode(field.help_text or ''),
                'help_text_wrapped': field.help_text and '<small class="helptext">%s</small>' % field.help_text or '',
            }

            widget = unicode(bf.field.widget.__class__.__name__)
            class_names = [class_prefix + widget + 'Row']
            if field.required:
                class_names.append(class_prefix + 'Required')
            if bf.errors:
                class_names.append(class_prefix + 'Errors')
            params['class_names'] = ' '.join(class_names)

            # XXX: Bad Hack
            if widget in ('CheckboxInput', 'RadioInput') and params['help_text']:
                output.append(inline_row % params)
            else:
                output.append(normal_row % params)
    if top_errors:
        output.insert(0, error_row % force_unicode(top_errors))
    if hidden_fields: # Insert any hidden fields in the last row.
        str_hidden = u''.join(hidden_fields)
        if output:
            last_row = output[-1]
            # Chop off the trailing row_ender (e.g. '</td></tr>') and
            # insert the hidden fields.
            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 Markup(u'\n'.join(output))
Example #49
0
    def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row, checkbox_row=''):
        """
        Helper function for outputting HTML. Used by as_table(), as_ul(), as_p().
        modified for Engineclub to wrap checkbox in label for Foundation markup with label to right.
        Hopefully a temporary hack until Django sorts out its form handling.
        """
        top_errors = self.non_field_errors() # Errors that should be displayed above all fields.
        output, hidden_fields = [], []

        for name, field in self.fields.items():
            
            # MOD FOR ENGINECLUB
            checkbox = isinstance(field.widget, CheckboxInput)

            html_class_attr = ''
            bf = BoundField(self, field, name)
            bf_errors = self.error_class([conditional_escape(error) for error in bf.errors]) # Escape and cache in local variable.
            if bf.is_hidden:
                if bf_errors:
                    top_errors.extend([u'(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors])
                hidden_fields.append(unicode(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_unicode(bf_errors))

                if bf.label:
                    label = conditional_escape(force_unicode(bf.label))
                    # Only add the suffix if the label does not end in
                    # punctuation.
                    if self.label_suffix:
                        if label[-1] not in ':?.!':
                            label += self.label_suffix

                    # MOD FOR ENGINECLUB
                    if not checkbox:
                        label = bf.label_tag(label) or ''
                else:
                    label = ''

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

                # MOD FOR ENGINECLUB
                output_row = checkbox_row if checkbox else normal_row

                output.append(output_row % {
                    'errors': force_unicode(bf_errors),
                    'label': force_unicode(label),
                    'field': unicode(bf),
                    'help_text': help_text,
                    'html_class_attr': html_class_attr
                })

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

        if hidden_fields: # Insert any hidden fields in the last row.
            str_hidden = u''.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(u'\n'.join(output))
Example #50
0
 def get_filters_as_options(self):
     fields = {}
     for name, filter_ in self.filters.iteritems():
         bf = BoundField(self.form, filter_.field, name)
         fields[name] = {'label': bf.label, 'label_tag': bf.label_tag(), 'widget': bf.__unicode__(), 'filter': filter_.__class__.__name__}
     return fields
Example #51
0
    def as_bootstrap_horizontal(self):
        """
        Returns this form rendered as HTML <div class="control-group">s 
            -- excluding the <fieldset></fieldset>.
        Also, it provides the non field alerts before fields.
        This form will be bootstrap 2.0 horizonal forms:
            http://twitter.github.com/bootstrap/base-css.html?#forms

        In template file, you can render a formset like following:
        <form class="form-horizontal" action="" method="post">
          <fieldset>
            {{ form.as_bootstrap_horizonal }}
            <div class="form-actions">
              <button type="submit" class="btn btn-primary">Submit</button>
            </div>
          </fieldset>
        </form>
        """
        output, hidden_fields = [], []
        error_row = u'<div class="alert alert-error alert-login">%s</div>'
        # self.non_field_errors returns <ul class="errorlist">
        top_errors = self.non_field_errors()

        for name, field in self.fields.items():
            bf = BoundField(self, field, name)
            if bf.is_hidden:
                # for hidden fields
                if bf.errors:
                    # for hidden fields, add errors to top_errors
                    hidden_errors = self.error_class([conditional_escape(error) for error in bf.errors])
                    top_errors.extend([u'(Hidden field %s) %s' % (name, force_unicode(e)) for e in hidden_errors])
                hidden_fields.append(unicode(bf))
            else:
                # for control-group tag
                if bf.errors:
                    output.append(u'<div class="control-group error">')
                else:
                    output.append(u'<div class="control-group">')

                # for label
                output.append(bf.label_tag(attrs={'class': 'control-label'}))
                # for controls div tag
                output.append(u'<div class="controls">')
                # input tag, textarea tag, etc...
                if isinstance(field.widget,CheckboxInput):
                    output.append(u'<label class="checkbox">')
                    output.append(unicode(bf))
                    if field.help_text:
                        output.append(force_unicode(field.help_text))
                    output.append(u'</label>')
                else: 
                    output.append(unicode(bf))
                    if field.help_text:
                        output.append(u'<p class="help-block">%s</p>' % force_unicode(field.help_text))

                # for error
                if bf.errors:
                    output.append(u'<ul class="errorlist help-block">')
                    for error in bf.errors:
                        output.append(u'<li>%s</li>' % conditional_escape(force_unicode(error)))
                    output.append(u'</ul>')

                # for controls div tag
                output.append(u'</div><!-- /controls -->')
                # for control-group div tag
                output.append(u'</div><!-- /control-group -->')

        # insert top error messages
        if top_errors:
            output.insert(0, error_row % force_unicode(top_errors))

        # append hidden fields to the end of the output
        if hidden_fields:
            for hf in hiddenfields:
                output.append(hf)

        return mark_safe(u'\n'.join(output))
Example #52
0
 def as_hidden(self):
     output = []
     for name, field in self.fields.items():
         bf = BoundField(self, field, name)
         output.append(bf.as_hidden())
     return u'\n'.join(output)
Example #53
0
    def render_field(self, field):

        ''' Render a named field to HTML. '''

        try:
            field_instance = self.fields[field]
        except KeyError:
            raise NoSuchFormField("Could not resolve form field '%s'." % field)

        bf = BoundField(self, field_instance, field)

        output = ''

        bf_errors = self.error_class([escape(error) for error in bf.errors])

        if bf.is_hidden:

            # If the field is hidden, add it at the top of the form

            self.prefix_r.append(unicode(bf))

            # If the hidden field has errors, append them to the top_errors
            # list which will be printed out at the top of form

            if bf_errors:
                self.top_errors.extend(bf.errors)
        else:

            # Find field + widget type css classes
            css_class = type(field_instance).__name__ + " " + \
                        type(field_instance.widget).__name__

            # Add an extra class, Required, if applicable
            if field_instance.required:
                css_class += " Required"

            if field_instance.help_text:
                # The field has a help_text, construct <span> tag
                help_text = escape(field_instance.help_text)
                help_text = '<span class="help_text">%s</span>' % help_text

            else:
                help_text = u''

            field_hash = {'field':mark_safe(field),
                          'class':mark_safe(css_class),
                          'label':mark_safe(bf.label and bf.label_tag(bf.label) or ''),
                          'help_text':mark_safe(help_text),
                          'field':field_instance,
                          'bf':mark_safe(unicode(bf)),
                          'bf_raw':bf,
                          'errors':mark_safe(bf_errors),
                          'field_type':mark_safe(field.__class__.__name__)}

            if self.custom_fields.has_key(field):
                template = get_template(self.custom_fields[field])
            else:
                template = select_template([
                    os.path.join(self.template_base,'field_%s.html' % field_instance.__class__.__name__.lower()),
                    os.path.join(self.template_base,'field_default.html')]
                                           )

            # Finally render the field
            output = template.render(Context(field_hash))

        return mark_safe(output)
Example #54
0
    def render_field(self, field):

        ''' Render a named field to HTML. '''

        try:
            field_instance = self.fields[field]
        except KeyError:
            raise NoSuchFormField("Could not resolve form field '%s'." % field)

        bf = BoundField(self, field_instance, field)

        output = ''

        if bf.errors:

            # If the field contains errors, render the errors to a <ul>
            # using the error_list helper function.
            bf_errors = error_list([escape(error) for error in bf.errors])

        else:
            bf_errors = ''

        if bf.is_hidden:

            # If the field is hidden, add it at the top of the form

            self.prefix.append(unicode(bf))

            # If the hidden field has errors, append them to the top_errors
            # list which will be printed out at the top of form
            
            if bf_errors:
                self.top_errors.extend(bf.errors)

        else:

            # Find field + widget type css classes
            css_class = type(field_instance).__name__ + " " + \
                        type(field_instance.widget).__name__

            # Add an extra class, Required, if applicable
            if field_instance.required:
                css_class += " Required"

            if bf.label:

                # The field has a label, construct <label> tag
                label = escape(bf.label)
                label = bf.label_tag(label) or ''

            else:
                label = ''

            if field_instance.help_text:

                # The field has a help_text, construct <span> tag
                help_text = escape(field_instance.help_text)
                help_text = '<span class="help_text">%s</span>' % help_text

            else:
                help_text = u''

            # Finally render the field
            output = '<div class="field %(class)s">%(label)s%(help_text)s%(errors)s<div class="input">%(field)s</div></div>\n' % \
                     {'class': css_class, 'label': label, 'help_text': help_text, 'errors': bf_errors, 'field': unicode(bf)}

        return output
Example #55
0
def bootstrapped(self):
    """Вывод формы отформатированной в соотвествии со стилями бутстрапа.
       Осторожно!!! Ч0рная магия и запутанный код!
    """

    normal_row = u"""
        <div class="control-group %(has_error)s">
            %(label)s
            <div class="controls">
                %(field)s
                <span class="help-inline">%(errors)s</span>
                <p class="help-block">%(help_text)s</p>
            </div>
        </div>"""
    error_row = u'<li>%s</li>'
    row_ender = u'</div>'
    help_text_html = u' %s'

    top_errors = self.non_field_errors()
    output, hidden_fields = [], []

    for name, field in self.fields.items():
        html_class_attr = ''
        
        bf = BoundField(self, field, name)
        bf_errors = self.error_class([conditional_escape(error) for error in bf.errors])
        error_text = bf.errors.as_text()[2:]
        has_error = ''
        if error_text:
            has_error = ' error'

        if bf.is_hidden:
            if bf_errors:
                top_errors.extend([u'(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors])
            hidden_fields.append(unicode(bf))
        else:

            css_classes = bf.css_classes()
            if css_classes:
                html_class_attr = ' class="%s"' % css_classes

            if bf.label:
                label = conditional_escape(force_unicode(bf.label))

                if self.label_suffix:
                    if label[-1] not in ':?.!':
                        label += self.label_suffix
                label = bf.label_tag(label, attrs={'class': "control-label"}) or ''
            else:
                label = ''

            if field.help_text:
                help_text = help_text_html % force_unicode(field.help_text)
            else:
                help_text = u''
                
            output.append(normal_row % {
                'has_error': force_unicode(has_error),
                'errors': force_unicode(error_text),
                'label': force_unicode(label),
                'field': unicode(bf),
                'help_text': help_text,
                'html_class_attr': html_class_attr
            })

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

    if hidden_fields:
        str_hidden = u''.join(hidden_fields)
        if output:
            last_row = output[-1]

            if not last_row.endswith(row_ender):
                last_row = (normal_row % {'errors': '', 'label': '',
                                          'field': '', 'help_text':'', 'has_error': has_error,
                                          'html_class_attr': html_class_attr})
                output.append(last_row)
            output[-1] = last_row[:-len(row_ender)] + str_hidden + row_ender
        else:
            output.append(str_hidden)
    return mark_safe(u'\n'.join(output))
Example #56
0
    def my_html_output(self, normal_row, error_row, row_ender,
                       help_text_html, errors_on_separate_row, cols):
        """
        Helper function for outputting HTML.
        Used by as_table(), as_ul(), as_p().
        """
        # Errors that should be displayed above all fields.
        top_errors = self.non_field_errors()
        output, hidden_fields = [], []
        idx = 1

        for name, field in self.fields.items():
            bf = BoundField(self, field, 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([u'(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors])
                hidden_fields.append(unicode(bf))
            else:
                if errors_on_separate_row and bf_errors:
                    output.append(error_row % force_unicode(bf_errors))
                if bf.label:
                    label = conditional_escape(force_unicode(bf.label))
                    # Only add the suffix if the label does not end in
                    # punctuation.
                    if self.label_suffix:
                        if label[-1] not in ':?.!':
                            label += self.label_suffix
                    label = bf.label_tag(label) or ''
                else:
                    label = ''
                if field.help_text:
                    help_text = help_text_html % force_unicode(field.help_text)
                else:
                    help_text = u''

                normal_row2 = normal_row
                if idx == 1:
                    normal_row2 = "<tr>%s" % (normal_row,)
                elif idx >= cols:
                    idx = 0
                    normal_row2 = "%s</tr>" % (normal_row,)

                idx += 1
                output.append(normal_row2 % {
                              'errors': force_unicode(bf_errors),
                              'label': force_unicode(label),
                              'field': unicode(bf),
                              'help_text': help_text})

        if idx < cols:
            output.append("<td></td>" * (cols - idx) + "</tr>")

        if top_errors:
            output.insert(0, error_row % force_unicode(top_errors))
        if hidden_fields:  # Insert any hidden fields in the last row.
            str_hidden = u''.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': ''}
                    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(u'\n'.join(output))
Example #57
0
    def render(self, context):
        form = context[self.arg]

        #TODO: cache
        #if adv_mode is None:
        adv_mode = Advanced.objects.order_by('-id')[0].adv_advancedmode
        #request.session['adv_mode'] = adv_mode
        form.advDefault = adv_mode

        if hasattr(form, "_meta") and hasattr(form._meta.model, '_admin'):
            model = form._meta.model
        else:
            model = None

        new_fields = form.fields.keys()
        output, hidden_fields, composed = [], [], {}

        top_errors = form.non_field_errors()
        if top_errors:
            output.append("<tr><td colspan=\"2\">%s</td></tr>" % (
                force_unicode(top_errors),
                ))
        else:
            if form.prefix:
                prefix = form.prefix + "-__all__"
            else:
                prefix = "__all__"
            output.append("""<tr>
<td colspan="2">
<input type="hidden" data-dojo-type="dijit.form.TextBox" name="%s" />
</td></tr>""" % (prefix,))

        if model:
            for label, fields in model._admin.composed_fields:
                for field in fields[1:]:
                    new_fields.remove(field)
                composed[fields[0]] = (label, fields)

        advanced_fields = getattr(form, 'advanced_fields', [])
        for field in new_fields:
            is_adv = field in advanced_fields
            _hide = ' style="display:none;"' if not adv_mode and is_adv else ''
            is_adv = ' class="advancedField"' if is_adv else ''
            if field in composed:
                label, fields = composed.get(field)
                html = u"""<tr><th><label%s>%s</label></th><td>""" % (
                    _hide,
                    label)
                for field in fields:
                    bf = BoundField(form, form.fields.get(field), field)
                    bf_errors = form.error_class(
                        [conditional_escape(error) for error in bf.errors]
                        )
                    html += unicode(bf_errors) + unicode(bf)
                html += u"</td></tr>"
                output.append(html)
            else:
                bf = BoundField(form, form.fields.get(field), field)
                bf_errors = form.error_class(
                    [conditional_escape(error) for error in bf.errors]
                    )
                if bf.is_hidden:
                    hidden_fields.append(unicode(bf))
                else:
                    if bf.help_text:
                        help_text = """<div data-dojo-type="dijit.Tooltip" data-dojo-props="connectId: '%shelp', showDelay: 200">%s</div><img id="%shelp" src="/static/images/ui/MoreInformation_16x16px.png" style="width:16px; height: 16px; cursor: help;" />""" % (bf.auto_id, bf.help_text, bf.auto_id)
                    else:
                        help_text = ""
                    html = u"""<tr%s%s><th>%s</th><td>%s%s %s</td></tr>""" % (
                        is_adv,
                        _hide,
                        bf.label_tag(),
                        bf_errors,
                        bf,
                        help_text,
                        )
                    output.append(html)

        if hidden_fields:
            str_hidden = u''.join(hidden_fields)
            output.append(str_hidden)

        return ''.join(output)
Example #58
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():
            bf = BoundField(self, field, name)
            bf_errors = self.error_class([conditional_escape(error) for error in bf.errors]) # Escape and cache in local variable.
            if bf.is_hidden:
                if bf_errors:
                    top_errors.extend([u'(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors])
                hidden_fields.append(unicode(bf))
            else:
                if errors_on_separate_row and bf_errors:
                    output.append(error_row % force_unicode(bf_errors))
                if bf.label:
                    label = conditional_escape(force_unicode(bf.label))
                    # Only add the suffix if the label does not end in
                    # punctuation.
                    if self.label_suffix:
                        if label[-1] not in ':?.!':
                            label += self.label_suffix
                    # Sets label with an asterisk if this is a obligatory field according to to validation rules
                    if hasattr(self.Meta,'min_required'):
                        if not hasattr(self.Meta,'count'):
                            self.Meta.count = 0
                        if self.Meta.min_required > 0 and self.Meta.count < self.Meta.min_required:
                            if name != 'DELETE':
                                label = label + ' <span class="required_field">(*)</span>'
                    elif trial_validator.field_is_required(self, name):
                        label = label + ' <span class="required_field">(*)</span>'
                    label = bf.label_tag(label) or ''
                else:
                    label = ''


                # Gets the field status for this field to use it as CSS class
                if self.instance:
                    field_status = trial_validator.get_field_status(self, name, self.instance)
                else:
                    field_status = ''

                if field.help_text:
                    help_text = help_text_html % force_unicode(field.help_text)
                else:
                    help_text = u''
                form_name = self.__class__.__name__
                help_record, new = FieldHelp.objects.get_or_create(form=form_name, field=name)

                # Trying to get the translation for help_record
                try:
                    help_object = FieldHelpTranslation.objects.get_translation_for_object(
                        lang=get_language(), model=FieldHelp, object_id=help_record.pk,
                        )
                    help_text = "<div class='help_text'>%s</div>" % (help_object.text,)
                    if help_object.example:
                        help_text = "%s<div class='help_text_example'>%s:<br />%s</div>" % (help_text, _("Example"), help_object.example)

                    if not help_text.strip():
                        help_text = unicode(help_record)
                except (FieldHelpTranslation.DoesNotExist, AttributeError):
                    help_text = "<div class='help_text'>%s</div>" % (help_record.text,)
                    if help_record.example:
                        help_text = "%s<div class='help_text_example'>%s:<br />%s</div>" % (help_text, _("Example"), help_record.example)

                help_text = u'' + force_unicode(help_text)
                help_text = linebreaksbr(help_text_html % help_text)
                output.append(normal_row % {'errors': force_unicode(bf_errors),
                                            'label': force_unicode(label),
                                            'field': unicode(bf),
                                            'help_text': help_text,
                                            'help_id': 'id_%s-help%s' % ((self.prefix or name),help_record.pk),
                                            'field_class': field_status,
                                            'field_name': name,
                                            })

        # if necessary, updates the count of rendered repetitive forms
        if hasattr(self.Meta,'min_required'):
            if hasattr(self.Meta,'count'):
                self.Meta.count = self.Meta.count + 1

        if top_errors:
            output.insert(0, error_row % force_unicode(top_errors))
        if hidden_fields: # Insert any hidden fields in the last row.
            str_hidden = u''.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': '',
                                             'help_id': 'id_%s-help%s' % (self.prefix,help_record.pk),
                                             'issue': '',}
                    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(u'\n'.join(output))
    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():
            bf = BoundField(self, field, name)
            bf_errors = self.error_class([conditional_escape(error) for error in bf.errors]) # Escape and cache in local variable.
            if bf.is_hidden:
                if bf_errors:
                    top_errors.extend([u'(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors])
                hidden_fields.append(unicode(bf))
            else:
                if errors_on_separate_row and bf_errors:
                    output.append(error_row % force_unicode(bf_errors))
                if bf.label:
                    label = conditional_escape(force_unicode(bf.label))
                    # Only add the suffix if the label does not end in
                    # punctuation.
                    if self.label_suffix:
                        if label[-1] not in ':?.!':
                            label += self.label_suffix
                    label = bf.label_tag(label) or ''
                else:
                    label = ''
                if field.help_text:
                    help_text = help_text_html % force_unicode(field.help_text)
                else:
                    help_text = u''
                form_name = self.__class__.__name__
                #import pdb; pdb.set_trace()
                help_record, new = FieldHelp.objects.get_or_create(form=form_name, field=name)
                help_text = help_text + u' ' + force_unicode(help_record)
                help_text = help_text_html % help_text
                field_path = '%s.%s' % (form_name, name)
                issue_text = '%s #%s' % (field_path, self.instance.pk)
                output.append(normal_row % {'errors': force_unicode(bf_errors),
                                            'label': force_unicode(label),
                                            'field': unicode(bf),
                                            'help_text': help_text,
                                            'help_id': 'id_%s-help%s' % ((self.prefix or name),help_record.pk),
                                            'issue': issue_text,})
        if top_errors:
            output.insert(0, error_row % force_unicode(top_errors))
        if hidden_fields: # Insert any hidden fields in the last row.
            str_hidden = u''.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': '',
                                             'help_id': 'id_%s-help%s' % (self.prefix,help_record.pk),
                                             'issue': '',}
                    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(u'\n'.join(output))
Example #60
0
def html_output_alt(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row,
        extra_css_class_attr = "manual_css_classes"):
    "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 list(self.fields.items()):
        html_class_attr = ''
        bf = BoundField(self, field, name)
        bf_errors = self.error_class([conditional_escape(error) for error in bf.errors]) # Escape and cache in local variable.
        if bf.is_hidden:
            if bf_errors:
                top_errors.extend(['(Hidden field %s) extra_css_class_attr%s' % (name, force_text(e)) for e in bf_errors])
            hidden_fields.append(str(bf))
        else:
            # Create a 'class="..."' atribute if the row should have any
            # CSS classes applied.
            css_classes = bf.css_classes(getattr(field, extra_css_class_attr, None))
            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 += 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': str(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))