API Reference¶
Auto-generated reference documentation from source code. For a guided walkthrough of settings, see Configuration Reference.
django_tenant_options¶
Initialise the Django Tenant Options package.
admin.py¶
Admin classes for the Django Tenant Options package.
- class django_tenant_options.admin.BaseOptionsAdmin(model, admin_site)[source]¶
Base class for Options Admin classes.
- class django_tenant_options.admin.BaseOptionsAdminMixin[source]¶
Mixin providing functionality specific to Options models.
app_settings.py¶
Namespaced settings for the django-tenant-options app.
Here is what it should look like in the settings.py file of the project:
DJANGO_TENANT_OPTIONS = {
"TENANT_MODEL": "example.Tenant",
# ...
}
- django_tenant_options.app_settings.ASSOCIATED_TENANTS_RELATED_NAME = '%(app_label)s_%(class)s_selections'¶
The related name template for the associated tenants model.
This is used for the ManyToManyField from an Option model to a Tenant model.
- Type:
- django_tenant_options.app_settings.ASSOCIATED_TENANTS_RELATED_QUERY_NAME = '%(app_label)s_%(class)ss_selected'¶
The related query name template for the associated tenants model.
This is used for the ManyToManyField from an Option model to a Tenant model.
- Type:
- django_tenant_options.app_settings.CACHE_ALIAS = 'default'¶
Which Django cache (from settings.CACHES) to use. Defaults to ‘default’.
- Type:
- django_tenant_options.app_settings.CACHE_KEY_PREFIX = 'dto'¶
Prefix applied to every cache key written by this package. Defaults to ‘dto’.
- Type:
- django_tenant_options.app_settings.CACHE_OPTIONS = False¶
Master switch for per-tenant option caching. Defaults to False (opt-in).
When True, OptionQuerySet.options_for_tenant and selected_options_for_tenant cache their results per tenant. Cached entries are invalidated automatically via post_save/post_delete signals on Option and Selection models. When False, query behavior is identical to the uncached logic.
- Type:
- django_tenant_options.app_settings.CACHE_TIMEOUT = 300¶
Time-to-live in seconds for cached per-tenant option lists. Defaults to 300.
- Type:
- django_tenant_options.app_settings.DB_VENDOR_OVERRIDE = None¶
The database vendor to use for generating triggers if the default is not one of the supported vendors.
In some cases, you may use a custom database backend, but the underlying database is still one of the supported vendors. In this case, you can specify that supported database vendor here.
An example of this is if you are using Django’s Postgis backend, but the underlying database is still PostgreSQL.
Allowed values are ‘postgresql’, ‘mysql’, ‘sqlite’, ‘oracle’.
- Type:
- django_tenant_options.app_settings.DEFAULT_MULTIPLE_CHOICE_FIELD¶
The default form field to use for multiple choice fields. This can also be overridden per form.
- django_tenant_options.app_settings.DISABLE_FIELD_FOR_DELETED_SELECTION = False¶
The behavior to use in user-facing forms when a selection was deleted by the tenant.
By default, if a selection was deleted, the user must select a new option when updating a form. If this setting is True, the deleted selection will be displayed in the form, but disabled so it cannot be changed.
In both cases, the deleted selection cannot be used in new forms.
- Type:
- django_tenant_options.app_settings.FOREIGNKEY_CLASS¶
The ForeignKey field class to use. Defaults to django.db.models.ForeignKey.
- django_tenant_options.app_settings.MANAGER_CLASS¶
The base Manager class to use. Defaults to django.db.models.Manager.
- django_tenant_options.app_settings.MODEL_CLASS¶
The base Model class to use. Defaults to django.db.models.Model.
- class django_tenant_options.app_settings.ModelClassConfig[source]¶
Configuration class for model base classes.
- django_tenant_options.app_settings.ONETOONEFIELD_CLASS¶
The OneToOneField field class to use. Defaults to django.db.models.OneToOneField.
- django_tenant_options.app_settings.OPTION_MODEL_RELATED_NAME = '%(app_label)s_%(class)s_related'¶
The related name template to use for all Option models.
- Type:
- django_tenant_options.app_settings.OPTION_MODEL_RELATED_QUERY_NAME = '%(app_label)s_%(class)ss'¶
The related query name template to use for all Option models.
- Type:
- django_tenant_options.app_settings.OPTION_ON_DELETE(collector, field, sub_objs, using)¶
What should happen to Selections when a related Option is deleted.
By default, Options are soft-deleted, so this setting is not used.
This sets the on_delete option for the option ForeignKey field on Selection models, and should use one of [django’s standard on_delete arguments](https://docs.djangoproject.com/en/dev/ref/models/fields/#arguments) (e.g. models.CASCADE, models.PROTECT, models.SET_NULL, etc).
- django_tenant_options.app_settings.QUERYSET_CLASS¶
The base QuerySet class to use. Defaults to django.db.models.QuerySet.
- django_tenant_options.app_settings.TENANT_MODEL = 'example.Tenant'¶
The model to use for the tenant.
- Type:
- django_tenant_options.app_settings.TENANT_MODEL_RELATED_NAME = '%(app_label)s_%(class)s_related'¶
The related name template for the tenant model.
- Type:
- django_tenant_options.app_settings.TENANT_MODEL_RELATED_QUERY_NAME = '%(app_label)s_%(class)ss'¶
The related query name template for the tenant model.
- Type:
- django_tenant_options.app_settings.TENANT_ON_DELETE(collector, field, sub_objs, using)¶
What should happen to Options and Selections when a related Tenant is deleted.
This sets the on_delete option for the tenant ForeignKey field on these models, and should use one of [django’s standard on_delete arguments](https://docs.djangoproject.com/en/dev/ref/models/fields/#arguments) (e.g. models.CASCADE, models.PROTECT, models.SET_NULL, etc).
exceptions.py¶
Exceptions for the Django Tenant Options package.
- exception django_tenant_options.exceptions.IncorrectSubclassError[source]¶
Used when the value of option_model is not a subclass of the correct abstract model.
- exception django_tenant_options.exceptions.InvalidDefaultOptionError[source]¶
Used when a default option defined in a model is not OptionType.MANDATORY or OptionType.OPTIONAL.
- exception django_tenant_options.exceptions.ModelClassParsingError[source]¶
Used when a model class cannot be parsed from the option provided.
forms.py¶
Forms for the Django Tenant Options package.
- class django_tenant_options.forms.AccessibleFormMixin[source]¶
Opt-in mixin that links validation errors to their inputs for assistive tech.
When a field fails validation, screen readers are not told unless the input carries
aria-invalidand points to its error text viaaria-describedby. Django does not do this automatically. Mix this in (beforeforms.Formorforms.ModelForm) to get it for free:class MyForm(AccessibleFormMixin, forms.ModelForm): ...
Render the matching error container with the id this mixin references, e.g.:
<ul id="id_{{ field.html_name }}_errors" role="alert">...</ul>
- add_error(field, error)[source]¶
Wire aria-invalid/aria-describedby onto every errored field’s widget.
This inspects
self.errorsrather than only thefieldargument, so it also covers errors raised as a dict (add_error(None, {...})) and the per-field errorsModelFormvalidation raises internally - the commonclean()idioms that a single-field check would miss. Non-field errors (keyed underNON_FIELD_ERRORS) are skipped because they have no widget to annotate. Thearia-describedbyid matches the documentedid_{{ field.html_name }}_errorscontainer so it is prefix-aware.
- class django_tenant_options.forms.OptionCreateFormMixin(*args, **kwargs)[source]¶
Used in forms that allow a tenant to create a new custom option.
- It requires a tenant argument to be passed from the view. This should be an instance of the model
class provided in the tenant_model parameter of the concrete OptionModel.
- The form will set the option_type field to OptionType.CUSTOM and the tenant field to the tenant instance,
using a HiddenInput widget.
Usage:
class MyOptionCreateForm(OptionCreateFormMixin, forms.ModelForm): class Meta: model = MyConcreteOptionModel fields = "__all__" def my_options_view(request): form = MyOptionCreateForm(request.POST, tenant=request.user.tenant)
- class django_tenant_options.forms.OptionFormMixin(*args, **kwargs)[source]¶
Base mixin for all Option forms.
- class django_tenant_options.forms.OptionUpdateFormMixin(*args, **kwargs)[source]¶
Used in forms that allow a tenant to update an existing custom option.
Has the same operation and requirements as OptionCreateFormMixin, but also allows the option to be deleted.
Usage:
class MyOptionUpdateForm(OptionUpdateFormMixin, forms.ModelForm): class Meta: model = MyConcreteOptionModel fields = "__all__" def my_options_view(request, option_id): option = MyConcreteOptionModel.objects.get(id=option_id) form = MyOptionUpdateForm(request.POST, instance=option, tenant=request.user.tenant)
- class django_tenant_options.forms.SelectionsForm(*args, **kwargs)[source]¶
Creates a form with a selections field for managing tenant selections.
- __init__(*args, **kwargs)[source]¶
Initialize the form with the tenant and set the selections field.
- property media¶
Return all media required to render the widgets on this form.
- class django_tenant_options.forms.TenantFormBaseMixin(*args, **kwargs)[source]¶
Base mixin that checks for a valid tenant value passed from the view and hides the tenant field.
form_fields.py¶
Custom form fields for the django_tenant_options app.
- class django_tenant_options.form_fields.GroupedModelChoiceIterator(field)[source]¶
Yields choices grouped into
<optgroup>tuples.The grouping key is read from the field’s
group_byattribute (a string, default"option_type").When
group_by == "option_type", each group’s value is mapped to its human label viadict(OptionType.choices)and groups are ordered Mandatory -> Optional -> Custom.For any other attribute, objects are grouped by
getattr(obj, group_by, ""). An empty/missing value is bucketed under the label"Uncategorized"and the remaining group labels are sorted alphabetically.
Within each group, the queryset’s own ordering is preserved.
- class django_tenant_options.form_fields.GroupedOptionsModelMultipleChoiceField(*args, group_by='option_type', **kwargs)[source]¶
A multiple-choice field that renders selectable options inside
<optgroup>groups.Drop-in replacement for
OptionsModelMultipleChoiceField. Setgroup_byto choose the grouping key (default"option_type"). The inheritedlabel_from_instanceis preserved, so option labels still show the type suffix (for example"High (mandatory)") inside each group.- __init__(*args, group_by='option_type', **kwargs)[source]¶
Store the grouping key before delegating to the parent field.
- iterator¶
alias of
GroupedModelChoiceIterator
helpers.py¶
Helper functions for the django_tenant_options app.
- django_tenant_options.helpers.all_option_subclasses()[source]¶
Returns a list of model classes that subclass AbstractOption.
- django_tenant_options.helpers.all_selection_subclasses()[source]¶
Returns a list of model classes that subclass AbstractSelection.
- django_tenant_options.helpers.get_default_option_names(option_model)[source]¶
Return the sorted list of default option names for a concrete Option model.
Reads the
default_optionsclass dict on the given model and returns its keys sorted alphabetically. Returns an empty list when the model defines no defaults.
models.py¶
Models for the Django Tenant Options app.
- class django_tenant_options.models.AbstractOption(*args, **kwargs)[source]¶
Abstract model for defining all available Options.
Options which are provided by default through model configuration may be Mandatory or Optional.
Using instance.delete() only soft-deletes the option.
- Parameters:
option_type (CharField) – Option Type
name (CharField) – Option Name
deleted (DateTimeField) – When was this option deleted? Leave blank for active options.
- class Meta[source]¶
Meta options for AbstractOption.
Subclass this in your concrete model’s Meta class to enforce constraints on the model.
- classmethod check(**kwargs)[source]¶
Check that the model has at least one manager that inherits from OptionManager and uses OptionQuerySet.
- delete(using=None, keep_parents=False, override=False)[source]¶
Delete the option, with option for hard delete.
- Parameters:
using – Database alias to use
keep_parents – Whether to keep parent models
override – If True, perform a hard delete. Otherwise, perform a soft delete.
- class django_tenant_options.models.AbstractSelection(*args, **kwargs)[source]¶
Identifies all selected Options for a given tenant, which it’s users can then choose from.
- A single tenant can select multiple Options. This model is a through model for the ManyToManyField
between the Tenant and the Option.
- Parameters:
deleted (DateTimeField) – When was this selection deleted? Leave blank for active selections.
- class Meta[source]¶
Meta options for AbstractSelection.
Subclass this in your concrete model’s Meta class to enforce constraints on the model.
- classmethod check(**kwargs)[source]¶
Check that model has at least one manager that inherits from SelectionManager and uses SelectionQuerySet.
- delete(using=None, keep_parents=False, override=False)[source]¶
Delete the selection, with option for hard delete.
- Parameters:
using – Database alias to use
keep_parents – Whether to keep parent models
override – If True, perform a hard delete. Otherwise, perform a soft delete
- django_tenant_options.models.METADATA_FIELD_NAMES = ('description', 'help_text', 'sort_order', 'category')¶
default_options keys that are persisted onto the Option row when the model defines them.
- class django_tenant_options.models.OptionManager(*args, **kwargs)[source]¶
Manager for Option models.
Provides methods for creating default options and filtering out deleted options.
Subclass this manager to provide additional functionality for your concrete Option model.
- create_for_tenant(tenant, name)[source]¶
Provided a tenant and a option name, creates the new option for that tenant.
- Parameters:
name (str)
- class django_tenant_options.models.OptionModelBase(name, bases, attrs, **kwargs)[source]¶
Metaclass for defining the default options available to all tenants.
Extends TenantOptionsCoreModelBase, which provides a ForeignKey to the tenant model in model metaclasses.
- Used to add a ManyToManyField from concrete classes of AbstractOption the Tenant model, through a concrete class
of AbstractSelection.
- Within the model, set the selection_model parameter to the concrete class inheriting AbstractSelection
and tenant_model to the tenant model to be used for both concrete classes.
For instance:
class ConcreteOption(AbstractOption): tenant_model = "myapp.Tenant" selection_model = "myapp.ConcreteSelection"
- class django_tenant_options.models.OptionQuerySet(model=None, query=None, using=None, hints=None)[source]¶
Custom QuerySet for Option models.
Subclass this QuerySet to provide additional functionality for your concrete Option model.
- delete(override=False)[source]¶
Delete the records in the current QuerySet.
- Parameters:
override – If True, perform a hard delete. Otherwise, perform a soft delete.
- options_for_tenant(tenant, include_deleted=False)[source]¶
Returns all available options for a given tenant, as below.
all required default options
all non-required default options
all tenant-specific options for this tenant
Set include_deleted=True to include deleted options.
- Return type:
- selected_options_for_tenant(tenant, include_deleted=False)[source]¶
Returns a QuerySet of the AbstractOption subclassed model.
Includes all selected options for a given tenant, including:
all mandatory default options
all selected optional default options for this tenant
all selected custom options for this tenant
Set include_deleted=True to include deleted options.
- Return type:
- class django_tenant_options.models.SelectionManager(*args, **kwargs)[source]¶
Custom Manager for Selection models.
Subclass this manager to provide additional functionality for your concrete Selection model.
- options_for_tenant(tenant, include_deleted=False)[source]¶
Returns a QuerySet of the AbstractOption subclassed model.
Includes all available options for a given tenant, including:
all required default options
all non-required default options
all tenant-specific options
Set include_deleted=True to include deleted options.
- selected_options_for_tenant(tenant, include_deleted=False)[source]¶
Returns a QuerySet of the AbstractOption subclassed model.
Includes all selected options for a given tenant, including:
all mandatory default options
all selected optional default options for this tenant
all selected custom options for this tenant
Set include_deleted=True to include deleted options.
- class django_tenant_options.models.SelectionModelBase(name, bases, attrs, **kwargs)[source]¶
Metaclass for defining which options have been selected for a given tenant.
Extends TenantOptionsCoreModelBase, which provides a ForeignKey to the tenant model in model metaclasses.
- Used to set up the ManyToManyField from concrete classes of AbstractSelection
to concrete classes of AbstractOption.
- Within the model, set the option_model parameter to the concrete class inheriting AbstractOption
and tenant_model to the model tenant which is associated with both concrete classes.
For instance:
class ConcreteSelection(AbstractSelection): tenant_model = "myapp.Tenant" option_model = "myapp.ConcreteOption"
- class django_tenant_options.models.SelectionQuerySet(model=None, query=None, using=None, hints=None)[source]¶
Custom QuerySet for Selection models.
Subclass this QuerySet to provide additional functionality for your concrete Selection model.
- class django_tenant_options.models.TenantOptionsCoreModelBase(name, bases, attrs, **kwargs)[source]¶
Base Metaclass for providing ForeignKey to a tenant model in other metaclasses.
- django_tenant_options.models.get_all_managers(model)[source]¶
Get all managers from a model using multiple approaches.
Skips managers that are known to intentionally not inherit from OptionManager/SelectionManager (e.g.
unscopedandprefetch_manager).
- django_tenant_options.models.get_constraint_dict()[source]¶
Return the constraint dictionary for the CheckConstraint in AbstractOption.
- django_tenant_options.models.make_check_constraint(condition, name)[source]¶
Create a CheckConstraint using the correct keyword for the installed Django version.
- django_tenant_options.models.validate_model_has_attribute(model, attr, attr_type=None)[source]¶
Raises an error if the provided model class does not contain the specified attribute with correct type.
If attr_type is not specified, the function only checks that the attribute is present.
- Parameters:
attr (str)
urls.py¶
URLs for the Django Tenant Options package.
views.py¶
Common Views for the Django Tenant Options package.
Commands¶
listoptions¶
syncoptions¶
- class django_tenant_options.management.commands.syncoptions.Command(stdout=None, stderr=None, no_color=False, force_color=False)[source]¶
Synchronizes the project’s Options Lists.
- print_all_pre_existing_deleted_options(ModelClass, updated_options)[source]¶
Prints all pre-existing deleted options not in the updated options.
- print_imported_or_verified_options(updated_options)[source]¶
Prints the imported or verified options.
validate_tenant_options¶
- class django_tenant_options.management.commands.validateoptions.Command(stdout=None, stderr=None, no_color=False, force_color=False)[source]¶
Validate django-tenant-options configuration.
See Commands for usage details and CI/CD integration.
maketriggers¶
- class django_tenant_options.management.commands.maketriggers.Command(*args, **kwargs)[source]¶
Management command to generate trigger migrations for AbstractSelection models.
This command identifies models that inherit from AbstractSelection and generates appropriate database trigger migrations to ensure data integrity between Tenants and their associated Options.
- __init__(*args, **kwargs)[source]¶
Initialize command with default values for all configuration options.
- add_arguments(parser)[source]¶
Add command-line arguments to the parser.
- Parameters:
parser (ArgumentParser) – The argument parser to add arguments to
- Return type:
None
maketriggers Options¶
- --app app_name¶
(str) Specify a specific app to create migrations for. If not provided, migrations for all apps will be created.
- --model ModelName¶
(str) Specify a specific model to create migrations for (format: app_label.ModelName). If not provided, migrations for all models will be created.
- --force¶
(bool) Force creation of migrations even if the trigger already exists.
- --dry-run¶
(bool) Simulate the migration creation process without writing any files. Use with –verbose to see the migration file content that would be created.
- --migration-dir directory¶
(str) Specify the directory to write the migration files to. Defaults to the app’s migrations directory.
- --db-vendor-override vendor¶
(str) Specify the database vendor to use for the migration file. Overrides the default database vendor detection and settings. Must be one of ‘postgresql’, ‘mysql’, ‘sqlite’, or ‘oracle’.
- --interactive¶
(bool) Prompt for confirmation before creating each migration.
- --verbose¶
(int) Provide detailed output of the migration creation process.
removetriggers¶
- class django_tenant_options.management.commands.removetriggers.Command(*args, **kwargs)[source]¶
Management command to generate migrations that remove previously created triggers.
This command scans existing migrations to identify triggers created by the maketriggers command and generates new migrations to remove them.
- __init__(*args, **kwargs)[source]¶
Initialize command with default values for all configuration options.
- add_arguments(parser)[source]¶
Add command-line arguments to the parser.
- Parameters:
parser (ArgumentParser) – The argument parser to add arguments to
- Return type:
None