Contrib for balderhub-crud

For activating this module, you need to install the package like shown below

>>> pip install balderhub-django[crud]

Once installed you can use it.

CRUD Feature / Pages Integration

This contribution module connects the generic CRUD testing framework of balderhub-crud with the Django admin interface. It ships everything you need to test CREATE, READ and UPDATE operations of your models over the default Django admin, without writing the interaction logic yourself:

  • Auto pages - page objects for the admin index, change-list, add-form and change-form views that resolve their URL automatically from a configuration feature

  • A model configuration feature - GeneralAdminModelConfig, which describes where the admin lives and which fields are shown in the different views

  • Auto setup features - implementations of the balderhub-crud setup features (AdminSingleReader, AdminSingleCreator, AdminSingleUpdater, AdminMultipleReader) that already know how the Django admin renders its forms and lists

  • Factories - helper classes that bind the setup features to a specific data item with a single call

If you are looking for a complete end-to-end walkthrough (data items, data environment, example providers and the final setup), take a look at the Examples section. This section here focuses on the details of the single components and how you can customize them.

The model configuration

Everything in this module is driven by the GeneralAdminModelConfig scenario feature. For every model (data item) you want to test, you provide one subclass and register it for the data item:

import balderhub.data
import balderhub.django.contrib.crud.scenario_features
from balderhub.url.lib.utils import Url

from tests.lib.utils.data import BookDataItem


@balderhub.data.register_for_data_item(BookDataItem)
class BookAdminModelConfig(balderhub.django.contrib.crud.scenario_features.GeneralAdminModelConfig):

    @property
    def admin_root_url(self) -> Url:
        return Url("http://example.com/admin")

    @property
    def app_name(self):
        return 'bookstore'

    @property
    def model_name(self):
        return 'book'

Only admin_root_url, app_name and model_name are mandatory. In addition, the config feature provides a couple of hooks you can overwrite to describe your concrete ModelAdmin:

get_multiple_read_fields()

the fields that are expected as columns in the change-list view (list_display) - by default all fields of the data item

get_single_read_fields() / get_single_create_fields() / get_single_update_fields()

the fields that are expected to be visible/writable in the change-form and add-form views - by default all fields of the data item (without id for create/update)

get_django_field_name_for_field(field)

converts a data-item field name into the identifier Django uses for the corresponding form field or table column - overwrite this if your data item field names differ from the Django model field names

write_date_format / write_datetime_format / read_date_format / read_datetime_format

the date/datetime formats used when filling or reading date fields of the admin interface

For example, if your ModelAdmin only shows some fields in list_display, remove the other fields from the multiple-read fields:

@balderhub.data.register_for_data_item(BookDataItem)
class BookAdminModelConfig(balderhub.django.contrib.crud.scenario_features.GeneralAdminModelConfig):
    ...

    def get_multiple_read_fields(self) -> list[str]:
        result = super().get_multiple_read_fields()
        result.remove('summary')
        result.remove('categories')
        return result

The auto pages

The auto pages are subclasses of the general admin page objects of this package (see balderhub.django.lib.pages.admin). While the general page objects require you to implement the URL schema yourself, the auto pages read all URL information from the GeneralAdminModelConfig of the same device:

Simply assign the config feature and the pages to the same device:

import balder

import balderhub.django.contrib.crud.pages.admin


class SetupExample(balder.Setup):

    class SuperuserClient(balder.Device):
        admin_model_config = BookAdminModelConfig()

        page_index = balderhub.django.contrib.crud.pages.admin.AutoIndexPage()
        page_list = balderhub.django.contrib.crud.pages.admin.AutoChangeListPage()
        page_add = balderhub.django.contrib.crud.pages.admin.AutoAddItemFormPage()
        page_change = balderhub.django.contrib.crud.pages.admin.AutoChangeItemFormPage()

Because the pages know their model from the config, opening them does not require any arguments anymore:

# navigates to `http://example.com/admin/bookstore/book/add`
self.SuperuserClient.page_add.open()
self.SuperuserClient.page_add.wait_for_page()

The auto setup features

The setup features implement the abstract CRUD setup features of balderhub-crud for the Django admin. They combine the auto pages with the model configuration and take care of everything the ready-made CRUD scenarios of balderhub-crud need:

You can use these features without modification if your admin views use the default configuration. Every feature must be bound to a data item. The easiest way to do that is to use the corresponding factory, which internally creates a subclass and registers it via balderhub.data.register_for_data_item:

import balder

import balderhub.django.contrib.crud.setup_features.factories

from tests.lib.utils.data import BookDataItem


class SetupBook(balder.Setup):

    class SuperuserClient(balder.Device):
        admin_model_config = BookAdminModelConfig()
        ...

        multiple_reader = balderhub.django.contrib.crud.setup_features.factories.AutoAdminMultipleReaderFactory.get_for(BookDataItem)()
        single_reader = balderhub.django.contrib.crud.setup_features.factories.AutoAdminSingleReaderFactory.get_for(BookDataItem)()
        single_creator = balderhub.django.contrib.crud.setup_features.factories.AutoAdminSingleCreatorFactory.get_for(BookDataItem)()
        single_updater = balderhub.django.contrib.crud.setup_features.factories.AutoAdminSingleUpdaterFactory.get_for(BookDataItem)()

If you prefer explicit classes (for example because you want to overwrite some behavior), you can subclass the setup feature yourself instead of using the factory:

import balderhub.data
import balderhub.django.contrib.crud.setup_features

from tests.lib.utils.data import BookDataItem


@balderhub.data.register_for_data_item(BookDataItem)
class BookAdminSingleCreator(balderhub.django.contrib.crud.setup_features.AdminSingleCreator):
    pass

With these features assigned to your setup device, the ready-made scenarios of balderhub-crud (ScenarioSingleRead, ScenarioMultipleRead, ScenarioSingleCreate, ScenarioSingleUpdate) match automatically and test the corresponding admin views.

How form fields are filled and read

Internally, the setup features build a so-called item mapping: for every field of the data item they look up the corresponding form field container on the page (via get_form_field_container_for) and select a matching field callback that knows how to fill or read this widget type. The mapping between admin widgets and callbacks is done by get_field_filler_callback_type_for() and get_field_collector_callback_type_for().

Out of the box, the following default admin widgets are supported:

Admin widget

Callbacks

text/number input (<input>)

DjangoAdminInputFillerFieldCallback / DjangoAdminInputCollectorFieldCallback

text area (<textarea>)

DjangoAdminTextareaFillerFieldCallback / DjangoAdminTextareaCollectorFieldCallback

date field

DjangoAdminDateFillerFieldCallback / DjangoAdminDateCollectorFieldCallback

foreign key (<select>)

DjangoAdminForeignkeyFillerFieldCallback / DjangoAdminForeignkeyCollectorFieldCallback

many-to-many (filter widget)

DjangoAdminM2MFillerFieldCallback / DjangoAdminM2MCollectorFieldCallback

Values that were read from the page are always strings. The config feature converts them back into the data-item types (int, float, decimal.Decimal, datetime.date, datetime.datetime, lists of them) via GeneralAdminModelConfig.get_collector_type_convertion_cb, using the read_date_format/read_datetime_format definitions.

Customizing for non-default admin views

If your admin views deviate from the default configuration (custom widgets, custom rendering, custom messages, …), subclass the relevant setup feature and overwrite the relevant methods. The most common hooks are:

item_mapping()

returns the mapping between data-item fields and their field callbacks - overwrite it to use custom callbacks for custom widgets

load(**kwargs)

opens the relevant page - overwrite it if the object cannot be reached over the default URL

save()

submits the form - overwrite it if your view uses a different submit mechanism

get_expected_error_message_for_missing_mandatory_field(...)

the error messages that are expected when a mandatory field is not provided - overwrite it if your project uses custom validation messages

For example, to support a custom widget for the summary field of a book:

@balderhub.data.register_for_data_item(BookDataItem)
class BookAdminSingleCreator(balderhub.django.contrib.crud.setup_features.AdminSingleCreator):

    def item_mapping(self):
        result = super().item_mapping()
        summary_container = self.page.content.form.get_form_field_container_for(django_identifier='summary')
        result['summary'] = MyCustomSummaryFillerFieldCallback(summary_container)
        return result

The active success and error messages are extracted from the pages with get_success_messages_from() and get_error_messages_from(), which you can also reuse in your own subclasses.

API balderhub-crud

CRUD Admin Pages

class balderhub.django.contrib.crud.pages.admin.AutoIndexPage(**kwargs)

