API Reference

This section provides detailed API documentation for all modules, classes, and functions in django-app-parameter.

Models

The models module contains the core data models for storing parameters, validators, and history.

exception django_app_parameter.models.ParameterValueTypeError[source]

Bases: BaseException

Raised when a parameter value is of incorrect type

class django_app_parameter.models.Parameter(*args, **kwargs)[source]

Bases: Model

Base model for application parameters with typed value support.

Parameters are stored as strings in the database and converted to their appropriate Python types when accessed. Supports encryption, validation, and value history tracking.

The default value type is STR (string).

..todo::
  • Add validate_value methode to validate without setting value

  • add form field support

objects: ParameterManager = <django_app_parameter.managers.ParameterManager object>
name

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

slug

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

value_type

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

description

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

value

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

is_global

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

enable_cypher

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

enable_history

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

classmethod from_db(db, field_names, values)[source]

Create instance from database row and convert to appropriate proxy class.

This method is called by Django’s ORM when loading instances from the database. It automatically converts the instance to the correct proxy class based on the value_type field.

Return type:

Parameter

Parameters:
type: str = 'STR'
get_type()[source]

Return the TYPES value for this parameter.

Return type:

str

Returns:

The type code (e.g., ‘INT’, ‘STR’, etc.). Defaults to ‘STR’.

save(*args, **kwargs)[source]

Save the parameter, auto-generating slug and setting value_type.

Return type:

None

Parameters:
get()[source]

Get the parameter value converted to its native type.

Return type:

Any

set(new_value, auto_cast=False)[source]

Set the parameter value with type validation.

Parameters:
  • new_value (Any) – The new value to set.

  • auto_cast (bool) – If True, convert string value to native type before validation. Useful when setting from user input.

Raises:
  • ParameterValueTypeError – If value is not of expected type.

  • ValidationError – If value fails validator checks.

Return type:

None

to_dict(decrypt=True)[source]

Export this parameter instance to JSON-compatible dictionary.

Return type:

ParameterDict_

Returns:

Dictionary with all parameter fields and validators. Note: The value is exported in decrypted form for portability. History entries are NOT exported.

Parameters:

decrypt (bool)

from_dict(data, force_encrypt=False)[source]

Update this parameter instance from a dictionary.

Parameters:
  • data (ParameterDict_) – Dictionary containing parameter fields and optionally validators. The ‘slug’ and ‘value_type’ fields are ignored if the instance already exists (has a pk), as they should not be changed. Validators are always processed: if not present in data, existing validators are removed. History entries are NOT imported.

  • force_encrypt (bool) – If True, the ‘value’ field in data is treated as unencrypted and will be encrypted if ‘enable_cypher’ is True.

Return type:

None

__str__()[source]

Return the parameter name as string representation.

Return type:

str

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

get_value_type_display(*, field=<django.db.models.fields.CharField: value_type>)
history

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

validators

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

class django_app_parameter.models.ParameterValidator(*args, **kwargs)[source]

Bases: Model

Stores validator configuration for a Parameter

parameter

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

validator_type

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

validator_params

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

get_validator()[source]

Instantiate and return the validator based on type and params.

Supports both built-in Django validators and custom validators defined in DJANGO_APP_PARAMETER[‘validators’] setting.

Return type:

Callable[[Any], None]

Returns:

Callable validator function or instance

Raises:

ValueError – If validator_type is not found in built-in or custom validators

__str__()[source]

Return parameter name and validator display name.

Return type:

str

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>
parameter_id
class django_app_parameter.models.ParameterHistory(*args, **kwargs)[source]

Bases: Model

Stores historical values of a Parameter

parameter

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

value

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

modified_at

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

__str__()[source]

Return value and modification timestamp.

Return type:

str

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

get_next_by_modified_at(*, field=<django.db.models.fields.DateTimeField: modified_at>, is_next=True, **kwargs)
get_previous_by_modified_at(*, field=<django.db.models.fields.DateTimeField: modified_at>, is_next=False, **kwargs)
id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>
parameter_id
class django_app_parameter.models.ParameterInt(*args, **kwargs)[source]

Bases: Parameter

