Translations¶
This guide covers how to add, update, and manage translations in Django Admin Dashboards.
概述¶
Django Admin Dashboards uses Django\'s internationalization (i18n) framework to support multiple languages. The package includes Chinese (Simplified) translations by default and can be extended to support additional languages.
Current Translations¶
Supported Languages¶
- English (en): Default language, strings are in source code
- Chinese Simplified (zh_Hans): Included in package
(
locale/zh_Hans/LC_MESSAGES/)
Translation Files¶
django_admin_dashboards/locale/
└── zh_Hans/
└── LC_MESSAGES/
├── django.po # Source translation file (human-readable)
└── django.mo # Compiled translation file (machine-readable)
The .po files are included in source control for editing. The .mo
files are compiled binaries that Django uses at runtime.
Adding New Translations¶
Step 1: Create Translation Directory¶
Navigate to the package directory and create a new locale:
This creates:
Step 2: Edit the .po File¶
Open the .po file in a text editor or translation tool. You\'ll see
entries like:
For each entry: 1. Add the translation in the msgstr field 2. Keep the
formatting placeholders (%s, %(variable)s) intact
Example for Spanish:
Step 3: Compile Translations¶
After editing, compile the .po file to create the .mo file:
This creates django.mo in the same directory.
Step 4: Verify Translation¶
Test the translation by setting Django\'s language:
# In Django settings or shell
from django.utils import translation
# Activate Spanish
translation.activate('es')
# Check translated strings
from django.utils.translation import gettext as _
print(_("Dashboard")) # Should print "Panel de Control"
Updating Existing Translations¶
When Source Strings Change¶
When new strings are added or existing strings modified in the source code:
- Extract messages to update all
.pofiles:
This updates all .po files with: - New strings (marked as needing
translation) - Changed strings (marked as \"fuzzy\") - Removed strings
(commented out)
-
Review fuzzy matches: Fuzzy entries need manual review. Remove the
#, fuzzyline and update the translation if needed. -
Translate new strings: Add translations for any new
msgidentries. -
Compile messages:
When Only Translations Need Updates¶
To update translations without extracting from source:
- Edit the
.pofile directly - Update
msgstrfields - Compile messages
Translation Workflow¶
For Contributors¶
- Fork and clone the repository
-
Create translation branch:
3. Add or update translations (see steps above) 4. Test translations using the demo project 5. Commit changes: 6. Submit pull request
For Maintainers¶
- Review translation quality
- Verify format and placeholders
- Test with demo project
- Merge and release
Source Code Translation¶
Marking Strings for Translation¶
In Python code:
from django.utils.translation import gettext as _
from django.utils.translation import gettext_lazy
# Simple string
title = _("Dashboard")
# With variables
message = _("Welcome, %(username)s") % {"username": user.username}
# Lazy translation (for module-level code)
verbose_name = gettext_lazy("User Dashboard")
In templates:
{% load i18n %}
<h1>{% trans "Dashboard" %}</h1>
<p>{% trans "Showing results for" context "search results" %}</p>
{% blocktrans %}
Found {{ count }} results in {{ category }}.
{% endblocktrans %}
{% blocktrans with username=user.get_full_name %}
Welcome, {{ username }}!
{% endblocktrans %}
Best Practices¶
-
Use context where ambiguous: Some words have multiple meanings.
-
Keep strings complete: Don\'t split sentences into multiple translations.
-
Use named placeholders: More readable and order-independent.
-
Avoid HTML in translations: Keep markup outside translated strings when possible.
Testing Translations¶
Demo Project Setup¶
The demo project includes language 配置 for testing:
- Enable languages in
settings.py:
LANGUAGES = [
('en', 'English'),
('zh-hans', '简体中文'),
('es', 'Español'), # Add new languages here
]
LOCALE_PATHS = [
BASE_DIR / 'locale', # Project translations
]
- Add middleware (already included):
- Set language prefix in URLs (optional):
urlpatterns = [
path('i18n/', include('django.conf.urls.i18n')),
path('<str:language>/admin/', admin.site.urls),
]
Manual Testing¶
-
Start 开发 server:
-
Access with language prefix:
-
English:
http://localhost:8000/en/admin/ -
Chinese:
http://localhost:8000/zh-hans/admin/ -
Spanish:
http://localhost:8000/es/admin/ -
Use Django admin language switcher (if enabled)
Automated Testing¶
Test translations in your test suite:
from django.test import TestCase
from django.utils.translation import activate, gettext
class TranslationTests(TestCase):
def test_spanish_translation(self):
activate('es')
self.assertEqual(gettext("Dashboard"), "Panel de Control")
def test_chinese_translation(self):
activate('zh-hans')
self.assertEqual(gettext("Dashboard"), "数据看板")
Translation Tools¶
Recommended Editors¶
- Poedit: Desktop application with translation memory
- Virtaal: Open-source translation tool
- VS Code: With Gettext extension
- Weblate: Web-based collaborative translation platform
Django Commands¶
# Extract messages from source
django-admin makemessages -l es -l fr -l de
# Extract from specific directories
django-admin makemessages -l es --ignore=venv --ignore=.git
# Update all existing .po files
django-admin makemessages -a
# Compile all .po files
django-admin compilemessages
# Create fuzzy translations (experimental)
django-admin makemessages -a --keep-fuzzy
Quality Checks¶
# Check .po file syntax
msgfmt -c locale/es/LC_MESSAGES/django.po
# Check for untranslated strings
grep 'msgstr ""' locale/es/LC_MESSAGES/django.po | wc -l
# Check for fuzzy translations
grep '^#, fuzzy' locale/es/LC_MESSAGES/django.po | wc -l
Package Distribution¶
Including Translations in Package¶
Translations are automatically included via package_data in
pyproject.toml:
[tool.setuptools.package-data]
"django_admin_dashboards" = [
"locale/*/LC_MESSAGES/*.mo", # Compiled translations
# ... other files
]
Verifying Inclusion¶
Check that translations are included in the built package:
Should show paths like:
Common Issues¶
Translations Not Showing¶
Problem: Strings appear in English even when language is set.
Solutions: 1. Verify .mo files are compiled:
ls locale/*/LC_MESSAGES/*.mo 2. Check Django can find translations:
python -c "import django; print(django.__file__)" 3. Ensure
LocaleMiddleware is installed and before CommonMiddleware 4. Check
browser language settings
Missing .mo Files¶
Problem: django.mo files missing after 安装.
Solution: Ensure .mo files are committed to repository and
included in package_data.
Placeholder Errors¶
Problem: Placeholders (%s, %(name)s) not matching.
Solution: Keep placeholders exactly the same in translation:
# Source
msgid "User %(username)s created"
msgstr "Usuario %(username)s creado" # Correct
msgstr "Usuario %(nombre)s creado" # WRONG - placeholder name changed
Pluralization Issues¶
Problem: Different languages have different plural rules.
Solution: Use Django\'s pluralization system:
# Python
from django.utils.translation import ngettext
count = 5
message = ngettext(
"Found %(count)s result",
"Found %(count)s results",
count
) % {"count": count}
In .po file:
msgid "Found %(count)s result"
msgid_plural "Found %(count)s results"
msgstr[0] "Se encontró %(count)s resultado"
msgstr[1] "Se encontraron %(count)s resultados"
Adding a New Language to Demo¶
To test a new language in the demo project:
- Add to
LANGUAGESindemo/settings.py:
LANGUAGES = [
('en', 'English'),
('zh-hans', '简体中文'),
('es', 'Español'), # New language
('fr', 'Français'), # Another new language
]
- Create project-level translations (if needed):
-
Translate demo-specific strings
-
Compile messages:
- Test with language prefix or Django admin language switcher
Translation Maintenance¶
Regular Updates¶
Schedule periodic translation updates:
- Quarterly review of fuzzy translations
- Update after major releases with new features
- Community contributions via GitHub
Quality Assurance¶
- Native speaker review for each language
- Consistency checks across similar strings
- Context validation for ambiguous terms
- Format testing with real data
Community Contributions¶
Encourage community translations by:
- Documenting the process (this guide)
- Providing translation templates
- Recognizing contributors in README
- Making it easy with clear instructions
Resources¶
- Django Internationalization Documentation
- GNU gettext Utilities
- Poedit Translation Editor
- Translation Best Practices
Next Steps¶
- 贡献指南 - General contribution guidelines
- Building Guide - Package building and distribution
- 用户指南 - Using dashboards in your projects