Bases: IndexPage

Represents the admin index page in the Django admin interface.

This class is responsible for representing and interacting with the admin index page in a web-driven testing environment. It utilizes configurations specified in the GeneralAdminModelConfig to auto-determine applicable URL schema and other information.

Variables:

admin_config – Stores the general admin configuration settings.

property applicable_on_url_schema: Url | List[Url]

This method needs to be overwritten by child classes. It should return one or more balderhub.url.lib.utils.Url objects that describe a schema, on which this page is applicable.

For example:

from balderhub.html.lib.scenario_features import HtmlPage
from balderhub.url.lib.utils import Url

class MyPage(HtmlPage):

    def applicable_on_url_schema(self) -> Url:
        return Url('http://example.com/article/<int:article_id>/')

This makes the page applicable on domains like http://example.com/article/1/ or also http://example.com/article/555/, but not on http://example.com/article/a/.

Returns:

a specific balderhub.url.lib.utils.Url object or a list of it

open()

Opens the URL specified by the applicable URL schema.

The method utilizes the stored URL schema to navigate to the target location using the associated driver. The navigation process is expected to adhere to the format and structure defined in the URL schema.

class balderhub.django.contrib.crud.pages.admin.AutoAddItemFormPage(**kwargs)

Bases: ChangeFormPage

Represents a page for adding an item via the Django admin interface.

This class models the behavior and attributes relevant for an admin page where items can be added. It is specifically designed to integrate with Balderhub’s Django utilities and manage navigation to the appropriate admin URL for adding new items.

admin_config = <balderhub.django.contrib.crud.scenario_features.general_admin_model_config.GeneralAdminModelConfig object>

main configuration object containing information about the admin panel, such as root URL, app and model name

property applicable_on_url_schema: Url | List[Url]

This method needs to be overwritten by child classes. It should return one or more balderhub.url.lib.utils.Url objects that describe a schema, on which this page is applicable.

For example:

from balderhub.html.lib.scenario_features import HtmlPage
from balderhub.url.lib.utils import Url

class MyPage(HtmlPage):

    def applicable_on_url_schema(self) -> Url:
        return Url('http://example.com/article/<int:article_id>/')

This makes the page applicable on domains like http://example.com/article/1/ or also http://example.com/article/555/, but not on http://example.com/article/a/.

Returns:

a specific balderhub.url.lib.utils.Url object or a list of it

open()

Opens the URL specified by the applicable URL schema.

The method utilizes the stored URL schema to navigate to the target location using the associated driver. The navigation process is expected to adhere to the format and structure defined in the URL schema.

class balderhub.django.contrib.crud.pages.admin.AutoChangeItemFormPage(**kwargs)

Bases: ChangeFormPage

Represents a page for changing an item in the Django admin interface.

Provides functionality to interact with the Django admin change item page. Utilizes a configurable URL schema and navigation method to allow access to the relevant page in the admin interface.

property applicable_on_url_schema: Url | List[Url]

This method needs to be overwritten by child classes. It should return one or more balderhub.url.lib.utils.Url objects that describe a schema, on which this page is applicable.

For example:

from balderhub.html.lib.scenario_features import HtmlPage
from balderhub.url.lib.utils import Url

class MyPage(HtmlPage):

    def applicable_on_url_schema(self) -> Url:
        return Url('http://example.com/article/<int:article_id>/')

This makes the page applicable on domains like http://example.com/article/1/ or also http://example.com/article/555/, but not on http://example.com/article/a/.

Returns:

a specific balderhub.url.lib.utils.Url object or a list of it

open(item_id: int)

Navigates to the URL of a specific item based on the provided item ID. The URL is constructed using the application’s configuration parameters and the item ID supplied.

Parameters:

item_id – The unique identifier of the item to navigate to.

class balderhub.django.contrib.crud.pages.admin.AutoChangeListPage(**kwargs)

Bases: ChangeListPage

Represents an admin change list page in a Django-based application.

This class provides functionality to interact with the admin change list page and navigate to it dynamically based on the application and model names.

property applicable_on_url_schema: Url | List[Url]

This method needs to be overwritten by child classes. It should return one or more balderhub.url.lib.utils.Url objects that describe a schema, on which this page is applicable.

For example:

from balderhub.html.lib.scenario_features import HtmlPage
from balderhub.url.lib.utils import Url