Proxy model for integer parameters.

type: str = 'INT'
exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

class django_app_parameter.models.ParameterStr(*args, **kwargs)[source]

Bases: Parameter

Proxy model for string parameters.

exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

class django_app_parameter.models.ParameterFloat(*args, **kwargs)[source]

Bases: Parameter

Proxy model for float parameters.

type: str = 'FLT'
exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

class django_app_parameter.models.ParameterDecimal(*args, **kwargs)[source]

Bases: Parameter

Proxy model for Decimal parameters.

type: str = 'DCL'
exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

class django_app_parameter.models.ParameterJson(*args, **kwargs)[source]

Bases: Parameter

Proxy model for JSON parameters.

type: str = 'JSN'
exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

class django_app_parameter.models.ParameterBool(*args, **kwargs)[source]

Bases: Parameter

Proxy model for boolean parameters.

type: str = 'BOO'
FALSY_VALUES = ['false', '0', 'no', 'off']
exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

class django_app_parameter.models.ParameterDate(*args, **kwargs)[source]

Bases: Parameter

Proxy model for date parameters.

type: str = 'DAT'
exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

class django_app_parameter.models.ParameterDatetime(*args, **kwargs)[source]

Bases: Parameter

Proxy model for datetime parameters.

type: str = 'DTM'
exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

class django_app_parameter.models.ParameterTime(*args, **kwargs)[source]

Bases: Parameter

Proxy model for time parameters.

type: str = 'TIM'
exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

class django_app_parameter.models.ParameterUrl(*args, **kwargs)[source]

Bases: Parameter

Proxy model for URL parameters with validation.

type: str = 'URL'
exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

class django_app_parameter.models.ParameterEmail(*args, **kwargs)[source]

Bases: Parameter

Proxy model for email parameters with validation.

type: str = 'EML'
exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

class django_app_parameter.models.ParameterList(*args, **kwargs)[source]

Bases: Parameter

Proxy model for comma-separated list parameters.

type: str = 'LST'
exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

class django_app_parameter.models.ParameterDict(*args, **kwargs)[source]

Bases: Parameter

Proxy model for dict parameters (suffixed to avoid conflict with TypedDict).

type: str = 'DCT'
exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

class django_app_parameter.models.ParameterPath(*args, **kwargs)[source]

Bases: Parameter

Proxy model for filesystem path parameters.

type: str = 'PTH'
exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

class django_app_parameter.models.ParameterDuration(*args, **kwargs)[source]

Bases: Parameter

Proxy model for duration parameters stored as seconds.

type: str = 'DUR'
exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

class django_app_parameter.models.ParameterPercentage(*args, **kwargs)[source]

Bases: Parameter

Proxy model for percentage parameters (0-100).

type: str = 'PCT'
exception DoesNotExist

Bases: DoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

Parameter Model

class django_app_parameter.models.Parameter(*args, **kwargs)[source]

Bases: Model

Base model for application parameters with typed value support.

Parameters are stored as strings in the database and converted to their appropriate Python types when accessed. Supports encryption, validation, and value history tracking.

The default value type is STR (string).

..todo::
  • Add validate_value methode to validate without setting value

  • add form field support

objects: ParameterManager = <django_app_parameter.managers.ParameterManager object>
name

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

slug

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

value_type

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

description

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

value

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

is_global

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

enable_cypher

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

enable_history

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

classmethod from_db(db, field_names, values)[source]

Create instance from database row and convert to appropriate proxy class.

This method is called by Django’s ORM when loading instances from the database. It automatically converts the instance to the correct proxy class based on the value_type field.

Return type:

Parameter

Parameters:
type: str = 'STR'
get_type()[source]

Return the TYPES value for this parameter.

Return type:

str

Returns:

The type code (e.g., ‘INT’, ‘STR’, etc.). Defaults to ‘STR’.

save(*args, **kwargs)[source]

Save the parameter, auto-generating slug and setting value_type.

Return type:

None

Parameters:
get()[source]

Get the parameter value converted to its native type.

Return type:

Any

set(new_value, auto_cast=False)[source]

Set the parameter value with type validation.

