Beispiel #1
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)
Beispiel #2
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)
Beispiel #3
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))
Beispiel #4
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))
Beispiel #5
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
Beispiel #6
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
Beispiel #7
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))
Beispiel #8
0
def outputhelper(self,
                 normal_row,
                 error_row,
                 row_ender,
                 help_text_html,
                 errors_on_separate_row,
                 separator_html=SEPARATOR_HTML):
    "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.

        # Check that we can get a unicode output of the field (in particular
        # if someone tries to pass bad data to the form
        try:
            unicode(bf)
        except TypeError:
            raise Http404

        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))

        elif bf.field.is_separator():
            output.append(separator_html % {
                'label': conditional_escape(force_unicode(bf.label)),
            })

        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
                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))

    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))
Beispiel #9
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))
Beispiel #10
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))
Beispiel #11
0
    def _html_output_as_dl(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.
        mark_as_required_field = _('mark as required field')
        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 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.
                widget_type = type(field.widget)
                widget_base_type = widget_type.__bases__[0]
                extra_classes = None
                if widget_base_type == widgets.Input:
                    if widget_type == widgets.FileInput:
                        extra_classes = 'input_file'
                    else:
                        extra_classes = 'input_text'
                elif widget_base_type == widgets.Widget:
                    if widget_type == widgets.Select:
                        extra_classes = 'select'
                    elif widget_type == widgets.Textarea:
                        extra_classes = 'textarea'
                    elif widget_type == widgets.CheckboxInput:
                        extra_classes = 'input_checkbox'
                elif widget_base_type == widgets.Select:
                    if widget_type == widgets.RadioSelect:
                        extra_classes = 'input_radio'
                css_classes = bf.css_classes(extra_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))
                    if bf.field.required and (widget_base_type == widgets.Input\
                        or widget_type == widgets.Textarea):
                        label += mark_as_required_field
                    # 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))

        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))
Beispiel #12
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))
Beispiel #13
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))
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)
    def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row, rest_help_text=True, hide_help_text=True):
        "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 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
                    label = bf.label_tag(label) or ''
                else:
                    label = ''

                if field.help_text:
                    help_text = force_unicode(field.help_text)
                    if rest_help_text:
                        try:
                            from django.contrib.markup.templatetags.markup import restructuredtext
                            help_text = restructuredtext(help_text)
                        except ImportError:
                            pass
                    if hide_help_text:
                        # put the help text in a div that the
                        # help_text_hider.js script can find
                        help_text = u"""
                            <div class="help_text">
                              %s
                            </div>
                        """ % help_text
                    help_text = help_text_html % 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))

        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))