class MyPage(HtmlPage):

    def applicable_on_url_schema(self) -> Url:
        return Url('http://example.com/article/<int:article_id>/')

This makes the page applicable on domains like http://example.com/article/1/ or also http://example.com/article/555/, but not on http://example.com/article/a/.

Returns:

a specific balderhub.url.lib.utils.Url object or a list of it

open()

Opens the URL specified by the applicable URL schema.

The method utilizes the stored URL schema to navigate to the target location using the associated driver. The navigation process is expected to adhere to the format and structure defined in the URL schema.

CRUD Scenario Features

class balderhub.django.contrib.crud.scenario_features.GeneralAdminModelConfig(**kwargs)

Bases: GeneralAdminModelConfig

This class provides configuration for administrative models wherein it defines important settings, including root URL, application name, field formats, and field handling in django admin pages. It ensures compatibility with Django’s field processing.

property admin_root_url: Url

the root URL for administrative actions related to the model.

property app_name

the name of the application associated with the model.

get_collector_type_convertion_cb(for_field: LookupFieldString | str) Callable | None

Determines and provides a type conversion callback function for a given field, based on its specified data type. This function supports type conversion for basic data types, including strings, numbers, dates, and lists of these types, allowing custom processing of values as required for specific fields.

Parameters:

for_field – The field for which to determine the type conversion callback. It can be of type LookupFieldString or str.

Returns:

A callable function capable of converting input data to the expected type, or None if no conversion is necessary or possible for the specified type. Can directly be used for field-callbacks within item-mapping.

get_django_field_name_for_field(field: LookupFieldString | str) str

Converts a specific data item field into the corresponding Django field name string used for its fields and columns.

Parameters:

field – The field to be converted. It can be either an instance of LookupFieldString or a string.

Returns:

A string representing the Django field name.

get_multiple_read_fields() list[str]

Provides the list of field names, representing the fields that are expected to be visible within the multiple-read view (list view) of the admin interface

get_single_create_fields() list[str]

Provides the list of field names, representing the fields that are expected to be visible within the single create view (adding new item over detail view) of the admin interface

get_single_read_fields() list[str]

Provides the list of field names, representing the fields that are expected to be visible within the single-read view (detail view) of the admin interface

get_single_update_fields() list[str]

Provides the list of field names, representing the fields that are expected to be writable within the update view (detail view) of the admin interface

property model_name

the name of the model.

property read_date_format: list[str]
Returns:

A list of date format strings. These formats are the accepted formats for parsing read data formats.

property read_datetime_format: list[str]
Returns:

Provides a property method to retrieve a list of datetime formats for reading and parsing various datetime string formats. These formats are the accepted formats for parsing read data formats.

property write_date_format

the format string for dates displayed in the admin interface

property write_datetime_format

the format string for date and time displayed in the admin interface.

CRUD Setup Features

class balderhub.django.contrib.crud.setup_features.AdminMultipleReader(**kwargs)

Bases: MultipleReaderFeature

This is an auto feature providing functionality for handling multiple read operations within the admin interface. You can use this class without modifications if your django admin view has the default configuration.

This class extends the MultipleReaderFeature and provides functionality for managing pages, retrieving fields, item mappings, and handling success and error messages in the context of a Django admin interface.

admin_config = <balderhub.django.contrib.crud.scenario_features.general_admin_model_config.GeneralAdminModelConfig object>

an instance of GeneralAdminModelConfig that holds configurations and settings related to the admin model.

get_active_error_messages() ResponseMessageList
Returns:

returns a list of all active error messages

get_active_success_messages() ResponseMessageList
Returns:

returns a list of all active success messages

get_list_item_element_container()

this callback collects the data of the table and returns a dictionary with the unique id as key and the data as value

get_non_collectable_fields()

This method should return a list of field names that are not collectable by this feature. Note that the method will assign the NOT_DEFINABLE object to them.

You can provide lookup strings for this field too. If the field is a nested data item, the feature will automatically resolve the nested fields.

Returns:

returns a list of fields that are not collectable with this feature

item_mapping()

returns a dictionary with the dataclass field name as key and the callback that returns the data for this field as value - the value is a tuple with the callback on the first place and the parameter afterwards

load()

Loads the system-under-test to be in the state for collecting the data items.