Parameters:
  • new_value (Any) – The new value to set.

  • auto_cast (bool) – If True, convert string value to native type before validation. Useful when setting from user input.

Raises:
  • ParameterValueTypeError – If value is not of expected type.

  • ValidationError – If value fails validator checks.

Return type:

None

to_dict(decrypt=True)[source]

Export this parameter instance to JSON-compatible dictionary.

Return type:

ParameterDict_

Returns:

Dictionary with all parameter fields and validators. Note: The value is exported in decrypted form for portability. History entries are NOT exported.

Parameters:

decrypt (bool)

from_dict(data, force_encrypt=False)[source]

Update this parameter instance from a dictionary.

Parameters:
  • data (ParameterDict_) – Dictionary containing parameter fields and optionally validators. The ‘slug’ and ‘value_type’ fields are ignored if the instance already exists (has a pk), as they should not be changed. Validators are always processed: if not present in data, existing validators are removed. History entries are NOT imported.

  • force_encrypt (bool) – If True, the ‘value’ field in data is treated as unencrypted and will be encrypted if ‘enable_cypher’ is True.

Return type:

None

__str__()[source]

Return the parameter name as string representation.

Return type:

str

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

get_value_type_display(*, field=<django.db.models.fields.CharField: value_type>)
history

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

validators

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

ParameterValidator Model

class django_app_parameter.models.ParameterValidator(*args, **kwargs)[source]

Bases: Model

Stores validator configuration for a Parameter

parameter

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

validator_type

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

validator_params

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

get_validator()[source]

Instantiate and return the validator based on type and params.

Supports both built-in Django validators and custom validators defined in DJANGO_APP_PARAMETER[‘validators’] setting.

Return type:

Callable[[Any], None]

Returns:

Callable validator function or instance

Raises:

ValueError – If validator_type is not found in built-in or custom validators

__str__()[source]

Return parameter name and validator display name.

Return type:

str

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>
parameter_id

ParameterHistory Model

class django_app_parameter.models.ParameterHistory(*args, **kwargs)[source]

Bases: Model

Stores historical values of a Parameter

parameter

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

value

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

modified_at

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

__str__()[source]

Return value and modification timestamp.

Return type:

str

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

get_next_by_modified_at(*, field=<django.db.models.fields.DateTimeField: modified_at>, is_next=True, **kwargs)
get_previous_by_modified_at(*, field=<django.db.models.fields.DateTimeField: modified_at>, is_next=False, **kwargs)
id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>
parameter_id

Admin

The admin module provides Django admin customization for parameter management.

Forms

The forms module provides a flexible system to create form fields adapted to each parameter type.

Forms and field configuration for django-app-parameter.

This module provides a flexible system to create form fields adapted to each parameter type. It can be used in Django Admin or in any custom form.

Usage in a custom form

from django import forms from django_app_parameter.forms import ParameterField from django_app_parameter.models import Parameter

class MySettingsForm(forms.Form):
def __init__(self, *args, **kwargs):

super().__init__(*args, **kwargs)

# Dynamically add a field for each parameter for param in Parameter.objects.filter(is_global=True):

self.fields[param.slug] = ParameterField(param)

Usage with a single parameter

from django_app_parameter.forms import ParameterField from django_app_parameter.models import Parameter

param = Parameter.objects.get(slug=”max-retries”) field = ParameterField(param) # Returns an IntegerField with initial=param.get(), required=False

class django_app_parameter.forms.FieldConfig(field_class=<class 'django.forms.fields.CharField'>, widget=None, extra_kwargs=<factory>, help_text='')[source]

Bases: object

Configuration for a form field associated with a parameter type.

Parameters:
  • field_class (type[Field])

  • widget (Widget | type[Widget] | None)

  • extra_kwargs (dict[str, Any])

  • help_text (str)

field_class

The Django form field class to use.

widget

Optional widget instance or class to use.

extra_kwargs

Additional keyword arguments for field instantiation.

help_text

Optional help text for the field.

field_class

alias of CharField

