本文整理汇总了Python中django.forms.forms.BoundField类的典型用法代码示例。如果您正苦于以下问题:Python BoundField类的具体用法?Python BoundField怎么用?Python BoundField使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BoundField类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __iter__
def __iter__(self):
for name, field in self.fields.items():
bound_field = BoundField(self, field, name)
bound_field.percent = field.percent
bound_field.student_name = field.student_name
yield bound_field
示例2: render
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK):
extra = []
for field in self.fields:
field_instance = form.fields[field]
bound_field = BoundField(form, field_instance, field)
extra.append(bound_field.value())
context["extra"] = mark_safe("\n".join(extra))
return super(VisibleHiddenField, self).render(form, form_style, context, template_pack)
示例3: as_hidden
def as_hidden(self):
"""Returns this form rendered entirely as hidden fields."""
output = []
for name, field in self.fields.items():
bf = BoundField(self, field, name)
output.append(bf.as_hidden())
return mark_safe(u'\n'.join(output))
示例4: _ul_html_output
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))
示例5: get_field_tuple
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)
示例6: as_div
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))
示例7: _html_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))
示例8: render_label
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)
示例9: _html_output
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))
示例10: _bind_field
def _bind_field(self, name, field):
bound = BoundField(self, field, name)
bound.metadata = self._prepare_field_metadata(name, field)
value = self._get_field_value(bound)
if isinstance(field, forms.ModelMultipleChoiceField):
if value:
ref = [field.queryset.get(pk=val) for val in value if val]
else:
ref = []
elif isinstance(field, forms.ModelChoiceField):
ref = (field.queryset.get(pk=value) if value else None)
else:
ref = value
bound.initial_value = {'value': value, 'ref': ref}
return bound
示例11: format_as_pml
def format_as_pml(self):
output = []
for name, field in self.fields.items():
bf = BoundField(self, field, name)
text_field_type = 'Text'
if(isinstance(field, IntegerField)):
text_field_type = 'num'
field_str = ('<TEXT position="ABOVE">%(label_name)s</TEXT><FIELD name="%(field_name)s" type="%(text_field_type)s" default="%(field_value)s"/><br/>'
% {
'label_name': conditional_escape(force_unicode(bf.label)),
'field_name': bf.html_name,
'field_value': bf.value() if bf.value() != None else '',
'text_field_type': text_field_type
})
if(isinstance(field, BooleanField)):
default = bf.value() if bf.value() != None else ''
field_str = ('''<CHOICE-GROUP type="radio" name="%(field_name)s">
<TEXT>%(label_name)s</TEXT>
<CHOICE value="True" %(default_true)s>Yes</CHOICE>
<CHOICE value="False" %(default_false)s>No</CHOICE>
</CHOICE-GROUP>''' %
{
'default_true': 'checked="true"' if default else '',
'default_false': 'checked="true"' if not default else '',
'label_name': conditional_escape(force_unicode(bf.label)),
'field_name': bf.html_name,
'field_value': bf.value() if bf.value() != None else ''
})
output.append(field_str)
return mark_safe(u'\n'.join(output))
示例12: field_template
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
示例13: uka_form_row_stacked
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
示例14: bootstrapped3
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))
示例15: as_widget
def as_widget(self, widget=None, attrs=None, only_initial=False):
"""Renders a field and adds dlgi styles if appropriate."""
if not widget:
widget = self.field.widget
if isinstance(widget, widgets.Input):
if not attrs:
# Maintain existing style classes:
class_attrs = set((
self.field.widget.attrs.get('class') or '').split(' '))
# anf add those for general layout:
class_attrs.add('input-text')
attrs = {'class': ' '.join(class_attrs)}
return BaseBoundField.as_widget(self, widget=widget, attrs=attrs,
only_initial=only_initial)