page = <balderhub.django.contrib.crud.pages.admin.auto_change_list_page.AutoChangeListPage object>

reference to the AdminChangeListPage object for interacting with the admin change list page.

class balderhub.django.contrib.crud.setup_features.AdminSingleCreator(**kwargs)

Bases: SingleCreatorFeature

This is an auto feature providing functionality for managing a single administrative item creation setup. You can use this class without modifications if your django admin view has the default configuration.

This class extends the SingleCreatorFeature and provides specific functionality for interacting with admin configuration and form pages in a structured way.

admin_config = <balderhub.django.contrib.crud.scenario_features.general_admin_model_config.GeneralAdminModelConfig object>

main configuration object containing settings related to the admin model.

get_active_error_messages() ResponseMessageList
Returns:

returns a list of all active error messages

get_active_success_messages() ResponseMessageList
Returns:

returns a list of all active success messages

get_element_container()

This method returns a custom object that will be given to any callback. :return:

get_expected_default_values_for_fields() dict[str, Any]
Returns:

returns a dictionary of expected default values for fields in the system-under-test.

get_expected_error_message_for_missing_mandatory_field(data: dict[str, Any], without_mandatory_field: str) ResponseMessageList

This method returns a list of expected error messages if one mandatory field is missing. :param data: the invalid data item that was filled :param without_mandatory_field: the mandatory field that is missing. :return: a list of expected error messages

get_non_fillable_fields() list[str]

This method should return a list of field names that are not fillable with this feature. Note that the method will assign the NOT_DEFINABLE object to the filled-field object.

You can provide lookup strings for this field too.

Returns:

returns a list of fields that are not collectable with this feature

item_mapping()

returns a dictionary with the dataclass field name as key and its configuration as value

load(**kwargs)

Loads the system-under-test to be in the state for filling the data item.

page = <balderhub.django.contrib.crud.pages.admin.auto_add_item_form_page.AutoAddItemFormPage object>

the form page object used to interact with the admin form interface.

property resolved_fillable_fields: list[balderhub.data.lib.utils.lookup_field_string.LookupFieldString]
Returns:

a full resolved list of fields that are fillable with this feature

save() None

This method executes the final submit command to trigger the saving of the filled data items :return:

success_page = <balderhub.django.contrib.crud.pages.admin.auto_change_list_page.AutoChangeListPage object>

the page that should be open when the creation was successful (used for error messages)

class balderhub.django.contrib.crud.setup_features.AdminSingleReader(**kwargs)

Bases: SingleReaderFeature

This is an auto feature providing single-read access to admin forms. You can use this class without modifications if your django admin view has the default configuration.

This class is primarily designed for managing SingleReaderFeature behavior linked to admin forms. It uses an associated admin page and configuration to handle the loading and reading data on single admin items.

admin_config = <balderhub.django.contrib.crud.scenario_features.general_admin_model_config.GeneralAdminModelConfig object>

main configuration for admin model settings, containing details about fields and format specifications (e.g., date format).

get_active_error_messages() ResponseMessageList
Returns:

returns a list of all active error messages

get_active_success_messages() ResponseMessageList
Returns:

returns a list of all active success messages

get_element_container() ElementContainerTypeT

This method returns a custom object that will be given to any callback. :return:

get_non_collectable_fields() list[str]

This method should return a list of field names that are not collectable by this feature. Note that the method will assign the NOT_DEFINABLE object to them.

You can provide lookup strings for this field too. If the field is a nested data item, the feature will automatically resolve the nested fields.

Returns:

returns a list of fields that are not collectable with this feature

item_mapping()

returns a dictionary with the dataclass field name as key and the callback that returns the data for this field as value - the value is a tuple with the callback on the first place and the parameter afterwards

load(unique_identification_value: Any)

Loads the system-under-test to be in the state for collecting the data item.

page = <balderhub.django.contrib.crud.pages.admin.auto_change_item_form_page.AutoChangeItemFormPage object>

the page object representing the admin form page.

class balderhub.django.contrib.crud.setup_features.AdminSingleUpdater(**kwargs)

Bases: SingleUpdaterFeature

This is an auto feature providing functionality for managing and updating a single item in the admin interface. You can use this class without modifications if your django admin view has the default configuration.

This class is primarily designed for managing SingleUpdaterFeature behavior linked to admin forms. It uses an associated admin page and configuration to handle the loading, updating, and validation of data on single admin items.