widget: Widget | type[Widget] | None = None
extra_kwargs: dict[str, Any]
help_text: str = ''
__init__(field_class=<class 'django.forms.fields.CharField'>, widget=None, extra_kwargs=<factory>, help_text='')
Parameters:
  • field_class (type[Field])

  • widget (Widget | type[Widget] | None)

  • extra_kwargs (dict[str, Any])

  • help_text (str)

Return type:

None

django_app_parameter.forms.get_field_config_for_type(value_type)[source]

Get the field configuration for a given parameter type.

Parameters:

value_type (str) – The parameter type (e.g., TYPES.INT, TYPES.STR).

Return type:

FieldConfig

Returns:

The FieldConfig for the given type, or DEFAULT_FIELD_CONFIG if unknown.

django_app_parameter.forms.create_parameter_field(parameter, **kwargs)[source]

Create a form field adapted to a Parameter’s value_type.

This factory function dynamically selects the appropriate field class and widget based on the parameter’s type.

Parameters:
  • parameter (Parameter) – The Parameter instance to create a field for.

  • **kwargs (Any) – Additional keyword arguments passed to the field. Common options: required, initial, help_text, widget, label.

Return type:

Field

Returns:

A configured Django form field instance of the appropriate type.

Example

>>> param = Parameter.objects.get(slug="max-retries")
>>> field = ParameterField(param)
>>> # Returns an IntegerField if param.value_type == TYPES.INT
>>> # Override default options
>>> field = ParameterField(param, required=True, help_text="Custom help")
class django_app_parameter.forms.ParameterCreateForm(*args, **kwargs)[source]

Bases: ModelForm

Form for creating a new Parameter with only essential fields.

Parameters:
  • args (Any)

  • kwargs (Any)

class Meta[source]

Bases: object

model

alias of Parameter

fields = ['name', 'slug', 'value_type', 'description', 'is_global', 'enable_cypher', 'enable_history']
help_texts = {'enable_cypher': 'Si activé, la valeur sera chiffrée en base de données', 'enable_history': 'Si activé, les modifications de valeur seront enregistrées', 'name': 'Nom du paramètre', 'slug': 'Laissez vide pour générer automatiquement depuis le nom', 'value_type': 'Le type ne pourra plus être modifié après création'}
__init__(*args, **kwargs)[source]
Parameters:
Return type:

None

base_fields = {'description': <django.forms.fields.CharField object>, 'enable_cypher': <django.forms.fields.BooleanField object>, 'enable_history': <django.forms.fields.BooleanField object>, 'is_global': <django.forms.fields.BooleanField object>, 'name': <django.forms.fields.CharField object>, 'slug': <django.forms.fields.SlugField object>, 'value_type': <django.forms.fields.TypedChoiceField object>}
declared_fields = {}
property media

Return all media required to render the widgets on this form.

class django_app_parameter.forms.ParameterEditForm(data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=<class 'django.forms.utils.ErrorList'>, label_suffix=None, empty_permitted=False, instance=None, use_required_attribute=None, renderer=None)[source]

Bases: ModelForm

Form for editing Parameter with custom validation.

class Meta[source]

Bases: object

model

alias of Parameter

fields = ['name', 'description', 'value', 'is_global', 'enable_cypher', 'enable_history']
clean_value()[source]

Validate the value field using the parameter’s validators.

Return type:

Any

base_fields = {'description': <django.forms.fields.CharField object>, 'enable_cypher': <django.forms.fields.BooleanField object>, 'enable_history': <django.forms.fields.BooleanField object>, 'is_global': <django.forms.fields.BooleanField object>, 'name': <django.forms.fields.CharField object>, 'value': <django.forms.fields.CharField object>}
declared_fields = {}
property media

Return all media required to render the widgets on this form.

class django_app_parameter.forms.ParameterValidatorForm(*args, **kwargs)[source]

Bases: ModelForm

Form for ParameterValidator with dynamic validator_type choices.

Parameters:
  • args (Any)

  • kwargs (Any)

class Meta[source]

Bases: object

model

alias of ParameterValidator

fields = ['validator_type', 'validator_params']
__init__(*args, **kwargs)[source]
Parameters:
Return type:

None

clean_validator_type()[source]

Validate that the validator_type exists in available validators.

