Configuration¶
django-pint-field provides three settings that can be configured in your Django project’s settings.py. All settings are optional and have sensible defaults.
Settings Overview¶
Setting |
Type |
Default |
Description |
|---|---|---|---|
|
|
|
The Pint unit registry used throughout the project |
|
|
|
Project-wide decimal precision; if > 0, sets Python’s decimal context precision |
|
|
|
Default Pint format string for displaying Quantity objects |
DJANGO_PINT_FIELD_UNIT_REGISTER¶
Controls which Pint UnitRegistry the package uses. The default registry is created with non_int_type=Decimal, so all numeric values use Python’s Decimal type.
You typically override this setting when you need custom units:
# settings.py
from pint import UnitRegistry
from decimal import Decimal
custom_ureg = UnitRegistry(non_int_type=Decimal)
# Define custom units
custom_ureg.define("serving = [serving]")
custom_ureg.define("scoop = 2 * serving")
custom_ureg.define("dozen = 12 * serving")
DJANGO_PINT_FIELD_UNIT_REGISTER = custom_ureg
All PintFields in the project share this registry. Once set, the custom units are available everywhere.
For more on defining units, see the Pint documentation on custom units.
DJANGO_PINT_FIELD_DECIMAL_PRECISION¶
Sets the precision for Python’s decimal context. When set to a value greater than 0, the package calls getcontext().prec = value at startup.
# settings.py
# Use Python's default precision (28 digits)
DJANGO_PINT_FIELD_DECIMAL_PRECISION = 0
# Or set a higher precision for scientific applications
DJANGO_PINT_FIELD_DECIMAL_PRECISION = 40
This affects all Decimal operations in the process, not just django-pint-field. Set it only if you need precision beyond the default 28 digits.
DJANGO_PINT_FIELD_DEFAULT_FORMAT¶
Controls the default string representation of Quantity objects. This uses Pint’s format specification.
Common format strings:
Format |
Example Output |
Description |
|---|---|---|
|
|
Default format |
|
|
Pretty format |
|
|
Pretty format with abbreviated units |
|
|
Compact format |
|
|
HTML format |
# settings.py
DJANGO_PINT_FIELD_DEFAULT_FORMAT = "~P" # Use abbreviated units
Complete Example¶
# settings.py
from pint import UnitRegistry
from decimal import Decimal
# Create a custom registry with Decimal support
custom_ureg = UnitRegistry(non_int_type=Decimal)
custom_ureg.define("serving = [serving]")
# Configure django-pint-field
DJANGO_PINT_FIELD_UNIT_REGISTER = custom_ureg
DJANGO_PINT_FIELD_DECIMAL_PRECISION = 40
DJANGO_PINT_FIELD_DEFAULT_FORMAT = "D"