Skip to main content

CharField

This class represents a string-based form field that handles data normalization and validation. It supports constraints such as minimum and maximum lengths, provides automatic whitespace stripping, and manages the conversion of empty inputs to a specified default value. Additionally, it automatically provides relevant HTML attributes to associated widgets for client-side validation.

Attributes

AttributeTypeDescription
max_lengthint = NoneThe maximum number of characters allowed in the field, used for validation and setting the HTML maxlength attribute.
min_lengthint = NoneThe minimum number of characters required in the field, used for validation and setting the HTML minlength attribute.
stripboolean = TrueA boolean flag that determines whether leading and trailing whitespace should be removed from the input value.
empty_valuestring = ""The value to return when the input is considered empty, such as an empty string or None.

Constructor

Signature

def CharField(
max_length: int = None,
min_length: int = None,
strip: boolean = True,
empty_value: string = "",
**kwargs: dict
) - > null

Parameters

NameTypeDescription
max_lengthint = NoneThe maximum length allowed for the field value.
min_lengthint = NoneThe minimum length required for the field value.
stripboolean = TrueWhether to strip leading and trailing whitespace from the input.
empty_valuestring = ""The value to return if the input is empty.
**kwargsdictAdditional keyword arguments passed to the parent Field class.

Methods


to_python()

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

Return a string.

Parameters

NameTypeDescription
valueanyThe raw input value to be converted into a string representation.

Returns

TypeDescription
stringThe processed string value, stripped of whitespace if configured, or the designated empty_value if the input is null or empty.

widget_attrs()

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

Builds a dictionary of HTML attributes for the associated form widget based on the field's constraints.

Parameters

NameTypeDescription
widget[Widget](../widgets/widget.md?sid=django_forms_widgets_widget)The form widget instance that will render this field, used to check if the field is hidden before applying attributes.

Returns

TypeDescription
dictA dictionary containing HTML attributes like 'maxlength' and 'minlength' to be applied to the widget's HTML tag.