Return type:

str

base_fields = {'validator_params': <django.forms.fields.JSONField object>, 'validator_type': <django.forms.fields.CharField object>}
declared_fields = {}
property media

Return all media required to render the widgets on this form.

FieldConfig

class django_app_parameter.forms.FieldConfig(field_class=<class 'django.forms.fields.CharField'>, widget=None, extra_kwargs=<factory>, help_text='')[source]

Bases: object

Configuration for a form field associated with a parameter type.

Parameters:
  • field_class (type[Field])

  • widget (Widget | type[Widget] | None)

  • extra_kwargs (dict[str, Any])

  • help_text (str)

field_class

The Django form field class to use.

widget

Optional widget instance or class to use.

extra_kwargs

Additional keyword arguments for field instantiation.

help_text

Optional help text for the field.

field_class

alias of CharField

widget: Widget | type[Widget] | None = None
extra_kwargs: dict[str, Any]
help_text: str = ''
__init__(field_class=<class 'django.forms.fields.CharField'>, widget=None, extra_kwargs=<factory>, help_text='')
Parameters:
  • field_class (type[Field])

  • widget (Widget | type[Widget] | None)

  • extra_kwargs (dict[str, Any])

  • help_text (str)

Return type:

None

create_parameter_field

django_app_parameter.forms.create_parameter_field(parameter, **kwargs)[source]

Create a form field adapted to a Parameter’s value_type.

This factory function dynamically selects the appropriate field class and widget based on the parameter’s type.

Parameters:
  • parameter (Parameter) – The Parameter instance to create a field for.

  • **kwargs (Any) – Additional keyword arguments passed to the field. Common options: required, initial, help_text, widget, label.

Return type:

Field

Returns:

A configured Django form field instance of the appropriate type.

Example

>>> param = Parameter.objects.get(slug="max-retries")
>>> field = ParameterField(param)
>>> # Returns an IntegerField if param.value_type == TYPES.INT
>>> # Override default options
>>> field = ParameterField(param, required=True, help_text="Custom help")

ParameterCreateForm

class django_app_parameter.forms.ParameterCreateForm(*args, **kwargs)[source]

Bases: ModelForm

Form for creating a new Parameter with only essential fields.

Parameters:
  • args (Any)

  • kwargs (Any)

class Meta[source]

Bases: object

model

alias of Parameter

fields = ['name', 'slug', 'value_type', 'description', 'is_global', 'enable_cypher', 'enable_history']
help_texts = {'enable_cypher': 'Si activé, la valeur sera chiffrée en base de données', 'enable_history': 'Si activé, les modifications de valeur seront enregistrées', 'name': 'Nom du paramètre', 'slug': 'Laissez vide pour générer automatiquement depuis le nom', 'value_type': 'Le type ne pourra plus être modifié après création'}
__init__(*args, **kwargs)[source]
Parameters:
Return type:

None

base_fields = {'description': <django.forms.fields.CharField object>, 'enable_cypher': <django.forms.fields.BooleanField object>, 'enable_history': <django.forms.fields.BooleanField object>, 'is_global': <django.forms.fields.BooleanField object>, 'name': <django.forms.fields.CharField object>, 'slug': <django.forms.fields.SlugField object>, 'value_type': <django.forms.fields.TypedChoiceField object>}
declared_fields = {}
property media

Return all media required to render the widgets on this form.

ParameterEditForm

class django_app_parameter.forms.ParameterEditForm(data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=<class 'django.forms.utils.ErrorList'>, label_suffix=None, empty_permitted=False, instance=None, use_required_attribute=None, renderer=None)[source]

Bases: ModelForm

Form for editing Parameter with custom validation.

class Meta[source]

Bases: object

model

alias of Parameter

fields = ['name', 'description', 'value', 'is_global', 'enable_cypher', 'enable_history']
clean_value()[source]

Validate the value field using the parameter’s validators.

Return type:

Any

base_fields = {'description': <django.forms.fields.CharField object>, 'enable_cypher': <django.forms.fields.BooleanField object>, 'enable_history': <django.forms.fields.BooleanField object>, 'is_global': <django.forms.fields.BooleanField object>, 'name': <django.forms.fields.CharField object>, 'value': <django.forms.fields.CharField object>}
declared_fields = {}
property media

