lback.forms package
This file serves as the initialization point for the ‘lback_framework/lback/forms’ package. It is designed to expose the core components necessary for building, validating, and rendering web forms within the Lback web framework. This package centralizes the definition and management of form fields, form classes, validation mechanisms, and various input widgets, providing a comprehensive system for handling user input.
—
Key Components Exposed by this Package:
Date and Time Fields (from .fields_datetime): A collection of specialized form fields designed to handle date and time input.
- DateTimeField: A form field for capturing both date and time values. It handles
parsing and formatting of datetime strings.
TimeField: A form field specifically for capturing time values.
DateField: A form field specifically for capturing date values.
File Fields (from .fields_file): A form field dedicated to handling file uploads.
- FileField: A form field for allowing users to upload files. It manages file
data and provides mechanisms for validation and storage.
Basic Form Fields (from .fields): A set of fundamental form fields for common data types.
- BooleanField: A form field for capturing boolean (True/False) input, typically
rendered as a checkbox.
- CharField: A form field for capturing single-line text input, suitable for
names, titles, or short descriptions.
- ChoiceField: A form field that allows users to select one option from a predefined
set of choices, often rendered as a dropdown (<select>) or radio buttons.
- EmailField: A specialized form field for capturing email addresses, typically
including built-in validation for email format.
IntegerField: A form field for capturing integer (whole number) input.
Form Classes (from .forms): The core classes for defining and managing forms.
- Form: The base class for creating web forms. It orchestrates the collection of
fields, handles data binding, and manages the overall validation process for user input.
- FormMetaclass: The metaclass used by the Form class, responsible for processing
field definitions when a form class is created.
ModelForm (from .models): A specialized form class designed to work directly with Lback’s database models.
- ModelForm: A form class that automatically generates form fields based on a
given database model’s fields. It simplifies the process of creating forms for creating or updating model instances, often handling validation and saving to the database.
Validation (from .validation): Components for handling form and field validation errors.
- ValidationError: A custom exception or class used to signal that form or field
validation has failed. It typically carries messages detailing the specific validation issues.
Date and Time Widgets (from .widgets_datetime): HTML input widgets specifically designed for date and time fields.
- DateInput: A widget for rendering a date input field in HTML, often using
type=”date” for native browser date pickers.
- DateTimeInput: A widget for rendering a datetime input field in HTML, often
using type=”datetime-local” or similar.
- TextInput: A generic text input widget, which might be used as a fallback
or for custom date/time string input.
File Widgets (from .widgets_file): An HTML input widget for file uploads.
FileInput: A widget for rendering a file upload input field in HTML (<input type=”file”>).
Basic Widgets (from .widgets): Common HTML input widgets for various form fields.
TextInput: A widget for rendering a standard single-line text input field (<input type=”text”>).
Textarea: A widget for rendering a multi-line text input area (<textarea>).
- PasswordInput: A widget for rendering a password input field (<input type=”password”>),
masking the input for security.
CheckboxInput: A widget for rendering a checkbox input field (<input type=”checkbox”>).
Select: A widget for rendering a dropdown list (<select>) for choice fields.
Submodules
lback.forms.fields module
- class lback.forms.fields.BooleanField(required: bool = False, initial: bool = False, empty_value: bool = False, **kwargs: Any)[source][source]
Bases:
FieldA field that handles boolean input, typically from a checkbox.
- __init__(required: bool = False, initial: bool = False, empty_value: bool = False, **kwargs: Any)[source][source]
Initializes a BooleanField.
- widget[source]
alias of
CheckboxInput
- class lback.forms.fields.CharField(max_length: int | None = None, min_length: int | None = None, strip: bool = True, empty_value: str = '', **kwargs: Any)[source][source]
Bases:
FieldA field that handles text input. Validates that the input is a string.
- __init__(max_length: int | None = None, min_length: int | None = None, strip: bool = True, empty_value: str = '', **kwargs: Any)[source][source]
Initializes a CharField.
- class lback.forms.fields.ChoiceField(choices: List[Tuple[Any, str]], empty_value: Any | None = None, **kwargs: Any)[source][source]
Bases:
FieldA field that represents a choice from a limited set of options. Typically rendered with a Select widget.
- __init__(choices: List[Tuple[Any, str]], empty_value: Any | None = None, **kwargs: Any)[source][source]
Initializes a ChoiceField.
- class lback.forms.fields.EmailField(**kwargs: Any)[source][source]
Bases:
CharFieldA field that handles email input. Inherits from CharField and adds email format validation.
- EMAIL_REGEX = re.compile('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$')
- class lback.forms.fields.Field(required: bool = True, label: str | None = None, initial: Any = None, widget: Widget | None = None, attrs: Dict[str, Any] | None = None, help_text: str | None = None, error_messages: Dict[str, str] | None = None, validators: List[Callable[[Any], None]] | None = None)[source][source]
Bases:
objectBase class for all form fields. Fields manage data validation and rendering using a widget.
- __init__(required: bool = True, label: str | None = None, initial: Any = None, widget: Widget | None = None, attrs: Dict[str, Any] | None = None, help_text: str | None = None, error_messages: Dict[str, str] | None = None, validators: List[Callable[[Any], None]] | None = None)[source][source]
Initializes a form field.
- Parameters:
required – If True, the field is required. Defaults to True.
label – The label for the field in the form. If None, a label will be generated.
initial – The initial value of the field when the form is displayed.
widget – The widget instance to use for rendering. Defaults to an instance of self.widget.
attrs – A dictionary of HTML attributes for the widget.
help_text – Optional help text for the field.
error_messages – A dictionary of custom error messages for validation errors.
validators – A list of validator functions to run after basic field validation. Each validator function should accept one argument (the cleaned value) and raise ValidationError if validation fails.
- bind(name: str, data: Dict[str, Any], files: Dict[str, Any])[source][source]
Binds the field to data from the request. Called by the Form when data is submitted.
- Parameters:
name – The name of the field (from the form definition).
data – The dictionary of data (e.g., request.POST).
files – The dictionary of files (e.g., request.FILES).
- is_valid() bool[source][source]
Validates the field’s data. Returns True if the field is valid, False otherwise. Validation errors are stored in self.errors.
- render(value: Any = None, attrs: Dict[str, Any] | None = None) str[source][source]
Renders the field using its widget.
- Parameters:
value – The value to render. Defaults to self.value if bound, self.initial if unbound. Explicitly passing a value here overrides the default.
attrs – Additional HTML attributes for the widget. Merged with self.attrs.
- Returns:
An HTML string for the field’s input element.
- to_python(value: Any) Any[source][source]
Converts the raw value from the widget into a Python object. This method performs basic type conversion and may raise ValidationError. Subclasses must implement this method.
- Parameters:
value – The raw value obtained from the widget.
- Returns:
The converted Python object.
- Raises:
ValidationError – If the value cannot be converted or is invalid.
- class lback.forms.fields.FileField(required: bool = True, empty_value: Any | None = None, allow_empty_file: bool = False, max_size: int | None = None, allowed_extensions: List[str] | None = None, **kwargs: Any)[source][source]
Bases:
FieldA field that handles file uploads. The cleaned value is the uploaded file object itself.
- __init__(required: bool = True, empty_value: Any | None = None, allow_empty_file: bool = False, max_size: int | None = None, allowed_extensions: List[str] | None = None, **kwargs: Any)[source][source]
Initializes a FileField.
- Parameters:
required – If True, a file must be uploaded. Defaults to True.
empty_value – The cleaned value to return if the field is not required and no file is uploaded. Defaults to None.
**kwargs – Additional arguments for the base Field class.
- class lback.forms.fields.IntegerField(min_value: int | None = None, max_value: int | None = None, empty_value: int | None = None, **kwargs: Any)[source][source]
Bases:
FieldA field that handles integer input. Validates that the input can be converted to an integer.
- __init__(min_value: int | None = None, max_value: int | None = None, empty_value: int | None = None, **kwargs: Any)[source][source]
Initializes an IntegerField.
lback.forms.fields_datetime module
- class lback.forms.fields_datetime.DateField(input_formats: List[str] | None = None, empty_value: date | None = None, **kwargs: Any)[source][source]
Bases:
FieldA field that handles date input. Validates that the input can be converted to a Python date object.
- __init__(input_formats: List[str] | None = None, empty_value: date | None = None, **kwargs: Any)[source][source]
Initializes a DateField.
- Parameters:
input_formats – A list of date format strings to try when parsing the input. Defaults to common formats (e.g., ‘%Y-%m-%d’).
empty_value – The cleaned value to return if the input is empty and not required. Defaults to None.
**kwargs – Additional arguments for the base Field class.
- class lback.forms.fields_datetime.DateTimeField(input_formats: List[str] | None = None, empty_value: datetime | None = None, **kwargs: Any)[source][source]
Bases:
FieldA field that handles datetime input. Validates that the input can be converted to a Python datetime object.
- __init__(input_formats: List[str] | None = None, empty_value: datetime | None = None, **kwargs: Any)[source][source]
Initializes a DateTimeField.
- Parameters:
input_formats – A list of datetime format strings to try when parsing the input. Defaults to common formats (e.g., ‘%Y-%m-%dT%H:%M’).
empty_value – The cleaned value to return if the input is empty and not required. Defaults to None.
**kwargs – Additional arguments for the base Field class.
- to_python(value: Any) datetime | None[source][source]
Converts the input value to a Python datetime object and performs validation.
- widget[source]
alias of
DateTimeInput
- class lback.forms.fields_datetime.TimeField(input_formats: List[str] | None = None, empty_value: time | None = None, **kwargs: Any)[source][source]
Bases:
FieldA field that handles time input. Validates that the input can be converted to a Python time object.
- __init__(input_formats: List[str] | None = None, empty_value: time | None = None, **kwargs: Any)[source][source]
Initializes a TimeField.
- Parameters:
input_formats – A list of time format strings to try when parsing the input. Defaults to common formats (e.g., ‘%H:%M’, ‘%H:%M:%S’).
empty_value – The cleaned value to return if the input is empty and not required. Defaults to None.
**kwargs – Additional arguments for the base Field class.
lback.forms.forms module
- class lback.forms.forms.Form(data: Dict[str, Any] | None = None, files: Dict[str, Any] | None = None, initial: Dict[str, Any] | None = None)[source][source]
Bases:
objectBase class for all forms. Forms are collections of fields that handle data binding and validation. Uses FormMetaclass to automatically collect fields defined as class attributes.
- __init__(data: Dict[str, Any] | None = None, files: Dict[str, Any] | None = None, initial: Dict[str, Any] | None = None)[source][source]
Initializes a form instance.
- Parameters:
data – A dictionary of data to bind to the form (e.g., from request.POST).
files – A dictionary of files to bind to the form (e.g., from request.FILES).
initial – A dictionary of initial data to populate the form with.
- add_error(field: str | None, error: ValidationError)[source][source]
Adds an error to a specific field or to the form’s non-field errors.
- Parameters:
field – The name of the field to associate the error with. If None, the error is added to the form’s non-field errors.
error – The ValidationError object containing the error message and code.
- clean()[source][source]
Performs form-level validation that depends on multiple fields. Should raise ValidationError for non-field errors. Can also modify self.cleaned_data. Subclasses should override this method if form-level validation is needed.
- property cleaned_data: Dict[str, Any]
Returns a dictionary of validated and cleaned data for each field. Only available if the form is valid.
- property errors: Dict[str, List[ValidationError]]
Returns a dictionary of errors for the form. Keys are field names, values are lists of ValidationError instances. Includes ‘__all__’ key for non-field errors. Calls is_valid() implicitly if not already called.
- property non_field_errors: List[ValidationError]
Returns a list of non-field errors.
lback.forms.models module
- class lback.forms.models.ModelForm(data: Dict[str, Any] | None = None, files: Dict[str, Any] | None = None, initial: Dict[str, Any] | None = None, instance: Any | None = None)[source][source]
Bases:
FormA Form that is automatically generated from a database model. Requires a ‘Meta’ inner class with a ‘model’ attribute.
- __init__(data: Dict[str, Any] | None = None, files: Dict[str, Any] | None = None, initial: Dict[str, Any] | None = None, instance: Any | None = None)[source][source]
Initializes a ModelForm instance.
- class lback.forms.models.ModelFormMetaclass(name, bases, attrs)[source][source]
Bases:
FormMetaclassMetaclass for ModelForm classes. Collects declared fields and automatically generates fields from the associated model.
lback.forms.validation module
Contains exceptions used during form and field validation.
- exception lback.forms.validation.ValidationError(message: str, code: str | None = None)[source][source]
Bases:
ExceptionBase exception for validation errors. Can be raised by field or form validation methods.
lback.forms.widgets module
- class lback.forms.widgets.CheckboxInput(attrs: Dict[str, Any] | None = None)[source][source]
Bases:
WidgetA widget that renders as an HTML <input type=”checkbox”>. Handles boolean values.
- input_type = 'checkbox'
- class lback.forms.widgets.FileInput(attrs: Dict[str, Any] | None = None)[source][source]
Bases:
WidgetA widget that renders as an HTML <input type=”file”> element. Handles file uploads.
- input_type = 'file'
- class lback.forms.widgets.PasswordInput(attrs: Dict[str, Any] | None = None)[source][source]
Bases:
TextInputA widget that displays a password input (<input type=”password”>). By default, it does not pre-fill the value for security reasons.
- input_type = 'password'
- class lback.forms.widgets.Select(choices: List[Tuple[Any, str]], attrs: Dict[str, Any] | None = None)[source][source]
Bases:
WidgetA widget that renders as an HTML <select> element. Takes a list of choices.
- __init__(choices: List[Tuple[Any, str]], attrs: Dict[str, Any] | None = None)[source][source]
Initializes the Select widget.
- Parameters:
choices – A list of (value, label) tuples for the select options.
attrs – Optional HTML attributes for the <select> element.
- class lback.forms.widgets.TextInput(attrs: Dict[str, Any] | None = None)[source][source]
Bases:
WidgetA widget that renders as a standard HTML <input type=”text”>.
- input_type = 'text'
- class lback.forms.widgets.Textarea(attrs: Dict[str, Any] | None = None)[source][source]
Bases:
WidgetA widget that renders as an HTML <textarea> element.
- class lback.forms.widgets.Widget(attrs: Dict[str, Any] | None = None)[source][source]
Bases:
objectBase class for all form widgets. Widgets are responsible for rendering the HTML representation of a field.
- __init__(attrs: Dict[str, Any] | None = None)[source][source]
Initializes the widget with optional HTML attributes.
- Parameters:
attrs – A dictionary of HTML attributes (e.g., {‘class’: ‘my-input’, ‘placeholder’: ‘Enter text’}).
- build_attrs(base_attrs: Dict[str, Any] | None = None, extra_attrs: Dict[str, Any] | None = None) Dict[str, Any][source][source]
Helper method to combine base attributes, widget attributes, and extra attributes.
- Parameters:
base_attrs – Attributes from the field itself.
extra_attrs – Attributes passed during rendering (e.g., in template tags).
- Returns:
A combined dictionary of attributes.
- input_type = None
- render(name: str, value: Any, attrs: Dict[str, Any] | None = None) str[source][source]
Renders the widget as an HTML string. This method should be overridden by subclasses.
- Parameters:
name – The HTML ‘name’ attribute for the input element.
value – The current value of the field.
attrs – Additional HTML attributes to include (merged with self.attrs).
- Returns:
An HTML string representing the widget.
- template_name = None
- value_from_datadict(data: Dict[str, Any], files: Dict[str, Any], name: str) Any[source][source]
Given a dictionary of data and an attribute name, returns the value of that attribute, normalizing it if necessary.
- Parameters:
data – The dictionary of data (e.g., request.POST).
files – The dictionary of files (e.g., request.FILES).
name – The name of the field.
- Returns:
The raw value from the data dictionary.
lback.forms.widgets_datetime module
- class lback.forms.widgets_datetime.DateInput(attrs: Dict[str, Any] | None = None)[source][source]
Bases:
TextInputA widget that renders as an HTML <input type=”date”> or <input type=”text”> for date input.
- input_type = 'date'
- class lback.forms.widgets_datetime.DateTimeInput(attrs: Dict[str, Any] | None = None)[source][source]
Bases:
TextInputA widget that renders as an HTML <input type=”datetime-local”> or <input type=”text”> for datetime input.
- input_type = 'datetime-local'