admin_config = <balderhub.django.contrib.crud.scenario_features.general_admin_model_config.GeneralAdminModelConfig object>

main configuration for handling admin-specific settings for the model updates.

get_active_error_messages() ResponseMessageList
Returns:

returns a list of all active error messages

get_active_success_messages() ResponseMessageList
Returns:

returns a list of all active success messages

get_element_container() ElementContainerTypeT

This method returns a custom object that will be given to any callback. :return:

get_expected_error_message_for_missing_mandatory_field(data: dict[str, Any], without_mandatory_field: str) ResponseMessageList

This method returns a list of expected error messages if one mandatory field is missing. :param data: the invalid data item that was filled :param without_mandatory_field: the mandatory field that is missing. :return: a list of expected error messages

get_non_fillable_fields()

This method should return a list of field names that are not fillable with this feature. Note that the method will assign the NOT_DEFINABLE object to the filled-field object.

You can provide lookup strings for this field too.

Returns:

returns a list of fields that are not collectable with this feature

item_mapping() dict[str, balderhub.crud.lib.utils.field_callbacks.field_filler_callback.FieldFillerCallback]

returns a dictionary with the dataclass field name as key and its configuration as value

load(unique_identification_value: Any, **kwargs)

Loads the system-under-test to be in the state for filling the data item.

page = <balderhub.django.contrib.crud.pages.admin.auto_change_item_form_page.AutoChangeItemFormPage object>

represents the form page used to open and manage the item during updates.

save() None

This method executes the final submit command to trigger the saving of the filled data items :return:

success_page = <balderhub.django.contrib.crud.pages.admin.auto_change_list_page.AutoChangeListPage object>

the page that should be open when the update was successful (used for error messages)

CRUD Setup Features Factories

class balderhub.django.contrib.crud.setup_features.factories.AutoAdminMultipleReaderFactory

Bases: AutoFeatureFactory

Factory for creating data-item bounded setup-based config-feature AdminMultipleReader

class balderhub.django.contrib.crud.setup_features.factories.AutoAdminSingleCreatorFactory

Bases: AutoFeatureFactory

Factory for creating data-item bounded setup-based config-feature AdminSingleCreator

class balderhub.django.contrib.crud.setup_features.factories.AutoAdminSingleReaderFactory

Bases: AutoFeatureFactory

Factory for creating data-item bounded setup-based config-feature AdminSingleReader

class balderhub.django.contrib.crud.setup_features.factories.AutoAdminSingleUpdaterFactory

Bases: AutoFeatureFactory

Factory for creating data-item bounded setup-based config-feature AdminSingleUpdater

Field Callbacks

balderhub.django.contrib.crud.utils.field_callbacks.get_field_collector_callback_type_for(widget_type: type[html.HtmlElement] | type[change_form_fields.BaseChangeFormField]) type[FieldCollectorCallback]

Determine and return the appropriate field collector callback type for a given widget type. The function uses the widget type to identify its corresponding field collector callback. It supports multiple types of widgets, including date, foreign key, input, many-to-many, and textarea fields. If the widget type doesn’t match any of the predefined types, the function delegates the determination to the same function of the balderhub-html module.

Parameters:

widget_type – The class type of a widget, either an HTML element or a change form fieldset field.

Returns:

The corresponding field collector callback type for the given widget type.

balderhub.django.contrib.crud.utils.field_callbacks.get_field_filler_callback_type_for(widget_type: type[html.HtmlElement] | type[change_form_fields.BaseChangeFormField]) type[FieldFillerCallback]

Determines the appropriate callback type for filling fields, based on the provided widget type. The function maps specific widget types to their respective field filler callback classes. If the widget type is not recognized, it delegates the determination to the same function of the balderhub-html module.

Parameters:

widget_type – The type of widget for which the field filler callback type is to be determined. It must be either a subclass of HtmlElement or BaseChangeFormFieldsetField.

Returns:

The class type of the appropriate FieldFillerCallback for the given widget type.

class balderhub.django.contrib.crud.utils.field_callbacks.DjangoAdminDateCollectorFieldCallback(html_element: HtmlElement | Callable[[CallbackElementObjectT], HtmlElement], type_convert_cb: Callable[[Any], Any] | None = None, **kwargs)

Bases: BaseHtmlElemFieldCollectorCallback

