class BoundField
from django.forms import BoundField
A Field plus data
Ancestors (MRO)
- BoundField
- RenderableFieldMixin
- RenderableMixin
Attributes
| Defined in | |
|---|---|
initial = <django.utils.functional.cached_property object at 0x10f3c4550>
|
BoundField |
subwidgets = <django.utils.functional.cached_property object at 0x10f3611c0>
|
BoundField |
Properties
def
aria_describedby():
¶
BoundField
Getter
@property
def aria_describedby(self):
# Preserve aria-describedby set on the widget.
if self.field.widget.attrs.get("aria-describedby"):
return None
aria_describedby = []
if self.auto_id and not self.is_hidden:
if self.help_text:
aria_describedby.append(f"{self.auto_id}_helptext")
if self.errors:
aria_describedby.append(f"{self.auto_id}_error")
return " ".join(aria_describedby)
def
auto_id():
¶
BoundField
Getter
@property
def auto_id(self):
"""
Calculate and return the ID attribute for this BoundField, if the
associated Form has specified auto_id. Return an empty string
otherwise.
"""
auto_id = self.form.auto_id # Boolean or string
if auto_id and "%s" in str(auto_id):
return auto_id % self.html_name
elif auto_id:
return self.html_name
return ""
def
data():
¶
BoundField
Getter
@property
def data(self):
"""
Return the data for this BoundField, or None if it wasn't given.
"""
return self.form._widget_data_value(self.field.widget, self.html_name)
def
errors():
¶
BoundField
Getter
@property
def errors(self):
"""
Return an ErrorList (empty if there are no errors) for this field.
"""
return self.form.errors.get(
self.name, self.form.error_class(renderer=self.form.renderer)
)
def
id_for_label():
¶
BoundField
Getter
@property
def id_for_label(self):
"""
Wrapper around the field widget's `id_for_label` method.
Useful, for example, for focusing on this field regardless of whether
it has a single widget or a MultiWidget.
"""
widget = self.field.widget
id_ = widget.attrs.get("id") or self.auto_id
return widget.id_for_label(id_)
def
is_hidden():
¶
BoundField
def
template_name():
¶
BoundField
Getter
@property
def template_name(self):
return self.field.template_name or self.form.renderer.field_template_name
def
use_fieldset():
¶
BoundField
Getter
@property
def use_fieldset(self):
"""
Return the value of this BoundField widget's use_fieldset attribute.
"""
return self.field.widget.use_fieldset
def
widget_type():
¶
BoundField
Getter
@property
def widget_type(self):
return re.sub(
r"widget$|input$", "", self.field.widget.__class__.__name__.lower()
)
Methods
def
_has_changed(self):
¶
BoundField
def _has_changed(self):
field = self.field
if field.show_hidden_initial:
hidden_widget = field.hidden_widget()
initial_value = self.form._widget_data_value(
hidden_widget,
self.html_initial_name,
)
try:
initial_value = field.to_python(initial_value)
except ValidationError:
# Always assume data has changed if validation fails.
return True
else:
initial_value = self.initial
return field.has_changed(initial_value, self.data)
def
as_field_group(self):
¶
RenderableFieldMixin
def as_field_group(self):
return self.render()
def
as_hidden(self, attrs=None, **kwargs):
¶
def
as_text(self, attrs=None, **kwargs):
¶
BoundField
Return a string of HTML for representing this as an <input type="text">.
def as_text(self, attrs=None, **kwargs):
"""
Return a string of HTML for representing this as an
<input type="text">.
"""
return self.as_widget(TextInput(), attrs, **kwargs)
def
as_textarea(self, attrs=None, **kwargs):
¶
BoundField
Return a string of HTML for representing this as a <textarea>.
def as_textarea(self, attrs=None, **kwargs):
"""Return a string of HTML for representing this as a <textarea>."""
return self.as_widget(Textarea(), attrs, **kwargs)
def
as_widget(self, widget=None, attrs=None, only_initial=False):
¶
BoundField
Render the field by rendering the passed widget, adding any HTML attributes passed as attrs. If a widget isn't specified, use the field's default widget.
def as_widget(self, widget=None, attrs=None, only_initial=False):
"""
Render the field by rendering the passed widget, adding any HTML
attributes passed as attrs. If a widget isn't specified, use the
field's default widget.
"""
widget = widget or self.field.widget
if self.field.localize:
widget.is_localized = True
attrs = attrs or {}
attrs = self.build_widget_attrs(attrs, widget)
if self.auto_id and "id" not in widget.attrs:
attrs.setdefault(
"id", self.html_initial_id if only_initial else self.auto_id
)
if only_initial and self.html_initial_name in self.form.data:
# Propagate the hidden initial value.
value = self.form._widget_data_value(
self.field.hidden_widget(),
self.html_initial_name,
)
else:
value = self.value()
return widget.render(
name=self.html_initial_name if only_initial else self.html_name,
value=value,
attrs=attrs,
renderer=self.form.renderer,
)
RenderableFieldMixin
def as_widget(self):
raise NotImplementedError(
"Subclasses of RenderableFieldMixin must provide an as_widget() method."
)
def
build_widget_attrs(self, attrs, widget=None):
¶
BoundField
def build_widget_attrs(self, attrs, widget=None):
widget = widget or self.field.widget
attrs = dict(attrs) # Copy attrs to avoid modifying the argument.
if (
widget.use_required_attribute(self.initial)
and self.field.required
and self.form.use_required_attribute
):
# MultiValueField has require_all_fields: if False, fall back
# on subfields.
if (
hasattr(self.field, "require_all_fields")
and not self.field.require_all_fields
and isinstance(self.field.widget, MultiWidget)
):
for subfield, subwidget in zip(self.field.fields, widget.widgets):
subwidget.attrs["required"] = (
subwidget.use_required_attribute(self.initial)
and subfield.required
)
else:
attrs["required"] = True
if self.field.disabled:
attrs["disabled"] = True
if not widget.is_hidden and self.errors:
attrs["aria-invalid"] = "true"
# Preserve aria-describedby provided by the attrs argument so user
# can set the desired order.
if not attrs.get("aria-describedby") and not self.use_fieldset:
if aria_describedby := self.aria_describedby:
attrs["aria-describedby"] = aria_describedby
return attrs
def
css_classes(self, extra_classes=None):
¶
BoundField
Return a string of space-separated CSS classes for this field.
def css_classes(self, extra_classes=None):
"""
Return a string of space-separated CSS classes for this field.
"""
if hasattr(extra_classes, "split"):
extra_classes = extra_classes.split()
extra_classes = set(extra_classes or [])
if self.errors and hasattr(self.form, "error_css_class"):
extra_classes.add(self.form.error_css_class)
if self.field.required and hasattr(self.form, "required_css_class"):
extra_classes.add(self.form.required_css_class)
return " ".join(extra_classes)
def
get_context(self):
¶
BoundField
def get_context(self):
return {"field": self}
RenderableMixin
def get_context(self):
raise NotImplementedError(
"Subclasses of RenderableMixin must provide a get_context() method."
)
def
label_tag(self, contents=None, attrs=None, label_suffix=None, tag=None):
¶
BoundField
Wrap the given contents in a <label>, if the field has an ID attribute. contents should be mark_safe'd to avoid HTML escaping. If contents aren't given, use the field's HTML-escaped label. If attrs are given, use them as HTML attributes on the <label> tag. label_suffix overrides the form's label_suffix.
def label_tag(self, contents=None, attrs=None, label_suffix=None, tag=None):
"""
Wrap the given contents in a <label>, if the field has an ID attribute.
contents should be mark_safe'd to avoid HTML escaping. If contents
aren't given, use the field's HTML-escaped label.
If attrs are given, use them as HTML attributes on the <label> tag.
label_suffix overrides the form's label_suffix.
"""
contents = contents or self.label
if label_suffix is None:
label_suffix = (
self.field.label_suffix
if self.field.label_suffix is not None
else self.form.label_suffix
)
# Only add the suffix if the label does not end in punctuation.
# Translators: If found as last label character, these punctuation
# characters will prevent the default label_suffix to be appended to
# the label
if label_suffix and contents and contents[-1] not in _(":?.!"):
contents = format_html("{}{}", contents, label_suffix)
widget = self.field.widget
id_ = widget.attrs.get("id") or self.auto_id
if id_:
id_for_label = widget.id_for_label(id_)
if id_for_label:
attrs = {**(attrs or {}), "for": id_for_label}
if self.field.required and hasattr(self.form, "required_css_class"):
attrs = attrs or {}
if "class" in attrs:
attrs["class"] += " " + self.form.required_css_class
else:
attrs["class"] = self.form.required_css_class
context = {
"field": self,
"label": contents,
"attrs": attrs,
"use_tag": bool(id_),
"tag": tag or "label",
}
return self.form.render(self.form.template_name_label, context)
def
legend_tag(self, contents=None, attrs=None, label_suffix=None):
¶
BoundField
Wrap the given contents in a <legend>, if the field has an ID attribute. Contents should be mark_safe'd to avoid HTML escaping. If contents aren't given, use the field's HTML-escaped label. If attrs are given, use them as HTML attributes on the <legend> tag. label_suffix overrides the form's label_suffix.
def legend_tag(self, contents=None, attrs=None, label_suffix=None):
"""
Wrap the given contents in a <legend>, if the field has an ID
attribute. Contents should be mark_safe'd to avoid HTML escaping. If
contents aren't given, use the field's HTML-escaped label.
If attrs are given, use them as HTML attributes on the <legend> tag.
label_suffix overrides the form's label_suffix.
"""
return self.label_tag(contents, attrs, label_suffix, tag="legend")
def
render(self, template_name=None, context=None, renderer=None):
¶
RenderableMixin
def render(self, template_name=None, context=None, renderer=None):
renderer = renderer or self.renderer
template = template_name or self.template_name
context = context or self.get_context()
return mark_safe(renderer.render(template, context))
def
value(self):
¶
BoundField
Return the value for this BoundField, using the initial value if the form is not bound or the data otherwise.
def value(self):
"""
Return the value for this BoundField, using the initial value if
the form is not bound or the data otherwise.
"""
data = self.initial
if self.form.is_bound:
data = self.field.bound_data(self.data, data)
return self.field.prepare_value(data)