Python API¶
TranslateBot exposes a public Python API so you can trigger translations from anywhere in your code - Celery tasks, custom management commands, scripts, Django views, or any other Python context.
translate()¶
The translate() function provides the same functionality as the translate management command with a clean keyword-argument interface.
Parameters¶
| Parameter | Type | Default | Description |
|---|---|---|---|
target_langs |
str or list[str] |
None |
Language code(s) to translate to (e.g. "nl" or ["nl", "de"]). When omitted, translates to all languages in settings.LANGUAGES. |
dry_run |
bool |
False |
Preview what would be translated without saving changes. |
overwrite |
bool |
False |
Re-translate entries that already have translations. |
apps |
str or list[str] |
None |
Restrict PO file translation to specific app(s). Cannot be combined with models. |
models |
bool or list[str] |
None |
None: translate PO files only. True: translate all registered model fields. List of names: translate specific models. |
Exceptions¶
Raises django.core.management.base.CommandError on configuration or translation errors (missing API key, unknown language, API failures, etc.).
Examples¶
Basic usage¶
from translatebot_django import translate
# Translate PO files to all configured languages
translate()
# Translate to specific languages
translate(target_langs=["nl", "de", "fr"])
# Translate a single language
translate(target_langs="nl")
Model translation¶
# Translate all registered django-modeltranslation fields
translate(models=True)
# Translate specific models only
translate(target_langs="fr", models=["Article", "Product"])
Preview and overwrite¶
# Preview what would be translated
translate(dry_run=True)
# Re-translate everything (overwrite existing translations)
translate(target_langs="de", overwrite=True)
App-specific translation¶
# Translate PO files for a specific app
translate(target_langs="nl", apps="blog")
# Translate multiple apps
translate(target_langs="nl", apps=["blog", "shop"])
Celery task¶
from celery import shared_task
from translatebot_django import translate
@shared_task
def translate_nightly():
"""Run translations as a background task."""
translate()
Schedule it with Celery Beat:
# settings.py
CELERY_BEAT_SCHEDULE = {
"nightly-translations": {
"task": "myapp.tasks.translate_nightly",
"schedule": crontab(hour=2, minute=0), # Run at 2 AM
},
}
Django Q / Huey / APScheduler¶
The function works with any task runner:
Cron job¶
If you prefer cron over a task queue, the management command is the simplest option: