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, }, )
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)
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))
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)
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))
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 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))
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': ' ', '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))
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)
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))
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
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
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))
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': ' ', 'field': self.section_template % section, 'help_text': '' }) for name, field in [ i for i in list(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([ '(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors ]) hidden_fields.append(str(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 = '' output.append( normal_row % { 'errors': force_unicode(bf_errors), 'label': force_unicode(label), 'field': str(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 = ''.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('\n'.join(output))
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))
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))
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))
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
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)
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))
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))
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))
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 new_html_output(self, def_row_starter, short_field, long_field, error_txt, def_row_ender, help_text_html, errors_on_separate_row): "Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()." def line_group_safe(field): if hasattr(field, 'line_group'): return field.line_group else: return 0 def field_compare(field_a, field_b): return line_group_safe(field_a[1]) - line_group_safe(field_b[1]) top_errors = self.non_field_errors( ) # Errors that should be displayed above all fields. output, hidden_fields = [], [] fieldlist = self.fields.items() fieldlist.sort(field_compare) for i in range(0, len(fieldlist)): name = fieldlist[i][0] field = fieldlist[i][1] row_starter = def_row_starter row_ender = def_row_ender bf = BoundField(self, field, name) bf_errors = ErrorList([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) %s' % (name, e) for e in bf_errors ]) hidden_fields.append(unicode(bf)) else: # Only put in the row break if this field is on a different line group than the previous one if line_group_safe(field) == 0: row_starter = '<tr>' row_ender = '</tr>' else: if (i != 0) and (line_group_safe(fieldlist[i - 1][1]) == line_group_safe(field)): output.append( '<!-- Killing starter: prev=%d current=%d -->' % (line_group_safe( fieldlist[i - 1][1]), line_group_safe(field))) row_starter = '' if (i < len(fieldlist) - 1) and (line_group_safe( fieldlist[i + 1][1]) == line_group_safe(field)): output.append( '<!-- Killing ender: current=%d next=%d -->' % (line_group_safe(field), line_group_safe(fieldlist[i + 1][1]))) row_ender = '' output.append( '<!-- i=%d: begin field line group %d starter="%s" ender="%s" -->' % (i, line_group_safe(field), row_starter, row_ender)) if errors_on_separate_row and bf_errors: output.append(error_row % bf_errors) label = bf.label and bf.label_tag(escape(bf.label + ':')) or '' if field.help_text: help_text = help_text_html % field.help_text else: help_text = u'' field_text = short_field if hasattr(field, 'is_long') and field.is_long: field_text = long_field output.append(row_starter) output.append( field_text % { 'errors': bf_errors, 'label': label, 'field': unicode(bf), 'help_text': help_text, 'field_width': 35 }) output.append(row_ender) if top_errors: output.insert(0, error_txt % top_errors) if hidden_fields: # Insert any hidden fields in the last row. str_hidden = '<td>' + u''.join(hidden_fields) + '</td>' 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 u'\n'.join(output)
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)
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 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
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))
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))
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)
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))
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))