Return all media required to render the widgets on this form.

ParameterValidatorForm

class django_app_parameter.forms.ParameterValidatorForm(*args, **kwargs)[source]

Bases: ModelForm

Form for ParameterValidator with dynamic validator_type choices.

Parameters:
  • args (Any)

  • kwargs (Any)

class Meta[source]

Bases: object

model

alias of ParameterValidator

fields = ['validator_type', 'validator_params']
__init__(*args, **kwargs)[source]
Parameters:
Return type:

None

clean_validator_type()[source]

Validate that the validator_type exists in available validators.

Return type:

str

base_fields = {'validator_params': <django.forms.fields.JSONField object>, 'validator_type': <django.forms.fields.CharField object>}
declared_fields = {}
property media

Return all media required to render the widgets on this form.

Utilities

The utils module contains helper functions for encryption, slugification, and validator management.

Utility functions for django-app-parameter.

django_app_parameter.utils.parameter_slugify(content)[source]

Transform content : * slugify (with django’s function) * upperise * replace dash (-) with underscore (_)

Return type:

str

Parameters:

content (str)

django_app_parameter.utils.get_setting(key, default=None)[source]

Get a value from DJANGO_APP_PARAMETER settings dictionary.

Parameters:
  • key (str) – The setting key to retrieve

  • default (Optional[Any]) – Default value if key is not found

Return type:

Any

Returns:

The setting value or default

Example

>>> get_setting("validators", {})
{'even_number': 'myapp.validators.validate_even_number'}
django_app_parameter.utils.import_validator(validator_path)[source]

Import a validator from a dotted path string.

Parameters:

validator_path (str) – Dotted path to the validator (e.g., ‘myapp.validators.validate_even_number’)

Return type:

Any

Returns:

The imported validator function or class

Raises:
  • ImportError – If the module or validator cannot be imported

  • AttributeError – If the validator doesn’t exist in the module

Example

>>> validator = import_validator("myapp.validators.validate_even_number")
>>> validator(4)  # Should not raise
>>> validator(3)  # Should raise ValidationError
django_app_parameter.utils.get_validator_from_registry(validator_type, use_cache=True)[source]

Get a validator by type from built-in or custom validators.

This function looks up validators in the following order: 1. Built-in Django validators (from BUILTIN_VALIDATORS) 2. Custom validators from settings (DJANGO_APP_PARAMETER[‘validators’])

Parameters:
  • validator_type (str) – The validator type/key to look up

  • use_cache (bool) – Whether to use cached imports (default: True)

Return type:

Optional[Any]

Returns:

The validator class/function, or None if not found

Example

>>> # Built-in validator
>>> validator = get_validator_from_registry("MinValueValidator")
>>> validator is MinValueValidator
True
>>> # Custom validator (from settings)
>>> validator = get_validator_from_registry("even_number")
>>> validator.__name__
'validate_even_number'
django_app_parameter.utils.get_available_validators()[source]

Get all available validators (built-in + custom) with their display names.

Returns a dictionary mapping validator keys to human-readable names. Built-in validators use their class/function names as display names. Custom validators use their keys as display names.

Returns:

display_name}

Return type:

