Translates Django models using a registration approach without modifying original model classes.
—
Utility functions for language handling, field name building, configuration management, and context-aware translation functionality.
Core utilities for managing language codes, validation, and retrieval.
def get_language():
"""
Get active language code guaranteed to be in AVAILABLE_LANGUAGES.
Returns:
- str: Active language code, falls back to DEFAULT_LANGUAGE
"""
def get_language_bidi(lang):
"""
Check if a language uses bidirectional text layout.
Parameters:
- lang: Language code (e.g., 'ar', 'he', 'en')
Returns:
- bool: True if language is bidirectional (RTL)
"""Usage Example:
from modeltranslation.utils import get_language, get_language_bidi
# Get current active language
current_lang = get_language() # Returns 'en', 'fr', etc.
# Check text direction for UI layout
is_rtl = get_language_bidi('ar') # True for Arabic
is_rtl = get_language_bidi('en') # False for EnglishFunctions for building and parsing localized field names.
def build_localized_fieldname(field_name, lang):
"""
Build localized field name by appending language code.
Parameters:
- field_name: Base field name (e.g., 'title')
- lang: Language code (e.g., 'en', 'fr')
Returns:
- str: Localized field name (e.g., 'title_en')
"""
def get_translation_fields(*fields):
"""
Get localized field names for given base field names.
Parameters:
- *fields: Base field names
Returns:
- list: All localized field names for all languages
"""
def parse_field(field_name, model):
"""
Parse field name and return field information.
Parameters:
- field_name: Field name to parse
- model: Model class containing the field
Returns:
- tuple: (field_object, field_info)
"""Usage Example:
from modeltranslation.utils import build_localized_fieldname, get_translation_fields
# Build individual localized field names
title_en = build_localized_fieldname('title', 'en') # 'title_en'
title_fr = build_localized_fieldname('title', 'fr') # 'title_fr'
# Get all translation fields for base fields
all_fields = get_translation_fields('title', 'content')
# Returns: ['title_en', 'title_fr', 'title_de', 'content_en', 'content_fr', 'content_de']Utilities for analyzing model structure and field relationships.
def get_field_from_path(model, path):
"""
Get field object from dotted field path.
Parameters:
- model: Starting model class
- path: Dotted field path (e.g., 'category__name')
Returns:
- Field: Django field object at end of path
"""
def build_localized_verbose_name(verbose_name, lang):
"""
Build localized verbose name for field.
Parameters:
- verbose_name: Base verbose name
- lang: Language code
Returns:
- str: Localized verbose name
"""
def build_localized_intermediary_model(field, lang):
"""
Build localized intermediary model for M2M field.
Parameters:
- field: ManyToManyField instance
- lang: Language code
Returns:
- Model: Localized intermediary model class
"""Functions for handling language fallbacks and resolution order.
def resolution_order(lang, fallback_languages):
"""
Get language resolution order including fallbacks.
Parameters:
- lang: Primary language code
- fallback_languages: Fallback language configuration
Returns:
- list: Ordered list of languages to try
"""
def unique(seq):
"""
Remove duplicates from sequence while preserving order.
Parameters:
- seq: Sequence with potential duplicates
Returns:
- list: Sequence with duplicates removed
"""Usage Example:
from modeltranslation.utils import resolution_order
# Get language resolution order with fallbacks
order = resolution_order('fr', {'fr': ('en', 'de'), 'default': ('en',)})
# Returns: ['fr', 'en', 'de']
# For language not in fallback config
order = resolution_order('es', {'fr': ('en', 'de'), 'default': ('en',)})
# Returns: ['es', 'en'] # Uses default fallbackFunctions and context managers for automatic translation field population.
def auto_populate(sender, instance, **kwargs):
"""
Signal handler for auto-populating translation fields.
Parameters:
- sender: Model class sending the signal
- instance: Model instance being saved
- **kwargs: Additional signal arguments
"""
def auto_populate_mode(mode):
"""
Context manager for temporarily changing auto-populate mode.
Parameters:
- mode: Auto-populate mode ('required', 'all', False, or callable)
Yields:
- Context with specified auto-populate mode
"""
def fallbacks_disabled():
"""
Context manager for temporarily disabling fallback languages.
Yields:
- Context with fallbacks disabled
"""Usage Example:
from modeltranslation.utils import auto_populate_mode, fallbacks_disabled
# Temporarily change auto-populate behavior
with auto_populate_mode('all'):
# All translation fields will be auto-populated
article = Article.objects.create(title='Test Title')
# Creates title_en, title_fr, title_de all with 'Test Title'
# Temporarily disable fallbacks
with fallbacks_disabled():
# No fallback values will be used
articles = Article.objects.filter(title__icontains='test')
# Only searches title field for current language, no fallbacksUtilities for building CSS classes and display-related functionality.
def build_css_class(field_name, lang):
"""
Build CSS class name for translation field.
Parameters:
- field_name: Base field name
- lang: Language code
Returns:
- str: CSS class name for styling
"""Usage Example:
from modeltranslation.utils import build_css_class
# Build CSS classes for styling
css_class = build_css_class('title', 'en') # 'modeltranslation-title-en'
css_class = build_css_class('content', 'fr') # 'modeltranslation-content-fr'Thread-local context management for translation settings.
def set_auto_populate(value):
"""
Set auto-populate mode for current thread.
Parameters:
- value: Auto-populate mode (bool, str, or callable)
"""
def set_enable_fallbacks(value):
"""
Set fallback enablement for current thread.
Parameters:
- value: Whether to enable fallbacks (bool)
"""
def auto_populate_mode():
"""
Get current auto-populate mode for thread.
Returns:
- AutoPopulate mode for current context
"""
def fallbacks_enabled():
"""
Check if fallbacks are enabled for current thread.
Returns:
- bool: True if fallbacks are enabled
"""Core language settings that control translation behavior.
AVAILABLE_LANGUAGES: list
"""List of available language codes for translation."""
DEFAULT_LANGUAGE: str
"""Default language code used as fallback."""
REQUIRED_LANGUAGES: tuple
"""Tuple of language codes that are required for translation fields."""
FALLBACK_LANGUAGES: dict
"""
Dictionary mapping language codes to fallback language lists.
Format: {'default': ('en',), 'fr': ('en', 'de')}
"""
ENABLE_FALLBACKS: bool
"""Whether fallback language functionality is enabled globally."""Configuration Example:
# In Django settings.py
MODELTRANSLATION_LANGUAGES = ('en', 'fr', 'de', 'es')
MODELTRANSLATION_DEFAULT_LANGUAGE = 'en'
MODELTRANSLATION_REQUIRED_LANGUAGES = ('en', 'fr')
MODELTRANSLATION_FALLBACK_LANGUAGES = {
'default': ('en',),
'fr': ('en',),
'de': ('en', 'fr'),
'es': ('en', 'fr')
}
MODELTRANSLATION_ENABLE_FALLBACKS = TrueSettings that control field handling and translation behavior.
CUSTOM_FIELDS: tuple
"""Tuple of custom field class names that can be translated."""
AUTO_POPULATE: bool | str | callable
"""
Auto-populate mode for translation fields:
- False: No auto-population
- 'required': Auto-populate required languages only
- 'all': Auto-populate all languages
- callable: Custom auto-populate function
"""
PREPOPULATE_LANGUAGE: str | None
"""Fixed language for prepopulated fields like slugs."""
ENABLE_REGISTRATIONS: bool
"""Whether automatic translation registration discovery is enabled."""
DEBUG: bool
"""Enable debug mode for translation operations."""Advanced Configuration:
# Custom field support
MODELTRANSLATION_CUSTOM_FIELDS = ('MyCustomField', 'SpecialTextField')
# Auto-population behavior
MODELTRANSLATION_AUTO_POPULATE = 'required' # or False, 'all', or callable
# Prepopulated fields always use English
MODELTRANSLATION_PREPOPULATE_LANGUAGE = 'en'
# Debug mode (shows registered models on runserver)
MODELTRANSLATION_DEBUG = TrueSettings for controlling module discovery and loading.
TRANSLATION_FILES: tuple
"""Tuple of module paths to explicitly import for translations."""Module Configuration:
# Explicitly load translation modules
MODELTRANSLATION_TRANSLATION_FILES = (
'myapp.custom_translations',
'anotherapp.special_translations',
)Settings for handling data import/export with translations.
LOADDATA_RETAIN_LOCALE: bool
"""Whether loaddata command retains locale during fixture loading."""
BUILD_LOCALIZED_VERBOSE_NAME: callable
"""Function for building localized verbose names."""Create custom auto-population logic for specific use cases.
def custom_auto_populate(field, model, language):
"""Custom auto-populate function."""
# Get base field value
base_value = getattr(model, field.original_field.name, None)
if base_value and language != 'en':
# Custom logic: append language code to base value
return f"{base_value} ({language.upper()})"
return base_value
# Use in settings
MODELTRANSLATION_AUTO_POPULATE = custom_auto_populateCustom middleware for automatic language detection and setting.
from modeltranslation.utils import get_language
from django.utils import translation
class TranslationMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Custom language detection logic
detected_lang = self.detect_language(request)
# Activate language for modeltranslation
translation.activate(detected_lang)
response = self.get_response(request)
return response
def detect_language(self, request):
# Custom detection logic (headers, user preferences, etc.)
return get_language() # Fallback to default detectionUtilities for optimizing translation field access and caching.
from functools import lru_cache
from modeltranslation.utils import build_localized_fieldname
@lru_cache(maxsize=1000)
def cached_localized_fieldname(field_name, lang):
"""Cached version of build_localized_fieldname for performance."""
return build_localized_fieldname(field_name, lang)
class OptimizedTranslationMixin:
"""Mixin for models with optimized translation field access."""
def get_translated_field(self, field_name, language=None):
"""Get translated field value with caching."""
lang = language or get_language()
localized_name = cached_localized_fieldname(field_name, lang)
return getattr(self, localized_name, None)Install with Tessl CLI
npx tessl i tessl/pypi-django-modeltranslation