Collects and processes data specifically for date-related HTML elements within a Django administration interface.

This callback class is tailored to extract input from date-specific fields, ensuring compatibility with Django forms and internal logic.

class balderhub.django.contrib.crud.utils.field_callbacks.DjangoAdminDateFillerFieldCallback(html_element: HtmlElement | Callable[[CallbackElementObjectT], HtmlElement], date_format: str, **kwargs)

Bases: BaseHtmlElemFieldFillerCallback

Handles filling and unsetting date picker fields in Django admin HTML elements.

This class is designed to handle operations related to the filling or unsetting of date input fields that exist within specific Django admin HTML elements. The primary purpose of this class is to abstract and streamline the interactions between HTML form elements and the data being manipulated within the context of a feature-based framework.

class balderhub.django.contrib.crud.utils.field_callbacks.DjangoAdminForeignkeyCollectorFieldCallback(html_element: HtmlElement | Callable[[CallbackElementObjectT], HtmlElement], type_convert_cb: Callable[[Any], Any] | None = None, **kwargs)

Bases: BaseHtmlElemFieldCollectorCallback

Callback implementation for collecting field values from HTML elements associated with Django admin ForeignKey fields.

This class serves a specialized purpose of extracting and processing field values for foreign key fields rendered as HTML in Django admin interfaces.

class balderhub.django.contrib.crud.utils.field_callbacks.DjangoAdminForeignkeyFillerFieldCallback(html_element: HtmlElement | Callable[[CallbackElementObjectT], HtmlElement], **kwargs)

Bases: BaseHtmlElemFieldFillerCallback

Callback class to handle filling and unsetting of HTML select elements in Django admin forms for foreign key fields.

This class is specifically designed for working with HTML elements associated with foreign key fields in the admin interface. It provides a mechanism to programmatically select values in these fields or unset them. The callback interacts with elements of type ForeignKeyChangeFormFieldsetField and ensures that the desired values are appropriately reflected in the HTML element.

class balderhub.django.contrib.crud.utils.field_callbacks.DjangoAdminInputCollectorFieldCallback(html_element: HtmlElement | Callable[[CallbackElementObjectT], HtmlElement], type_convert_cb: Callable[[Any], Any] | None = None, **kwargs)

Bases: BaseHtmlElemFieldCollectorCallback

Handles the collection of field values from specific HTML form elements in a Django admin interface.

This callback class is responsible for extracting data values from HTML input elements of the type InputChangeFormFieldsetField.

class balderhub.django.contrib.crud.utils.field_callbacks.DjangoAdminInputFillerFieldCallback(html_element: HtmlElement | Callable[[CallbackElementObjectT], HtmlElement], **kwargs)

Bases: BaseHtmlElemFieldFillerCallback

Callback class to handle filling and unsetting of HTML input elements in Django admin forms.

This class is specifically designed for working with HTML elements. It provides a mechanism to programmatically write values in these fields or reset them by clearing the content.

class balderhub.django.contrib.crud.utils.field_callbacks.DjangoAdminM2MCollectorFieldCallback(html_element: HtmlElement | Callable[[CallbackElementObjectT], HtmlElement], type_convert_cb: Callable[[Any], Any] | None = None, **kwargs)

Bases: BaseHtmlElemFieldCollectorCallback

Collects values from M2M (Many-to-Many) change form fieldset fields in Django Admin and allows extracting their current state through the implemented callback. This class is a specialization for handling HTML elements corresponding to many-to-many relationships in Django Admin interfaces.

Detailed description of the class, its purpose, and usage.

class balderhub.django.contrib.crud.utils.field_callbacks.DjangoAdminM2MFillerFieldCallback(html_element: HtmlElement | Callable[[CallbackElementObjectT], HtmlElement], **kwargs)

Bases: BaseHtmlElemFieldFillerCallback

Provides functionality to handle the filling and unsetting of fields in the Django admin interface specifically for many-to-many (M2M) field relationships. The class interacts with HTML elements associated with the M2M fields, enabling automation and manipulation of those fields.

class balderhub.django.contrib.crud.utils.field_callbacks.DjangoAdminTextareaCollectorFieldCallback(html_element: HtmlElement | Callable[[CallbackElementObjectT], HtmlElement], type_convert_cb: Callable[[Any], Any] | None = None, **kwargs)

Bases: BaseHtmlElemFieldCollectorCallback

Handles the collection of textarea field values from HTML elements in Django admin interfaces.

This class serves as a callback for collecting text field values from specified HTML elements in a Django admin context. It provides mechanisms to extract and return the text input value of textarea fields available within certain HTML element types.

class balderhub.django.contrib.crud.utils.field_callbacks.DjangoAdminTextareaFillerFieldCallback(html_element: HtmlElement | Callable[[CallbackElementObjectT], HtmlElement], **kwargs)

Bases: BaseHtmlElemFieldFillerCallback

DjangoAdminTextareaFillerFieldCallback class.

Provides a callback implementation for filling in or unsetting the value of a specific textarea HTML field type in Django admin interfaces. This class ensures interactions with allowed HTML element types, performing actions like inserting or clearing text values within the corresponding HTML textarea elements.

CRUD Utility Functions

balderhub.django.contrib.crud.utils.functions.convert_item_mapping_dict(item_mapping_as_flat_dict: dict[str, Any]) dict[str, Union[balderhub.crud.lib.utils.field_callbacks.nested.Nested, balderhub.crud.lib.utils.field_callbacks.field_collector_callback.FieldCollectorCallback, balderhub.crud.lib.utils.field_callbacks.field_filler_callback.FieldFillerCallback]]

Converts a flat dictionary of item mappings into a nested dictionary structure. Each key-value pair in the input dictionary is processed and reorganized into a hierarchical structure that represents nested objects. The final result maps the original keys to either nested structures or callable objects depending on the data.

Parameters:

item_mapping_as_flat_dict – A dictionary where the keys represent a flat structure and the values may contain various types, including callable objects or nested structures.

Returns:

A dictionary where the input’s flat key-value pairs are reorganized and nested. Keys map to values which can be instances of Nested, FieldCollectorCallback, or FieldFillerCallback, depending on the input data.

Raises:

TypeError – If the provided item_mapping_as_flat_dict is not of type dict.

balderhub.django.contrib.crud.utils.functions.extract_all_possible_schemas(of_pages: list[balderhub.html.lib.scenario_features.html_page.HtmlPage]) set[balderhub.url.lib.utils.url.Url]

Extracts all unique URL schemas applicable from a list of HtmlPage objects.

This function processes a list of HtmlPage instances and collects all the applicable URL schemas associated with each page. The applicable schemas from each page are added to a set, ensuring uniqueness, and the resulting set of schemas is returned.

Parameters:

of_pages – A list of HtmlPage objects from which to extract applicable URL schemas. Each HtmlPage instance provides either a single schema or a list of schemas that it is applicable to.

Returns:

A set of all unique URL schemas extracted from the provided pages.

balderhub.django.contrib.crud.utils.functions.get_success_messages_from(single_page: ChangeFormPage, list_page: ChangeListPage) ResponseMessageList

Retrieves success response messages from the provided pages if applicable.

This function determines which page, among the given single_page and list_page, is currently applicable and returns the corresponding success response messages. If neither page is applicable, an exception is raised indicating an unexpected page visibility.

Parameters:
  • single_page – The page of type ChangeFormPage to check for applicability and retrieve success messages from.

  • list_page – The page of type ChangeListPage to check for applicability and retrieve success messages from.

Returns:

A list of success response messages as an instance of ResponseMessageList.

Raises:

ValueError – If no applicable page is found and an unexpected page is visible.

balderhub.django.contrib.crud.utils.functions.get_error_messages_from(single_page: ChangeFormPage, list_page: ChangeListPage) ResponseMessageList

Gets error messages from either a ChangeFormPage or a ChangeListPage object.

This function inspects the given ChangeFormPage and ChangeListPage objects to retrieve visible error messages present on the respective pages. If the single_page is applicable, it fetches all field-level errors and global messages (excluding success messages). If the list_page is applicable instead, an empty list of error messages is returned. An exception is raised if neither of the provided pages is applicable.

Note

This message does not return error messages if the current visible page is the list-view.

Parameters:
  • single_page – A ChangeFormPage instance to check for applicable form field-level or global error messages.

  • list_page – A ChangeListPage instance to verify its applicability and return an empty response if applicable.

Returns:

A ResponseMessageList containing all collected error messages from the applicable page. Returns an empty list if the list_page is valid and no errors are found.