Dictionary of {validator_key

Example

>>> validators = get_available_validators()
>>> "MinValueValidator" in validators
True
>>> "even_number" in validators  # If defined in settings
True
django_app_parameter.utils.clear_validator_cache()[source]

Clear the validator import cache.

Useful for testing or when validators are dynamically modified.

Return type:

None

django_app_parameter.utils.get_encryption_key(key=None)[source]

Get the encryption key from Django settings or use provided key.

The key should be stored in settings.DJANGO_APP_PARAMETER[‘encryption_key’] and must be a Fernet-compatible key (32 url-safe base64-encoded bytes).

Parameters:

key (Union[str, bytes, None]) – Optional encryption key to use. If provided, this key is used instead of the one from settings. Can be str or bytes.

Return type:

bytes

Returns:

The encryption key as bytes

Raises:

ImproperlyConfigured – If cryptography is not installed, or if the encryption key is not configured and no key parameter is provided

django_app_parameter.utils.encrypt_value(value, encryption_key=None)[source]

Encrypt a string value using Fernet symmetric encryption.

Parameters:
  • value (str) – The plaintext string to encrypt

  • encryption_key (Union[str, bytes, None]) – Optional encryption key to use. If not provided, uses key from settings.

Return type:

str

Returns:

The encrypted value as a string (base64-encoded)

Raises:

ImproperlyConfigured – If cryptography is not installed or if encryption key is not configured

django_app_parameter.utils.decrypt_value(encrypted_value, encryption_key=None)[source]

Decrypt a string value using Fernet symmetric encryption.

Parameters:
  • encrypted_value (str) – The encrypted value as a string (base64-encoded)

  • encryption_key (Union[str, bytes, None]) – Optional encryption key to use. If not provided, uses key from settings.

Return type:

str

Returns:

The decrypted plaintext string

Raises:
  • ImproperlyConfigured – If cryptography is not installed or if encryption key is not configured

  • cryptography.fernet.InvalidToken – If decryption fails (wrong key or corrupted data)

Context Processors

Template context processor for making global parameters available in templates.

django_app_parameter.context_processors.add_global_parameter_context(request)[source]
Return type:

dict[str, Any]

Parameters:

request (HttpRequest)

Management Commands

Command-line tools for importing and exporting parameters.

dap_load

Command to import parameters into the database

param –file:

a json file with all the parameter to be added

param –no-update:

flag to avoid updating existing parameters

param –json:

dict containing a new parameter’s values, can’t be use with –file

class django_app_parameter.management.commands.dap_load.Command(stdout=None, stderr=None, no_color=False, force_color=False)[source]

Bases: BaseCommand

help = 'Import parameters into the database'
add_arguments(parser)[source]

Entry point for subclassed commands to add custom arguments.

Return type:

None

Parameters:

parser (CommandParser)

handle(*args, **options)[source]

The actual logic of the command. Subclasses must implement this method.

Return type:

None

Parameters:

dap_dump

Command to export parameters from the database to a JSON file

param file:

path to the JSON file to create (required)

class django_app_parameter.management.commands.dap_dump.Command(stdout=None, stderr=None, no_color=False, force_color=False)[source]

Bases: BaseCommand

help = 'Export parameters from the database to a JSON file'
add_arguments(parser)[source]

Entry point for subclassed commands to add custom arguments.

Return type:

None

Parameters:

parser (CommandParser)

handle(*args, **options)[source]

The actual logic of the command. Subclasses must implement this method.

Return type:

None

Parameters:

dap_rotate_key

Command to rotate encryption key for encrypted parameters.

Two-step process for secure key rotation:

Step 1: Generate new key and backup old one

python manage.py dap_rotate_key - Backs up current key to dap_backup_key.json - Generates and displays new key - Shows next command to run

Step 2: Apply rotation with old key

python manage.py dap_rotate_key –old-key <key> - Decrypts with old key (from parameter) - Re-encrypts with new key (from settings)

param –old-key:

Old encryption key for decryption. When provided, performs step 2.

param –backup-file:

Path to backup file (default: dap_backup_key.json at project root)

class django_app_parameter.management.commands.dap_rotate_key.Command(stdout=None, stderr=None, no_color=False, force_color=False)[source]

Bases: BaseCommand

help = 'Rotate encryption key for encrypted parameters (two-step process)'
add_arguments(parser)[source]

Entry point for subclassed commands to add custom arguments.

Return type:

None

Parameters:

parser (CommandParser)

handle(*args, **options)[source]

The actual logic of the command. Subclasses must implement this method.

Return type:

None

Parameters:

AccessParameter Proxy

The AccessParameter class provides convenient attribute-style access to parameters.

class django_app_parameter.AccessParameter[source]

Bases: object

This class is a proxy to mimick Django’s settings. You will be able to read Parameter value through app_parameter.A_RANDOM_SLUG

__getattr__(slug)[source]
Return type:

Union[int, str, float, Decimal, bool, Any]

Parameters:

slug (str)