
Django i18n:國際化與翻譯指南
從 settings.py 到生產:設定 Django 翻譯系統、編寫 PO 檔案、處理複數,並利用 AI 自動翻譯。
安裝並提取字串
Django 內建 i18n 框架,只需啟用即可。安裝 django-locale-chain 以實現智能語言回退,再使用 makemessages 將 Python 程式碼和範本中的可翻譯字串提取到 PO 檔案。
pip install django-locale-chain# Extract all translatable strings from Python and template files
python manage.py makemessages -l de -l ja -l es -l fr
# After translating .po files, compile to .mo (binary)
python manage.py compilemessages
# Project structure after running makemessages:
# locale/
# ├── de/
# │ └── LC_MESSAGES/
# │ ├── django.po <-- translate this
# │ └── django.mo <-- compiled (auto-generated)
# ├── ja/
# │ └── LC_MESSAGES/
# │ ├── django.po
# │ └── django.mo
# └── es/
# └── LC_MESSAGES/
# ├── django.po
# └── django.mo設定和中介軟體
在 settings.py 中設定 USE_I18N = True、定義受支援的 LANGUAGES 列表,並將 LocaleMiddleware 新增到 MIDDLEWARE 棧,以啟用國際化。LocaleMiddleware 會從 URL 前綴、會話、Cookie 或 Accept-Language 標頭偵測使用者語言。
# settings.py
from django.utils.translation import gettext_lazy as _
# Default language
LANGUAGE_CODE = 'en'
# Enable i18n
USE_I18N = True
USE_L10N = True
# Languages your site supports
LANGUAGES = [
('en', _('English')),
('de', _('German')),
('ja', _('Japanese')),
('es', _('Spanish')),
('fr', _('French')),
('pt-br', _('Brazilian Portuguese')),
]
# Where Django looks for .po files
LOCALE_PATHS = [
BASE_DIR / 'locale',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware', # <-- enables i18n
'locale_chain.middleware.LocaleChainMiddleware', # <-- smart fallbacks
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]URL 國際化
使用 i18n_patterns() 自動為 URL 新增當前語言程式碼前綴。這樣每種語言都擁有獨立 URL 命名空間(/en/about/、/de/about/),更有利於 SEO,也方便使用者分享特定語言連結。
# urls.py
from django.conf.urls.i18n import i18n_patterns
from django.urls import path, include
urlpatterns = [
# Non-localized URLs (API, admin, etc.)
path('api/', include('api.urls')),
]
urlpatterns += i18n_patterns(
# These get prefixed with the language code: /en/about/, /de/about/
path('', include('myapp.urls')),
path('admin/', admin.site.urls),
prefix_default_language=False, # Skip prefix for default language
)標記待翻譯字串
Django 提供兩個主要翻譯函式:請求時求值的 gettext()(別名 _()),以及匯入時求值的 gettext_lazy()。範本中使用 {% trans %} 和 {% blocktrans %} 標籤。
在檢視中(Python 程式碼)
from django.utils.translation import gettext as _
from django.utils.translation import ngettext
from django.http import HttpResponse
def greeting_view(request):
# Simple translation
welcome = _("Welcome to our site")
# Translation with variables (Python string formatting)
user_greeting = _("Hello, %(name)s!") % {"name": request.user.username}
# Plurals
count = request.user.order_set.count()
order_text = ngettext(
"You have %(count)d order.",
"You have %(count)d orders.",
count,
) % {"count": count}
return HttpResponse(f"{welcome}<br>{user_greeting}<br>{order_text}")在範本中
{# Load the i18n template tags #}
{% load i18n %}
{# Simple translation #}
<h1>{% trans "Welcome to our site" %}</h1>
{# Translation with variables #}
{% blocktrans with name=user.username %}
Hello, {{ name }}!
{% endblocktrans %}
{# Plurals in templates #}
{% blocktrans count count=order_count %}
You have {{ count }} order.
{% plural %}
You have {{ count }} orders.
{% endblocktrans %}
{# Mark strings as translatable but don't output them (for attributes, etc.) #}
{% trans "Submit" as submit_label %}
<button type="submit">{{ submit_label }}</button>在模型和表單中
from django.db import models
from django.utils.translation import gettext_lazy as _
class Product(models.Model):
name = models.CharField(_("product name"), max_length=200)
description = models.TextField(_("description"), blank=True)
class Meta:
verbose_name = _("product")
verbose_name_plural = _("products")
def __str__(self):
return self.name
# IMPORTANT: Use gettext_lazy (_) for anything evaluated at import time:
# - Model field labels, verbose_name, help_text
# - Form field labels
# - Class-level attributes
# Use gettext for anything evaluated at request time:
# - View functions, template tagsPO 檔案格式
執行 makemessages 後,Django 會為每種語言產生 .po(Portable Object)檔案,其中包含 msgid/msgstr 對。翻譯 msgstr 值,再執行 compilemessages,產生 Django 在執行階段讀取的二進位 .mo 檔案。
# locale/de/LC_MESSAGES/django.po
msgid "Welcome to our site"
msgstr "Willkommen auf unserer Seite"
msgid "Hello, %(name)s!"
msgstr "Hallo, %(name)s!"
#, python-format
msgid "You have %(count)d order."
msgid_plural "You have %(count)d orders."
msgstr[0] "Sie haben %(count)d Bestellung."
msgstr[1] "Sie haben %(count)d Bestellungen."
msgid "product name"
msgstr "Produktname"
msgid "description"
msgstr "Beschreibung"
msgid "product"
msgstr "Produkt"
msgid "products"
msgstr "Produkte"
msgid "Submit"
msgstr "Absenden"處理複數和變數
Django 使用 ngettext() 處理複數,並遵守 GNU gettext 複數規則。每種語言都定義複數形式數量和選擇正確形式的公式,PO 檔案透過 Plural-Forms 標頭聲明這些規則。
# English: 2 forms (singular, plural)
msgid "%(count)d item"
msgid_plural "%(count)d items"
msgstr[0] "%(count)d item"
msgstr[1] "%(count)d items"
# German: 2 forms (singular, plural)
msgstr[0] "%(count)d Artikel"
msgstr[1] "%(count)d Artikel"
# Russian: 3 forms (one, few, many)
msgstr[0] "%(count)d товар" # 1 item
msgstr[1] "%(count)d товара" # 2-4 items
msgstr[2] "%(count)d товаров" # 5+ items
# Arabic: 6 forms (zero, one, two, few, many, other)
msgstr[0] "لا عناصر" # 0
msgstr[1] "عنصر واحد" # 1
msgstr[2] "عنصران" # 2
msgstr[3] "%(count)d عناصر" # 3-10
msgstr[4] "%(count)d عنصرًا" # 11-99
msgstr[5] "%(count)d عنصر" # 100+
# Japanese: 1 form (no plural distinction)
msgstr[0] "%(count)d個のアイテム"
# In Python code, always use ngettext:
from django.utils.translation import ngettext
msg = ngettext(
"%(count)d item",
"%(count)d items",
count,
) % {"count": count}自動保證翻譯品質
常見問題
混淆 gettext() 與 gettext_lazy()
忘記執行 compilemessages
未設定 LOCALE_PATHS
URL 中缺少 i18n_patterns
使用 django-locale-chain 實現智能語言回退
區域變體缺失時,Django 翻譯系統會直接回退到 LANGUAGE_CODE。即使已有 pt-PT 譯文,pt-BR 使用者仍會看到英語。django-locale-chain 透過安裝 gettext 回退鏈修復此問題:pt-BR 會先嘗試 pt-PT,再嘗試 pt,最後才使用預設語言。
# settings.py -- Smart fallback with django-locale-chain
# pip install django-locale-chain
MIDDLEWARE = [
# ...
'django.middleware.locale.LocaleMiddleware',
'locale_chain.middleware.LocaleChainMiddleware', # after LocaleMiddleware
# ...
]
# That's it! 75 built-in fallback chains are now active:
# pt-BR user → tries pt-PT → tries pt → falls back to LANGUAGE_CODE
# es-MX user → tries es-419 → tries es → falls back to LANGUAGE_CODE
# fr-CA user → tries fr → falls back to LANGUAGE_CODE
# Optional: customize specific chains
LOCALE_FALLBACK_CHAINS = {
"pt-BR": ["pt-PT", "pt"],
"es-MX": ["es-419", "es"],
"fr-CA": ["fr"],
}
# Or configure programmatically in AppConfig.ready():
from locale_chain import configure
class MyAppConfig(AppConfig):
name = "myapp"
def ready(self):
configure(overrides={"zh-Hant-HK": ["zh-Hant-TW", "zh-Hant"]})推薦的專案結構
myproject/
├── myproject/
│ ├── settings.py # i18n config, MIDDLEWARE, LANGUAGES
│ ├── urls.py # i18n_patterns for URL prefixing
│ └── wsgi.py
├── myapp/
│ ├── models.py # gettext_lazy for field labels
│ ├── views.py # gettext for request-time strings
│ └── templates/
│ └── myapp/
│ └── index.html # {% load i18n %}, {% trans %}, {% blocktrans %}
├── locale/ # Created by makemessages
│ ├── de/
│ │ └── LC_MESSAGES/
│ │ ├── django.po # German translations
│ │ └── django.mo # Compiled binary
│ ├── ja/
│ │ └── LC_MESSAGES/
│ │ ├── django.po
│ │ └── django.mo
│ └── es/
│ └── LC_MESSAGES/
│ ├── django.po
│ └── django.mo
├── manage.py
└── requirements.txt立即試用 i18n Agent
將翻譯檔案拖放到此處
JSON, YAML, PO, XML, CSV, Markdown, Properties
或點擊選擇檔案
目標語言
使用 django-locale-chain 實現語言回退
如果 pt-BR 等區域語言缺少翻譯鍵,Django 會直接跳到範本語言,而不會先檢查父語言 pt。
pip install django-locale-chain# settings.py
LOCALE_CHAINS = {
'pt-BR': ['pt', 'es', 'en'],
'zh-Hant-HK': ['zh-Hant', 'zh', 'en'],
}
MIDDLEWARE = [
...
'django_locale_chain.middleware.LocaleChainMiddleware',
...
]查看語言回退指南,瞭解受支援框架的完整列表和 75 條內建回退鏈。 Learn more →