0
# Utils and Configuration
1
2
Utility functions for language handling, field name building, configuration management, and context-aware translation functionality.
3
4
## Capabilities
5
6
### Language Management
7
8
Core utilities for managing language codes, validation, and retrieval.
9
10
```python { .api }
11
def get_language():
12
"""
13
Get active language code guaranteed to be in AVAILABLE_LANGUAGES.
14
15
Returns:
16
- str: Active language code, falls back to DEFAULT_LANGUAGE
17
"""
18
19
def get_language_bidi(lang):
20
"""
21
Check if a language uses bidirectional text layout.
22
23
Parameters:
24
- lang: Language code (e.g., 'ar', 'he', 'en')
25
26
Returns:
27
- bool: True if language is bidirectional (RTL)
28
"""
29
```
30
31
**Usage Example:**
32
33
```python
34
from modeltranslation.utils import get_language, get_language_bidi
35
36
# Get current active language
37
current_lang = get_language() # Returns 'en', 'fr', etc.
38
39
# Check text direction for UI layout
40
is_rtl = get_language_bidi('ar') # True for Arabic
41
is_rtl = get_language_bidi('en') # False for English
42
```
43
44
### Field Name Utilities
45
46
Functions for building and parsing localized field names.
47
48
```python { .api }
49
def build_localized_fieldname(field_name, lang):
50
"""
51
Build localized field name by appending language code.
52
53
Parameters:
54
- field_name: Base field name (e.g., 'title')
55
- lang: Language code (e.g., 'en', 'fr')
56
57
Returns:
58
- str: Localized field name (e.g., 'title_en')
59
"""
60
61
def get_translation_fields(*fields):
62
"""
63
Get localized field names for given base field names.
64
65
Parameters:
66
- *fields: Base field names
67
68
Returns:
69
- list: All localized field names for all languages
70
"""
71
72
def parse_field(field_name, model):
73
"""
74
Parse field name and return field information.
75
76
Parameters:
77
- field_name: Field name to parse
78
- model: Model class containing the field
79
80
Returns:
81
- tuple: (field_object, field_info)
82
"""
83
```
84
85
**Usage Example:**
86
87
```python
88
from modeltranslation.utils import build_localized_fieldname, get_translation_fields
89
90
# Build individual localized field names
91
title_en = build_localized_fieldname('title', 'en') # 'title_en'
92
title_fr = build_localized_fieldname('title', 'fr') # 'title_fr'
93
94
# Get all translation fields for base fields
95
all_fields = get_translation_fields('title', 'content')
96
# Returns: ['title_en', 'title_fr', 'title_de', 'content_en', 'content_fr', 'content_de']
97
```
98
99
### Model and Field Introspection
100
101
Utilities for analyzing model structure and field relationships.
102
103
```python { .api }
104
def get_field_from_path(model, path):
105
"""
106
Get field object from dotted field path.
107
108
Parameters:
109
- model: Starting model class
110
- path: Dotted field path (e.g., 'category__name')
111
112
Returns:
113
- Field: Django field object at end of path
114
"""
115
116
def build_localized_verbose_name(verbose_name, lang):
117
"""
118
Build localized verbose name for field.
119
120
Parameters:
121
- verbose_name: Base verbose name
122
- lang: Language code
123
124
Returns:
125
- str: Localized verbose name
126
"""
127
128
def build_localized_intermediary_model(field, lang):
129
"""
130
Build localized intermediary model for M2M field.
131
132
Parameters:
133
- field: ManyToManyField instance
134
- lang: Language code
135
136
Returns:
137
- Model: Localized intermediary model class
138
"""
139
```
140
141
### Language Resolution
142
143
Functions for handling language fallbacks and resolution order.
144
145
```python { .api }
146
def resolution_order(lang, fallback_languages):
147
"""
148
Get language resolution order including fallbacks.
149
150
Parameters:
151
- lang: Primary language code
152
- fallback_languages: Fallback language configuration
153
154
Returns:
155
- list: Ordered list of languages to try
156
"""
157
158
def unique(seq):
159
"""
160
Remove duplicates from sequence while preserving order.
161
162
Parameters:
163
- seq: Sequence with potential duplicates
164
165
Returns:
166
- list: Sequence with duplicates removed
167
"""
168
```
169
170
**Usage Example:**
171
172
```python
173
from modeltranslation.utils import resolution_order
174
175
# Get language resolution order with fallbacks
176
order = resolution_order('fr', {'fr': ('en', 'de'), 'default': ('en',)})
177
# Returns: ['fr', 'en', 'de']
178
179
# For language not in fallback config
180
order = resolution_order('es', {'fr': ('en', 'de'), 'default': ('en',)})
181
# Returns: ['es', 'en'] # Uses default fallback
182
```
183
184
### Auto-Population
185
186
Functions and context managers for automatic translation field population.
187
188
```python { .api }
189
def auto_populate(sender, instance, **kwargs):
190
"""
191
Signal handler for auto-populating translation fields.
192
193
Parameters:
194
- sender: Model class sending the signal
195
- instance: Model instance being saved
196
- **kwargs: Additional signal arguments
197
"""
198
199
def auto_populate_mode(mode):
200
"""
201
Context manager for temporarily changing auto-populate mode.
202
203
Parameters:
204
- mode: Auto-populate mode ('required', 'all', False, or callable)
205
206
Yields:
207
- Context with specified auto-populate mode
208
"""
209
210
def fallbacks_disabled():
211
"""
212
Context manager for temporarily disabling fallback languages.
213
214
Yields:
215
- Context with fallbacks disabled
216
"""
217
```
218
219
**Usage Example:**
220
221
```python
222
from modeltranslation.utils import auto_populate_mode, fallbacks_disabled
223
224
# Temporarily change auto-populate behavior
225
with auto_populate_mode('all'):
226
# All translation fields will be auto-populated
227
article = Article.objects.create(title='Test Title')
228
# Creates title_en, title_fr, title_de all with 'Test Title'
229
230
# Temporarily disable fallbacks
231
with fallbacks_disabled():
232
# No fallback values will be used
233
articles = Article.objects.filter(title__icontains='test')
234
# Only searches title field for current language, no fallbacks
235
```
236
237
### CSS and Display Utilities
238
239
Utilities for building CSS classes and display-related functionality.
240
241
```python { .api }
242
def build_css_class(field_name, lang):
243
"""
244
Build CSS class name for translation field.
245
246
Parameters:
247
- field_name: Base field name
248
- lang: Language code
249
250
Returns:
251
- str: CSS class name for styling
252
"""
253
```
254
255
**Usage Example:**
256
257
```python
258
from modeltranslation.utils import build_css_class
259
260
# Build CSS classes for styling
261
css_class = build_css_class('title', 'en') # 'modeltranslation-title-en'
262
css_class = build_css_class('content', 'fr') # 'modeltranslation-content-fr'
263
```
264
265
### Thread Context Management
266
267
Thread-local context management for translation settings.
268
269
```python { .api }
270
def set_auto_populate(value):
271
"""
272
Set auto-populate mode for current thread.
273
274
Parameters:
275
- value: Auto-populate mode (bool, str, or callable)
276
"""
277
278
def set_enable_fallbacks(value):
279
"""
280
Set fallback enablement for current thread.
281
282
Parameters:
283
- value: Whether to enable fallbacks (bool)
284
"""
285
286
def auto_populate_mode():
287
"""
288
Get current auto-populate mode for thread.
289
290
Returns:
291
- AutoPopulate mode for current context
292
"""
293
294
def fallbacks_enabled():
295
"""
296
Check if fallbacks are enabled for current thread.
297
298
Returns:
299
- bool: True if fallbacks are enabled
300
"""
301
```
302
303
## Configuration Settings
304
305
### Language Configuration
306
307
Core language settings that control translation behavior.
308
309
```python { .api }
310
AVAILABLE_LANGUAGES: list
311
"""List of available language codes for translation."""
312
313
DEFAULT_LANGUAGE: str
314
"""Default language code used as fallback."""
315
316
REQUIRED_LANGUAGES: tuple
317
"""Tuple of language codes that are required for translation fields."""
318
319
FALLBACK_LANGUAGES: dict
320
"""
321
Dictionary mapping language codes to fallback language lists.
322
Format: {'default': ('en',), 'fr': ('en', 'de')}
323
"""
324
325
ENABLE_FALLBACKS: bool
326
"""Whether fallback language functionality is enabled globally."""
327
```
328
329
**Configuration Example:**
330
331
```python
332
# In Django settings.py
333
MODELTRANSLATION_LANGUAGES = ('en', 'fr', 'de', 'es')
334
MODELTRANSLATION_DEFAULT_LANGUAGE = 'en'
335
MODELTRANSLATION_REQUIRED_LANGUAGES = ('en', 'fr')
336
MODELTRANSLATION_FALLBACK_LANGUAGES = {
337
'default': ('en',),
338
'fr': ('en',),
339
'de': ('en', 'fr'),
340
'es': ('en', 'fr')
341
}
342
MODELTRANSLATION_ENABLE_FALLBACKS = True
343
```
344
345
### Field and Behavior Configuration
346
347
Settings that control field handling and translation behavior.
348
349
```python { .api }
350
CUSTOM_FIELDS: tuple
351
"""Tuple of custom field class names that can be translated."""
352
353
AUTO_POPULATE: bool | str | callable
354
"""
355
Auto-populate mode for translation fields:
356
- False: No auto-population
357
- 'required': Auto-populate required languages only
358
- 'all': Auto-populate all languages
359
- callable: Custom auto-populate function
360
"""
361
362
PREPOPULATE_LANGUAGE: str | None
363
"""Fixed language for prepopulated fields like slugs."""
364
365
ENABLE_REGISTRATIONS: bool
366
"""Whether automatic translation registration discovery is enabled."""
367
368
DEBUG: bool
369
"""Enable debug mode for translation operations."""
370
```
371
372
**Advanced Configuration:**
373
374
```python
375
# Custom field support
376
MODELTRANSLATION_CUSTOM_FIELDS = ('MyCustomField', 'SpecialTextField')
377
378
# Auto-population behavior
379
MODELTRANSLATION_AUTO_POPULATE = 'required' # or False, 'all', or callable
380
381
# Prepopulated fields always use English
382
MODELTRANSLATION_PREPOPULATE_LANGUAGE = 'en'
383
384
# Debug mode (shows registered models on runserver)
385
MODELTRANSLATION_DEBUG = True
386
```
387
388
### File and Module Configuration
389
390
Settings for controlling module discovery and loading.
391
392
```python { .api }
393
TRANSLATION_FILES: tuple
394
"""Tuple of module paths to explicitly import for translations."""
395
```
396
397
**Module Configuration:**
398
399
```python
400
# Explicitly load translation modules
401
MODELTRANSLATION_TRANSLATION_FILES = (
402
'myapp.custom_translations',
403
'anotherapp.special_translations',
404
)
405
```
406
407
### Data Loading Configuration
408
409
Settings for handling data import/export with translations.
410
411
```python { .api }
412
LOADDATA_RETAIN_LOCALE: bool
413
"""Whether loaddata command retains locale during fixture loading."""
414
415
BUILD_LOCALIZED_VERBOSE_NAME: callable
416
"""Function for building localized verbose names."""
417
```
418
419
## Advanced Usage
420
421
### Custom Auto-Population
422
423
Create custom auto-population logic for specific use cases.
424
425
```python
426
def custom_auto_populate(field, model, language):
427
"""Custom auto-populate function."""
428
# Get base field value
429
base_value = getattr(model, field.original_field.name, None)
430
431
if base_value and language != 'en':
432
# Custom logic: append language code to base value
433
return f"{base_value} ({language.upper()})"
434
435
return base_value
436
437
# Use in settings
438
MODELTRANSLATION_AUTO_POPULATE = custom_auto_populate
439
```
440
441
### Language Detection Middleware
442
443
Custom middleware for automatic language detection and setting.
444
445
```python
446
from modeltranslation.utils import get_language
447
from django.utils import translation
448
449
class TranslationMiddleware:
450
def __init__(self, get_response):
451
self.get_response = get_response
452
453
def __call__(self, request):
454
# Custom language detection logic
455
detected_lang = self.detect_language(request)
456
457
# Activate language for modeltranslation
458
translation.activate(detected_lang)
459
460
response = self.get_response(request)
461
return response
462
463
def detect_language(self, request):
464
# Custom detection logic (headers, user preferences, etc.)
465
return get_language() # Fallback to default detection
466
```
467
468
### Performance Optimization
469
470
Utilities for optimizing translation field access and caching.
471
472
```python
473
from functools import lru_cache
474
from modeltranslation.utils import build_localized_fieldname
475
476
@lru_cache(maxsize=1000)
477
def cached_localized_fieldname(field_name, lang):
478
"""Cached version of build_localized_fieldname for performance."""
479
return build_localized_fieldname(field_name, lang)
480
481
class OptimizedTranslationMixin:
482
"""Mixin for models with optimized translation field access."""
483
484
def get_translated_field(self, field_name, language=None):
485
"""Get translated field value with caching."""
486
lang = language or get_language()
487
localized_name = cached_localized_fieldname(field_name, lang)
488
return getattr(self, localized_name, None)
489
```