Skip to main content

Field

This class serves as the base component for form fields, responsible for handling data validation, normalization, and widget rendering. It manages field-specific metadata such as labels, help text, and error messages while providing a standard interface for cleaning raw input into Python objects. The class also supports custom validators and localization to ensure data integrity across different locales.

Attributes

AttributeTypeDescription
widgetWidget class = TextInputDefault widget to use when rendering this type of Field.
hidden_widgetWidget class = HiddenInputDefault widget to use when rendering this as "hidden".
default_validatorslist = []Default set of validators
default_error_messagesdict = {"required": "This field is required."}Default error messages for the field, including an 'invalid' entry for specific field errors not raised by validators.
empty_valueslist = list(validators.EMPTY_VALUES)List of values that are considered empty for validation purposes.
bound_field_classBoundField class = nullBoundField class to use in Field.get_bound_field.

Constructor

Signature

def Field(
required: boolean = True,
widget: Widget|type = None,
label: str = None,
initial: any = None,
help_text: str = "",
error_messages: dict = None,
show_hidden_initial: boolean = False,
validators: tuple = (),
localize: boolean = False,
disabled: boolean = False,
label_suffix: str = None,
template_name: str = None,
bound_field_class: type = None
) - > null

Parameters

NameTypeDescription
requiredboolean = TrueSpecifies whether the field is required.
widget`Widgettype` = None
labelstr = NoneA verbose name for the field used in form display.
initialany = NoneA value to use for the field's initial display.
help_textstr = ""Optional help text for the field.
error_messagesdict = NoneOptional dictionary to override default validation error messages.
show_hidden_initialboolean = FalseSpecifies if a hidden widget with the initial value should be rendered.
validatorstuple = ()List of additional validators to apply to the field.
localizeboolean = FalseSpecifies if the field data should be localized.
disabledboolean = FalseSpecifies if the field is shown but not editable.
label_suffixstr = NoneSuffix to be added to the label, overriding the form's default suffix.
template_namestr = NoneThe name of the template used to render the field.
bound_field_classtype = NoneThe BoundField class to use for this field.

Methods


prepare_value()

@classmethod
def prepare_value(
value: any
) - > any

Prepares the raw value for display in a widget. This method is used to transform data from a Python object into a format suitable for rendering in an HTML form field.

Parameters

NameTypeDescription
valueanyThe Python object value to be prepared for the widget.

Returns

TypeDescription
anyThe value formatted for use by the widget.

to_python()

@classmethod
def to_python(
value: any
) - > any

Coerces the input value into a specific Python data type. This is the first step of the cleaning process and should raise a ValidationError if the value cannot be converted.

Parameters

NameTypeDescription
valueanyThe raw input value from the form submission or initial data.

Returns

TypeDescription
anyThe value converted to the appropriate Python type.

validate()

@classmethod
def validate(
value: any
) - > null

Performs basic validation on the field value, such as checking if a required field is empty. It raises a ValidationError if the value fails these fundamental checks.

Parameters

NameTypeDescription
valueanyThe Python-coerced value to validate against field-level constraints.

Returns

TypeDescription
nullNone

run_validators()

@classmethod
def run_validators(
value: any
) - > null

Executes all registered validators for the field and collects any resulting errors. It ensures that custom validation logic is applied to the value before it is considered clean.

Parameters

NameTypeDescription
valueanyThe value to be checked by the list of validator functions.

Returns

TypeDescription
nullNone

clean()

@classmethod
def clean(
value: any
) - > any

Validate the given value and return its "cleaned" value as an appropriate Python object. Raise ValidationError for any errors.

Parameters

NameTypeDescription
valueanyThe raw input value to be processed through the full cleaning pipeline.

Returns

TypeDescription
anyThe fully validated and coerced Python object.

bound_data()

@classmethod
def bound_data(
data: any,
initial: any
) - > any

Return the value that should be shown for this field on render of a bound form, given the submitted POST data for the field and the initial data, if any.

Parameters

NameTypeDescription
dataanyThe raw data submitted via the form for this specific field.
initialanyThe initial value provided to the field when the form was instantiated.

Returns

TypeDescription
anyThe data to be displayed, which is usually the submitted data unless the field is disabled.

widget_attrs()

@classmethod
def widget_attrs(
widget: [Widget](../widgets/widget.md?sid=django_forms_widgets_widget)
) - > dict

Given a Widget instance (not a Widget class), return a dictionary of any HTML attributes that should be added to the Widget, based on this Field.

Parameters

NameTypeDescription
widget[Widget](../widgets/widget.md?sid=django_forms_widgets_widget)The widget instance that will be used to render this field.

Returns

TypeDescription
dictA dictionary of HTML attribute names and values.

has_changed()

@classmethod
def has_changed(
initial: any,
data: any
) - > boolean

Return True if data differs from initial.

Parameters

NameTypeDescription
initialanyThe original value of the field before user modification.
dataanyThe new data submitted by the user to be compared against the initial value.

Returns

TypeDescription
booleanTrue if the submitted data is different from the initial value, False otherwise.

get_bound_field()

@classmethod
def get_bound_field(
form: [Form](../forms/form.md?sid=django_forms_forms_form),
field_name: string
) - > [BoundField](../boundfield/boundfield.md?sid=django_forms_boundfield_boundfield)

Return a BoundField instance that will be used when accessing the form field in a template.

Parameters

NameTypeDescription
form[Form](../forms/form.md?sid=django_forms_forms_form)The form instance this field is attached to.
field_namestringThe name assigned to this field within the form.

Returns

TypeDescription
[BoundField](../boundfield/boundfield.md?sid=django_forms_boundfield_boundfield)An object that wraps the field and its data for use in templates.