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
| Attribute | Type | Description |
|---|---|---|
| max_length | int = None | The maximum number of characters allowed in the field, used for validation and setting the HTML maxlength attribute. |
| min_length | int = None | The minimum number of characters required in the field, used for validation and setting the HTML minlength attribute. |
| strip | boolean = True | A boolean flag that determines whether leading and trailing whitespace should be removed from the input value. |
| empty_value | string = "" | 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
| Name | Type | Description |
|---|---|---|
| max_length | int = None | The maximum length allowed for the field value. |
| min_length | int = None | The minimum length required for the field value. |
| strip | boolean = True | Whether to strip leading and trailing whitespace from the input. |
| empty_value | string = "" | The value to return if the input is empty. |
| **kwargs | dict | Additional keyword arguments passed to the parent Field class. |
Methods
to_python()
@classmethod
def to_python(
value: any
) - > string
Return a string.
Parameters
| Name | Type | Description |
|---|---|---|
| value | any | The raw input value to be converted into a string representation. |
Returns
| Type | Description |
|---|---|
string | The 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
| Name | Type | Description |
|---|---|---|
| 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
| Type | Description |
|---|---|
dict | A dictionary containing HTML attributes like 'maxlength' and 'minlength' to be applied to the widget's HTML tag. |