跳转至

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:

    cd django_admin_dashboards
    django-admin makemessages -l es  # For Spanish

This creates:

    locale/es/LC_MESSAGES/django.po

Step 2: Edit the .po File

Open the .po file in a text editor or translation tool. You\'ll see entries like:

    #: base.py:45
    msgid "Dashboard"
    msgstr ""

For each entry: 1. Add the translation in the msgstr field 2. Keep the formatting placeholders (%s, %(variable)s) intact

Example for Spanish:

    #: base.py:45
    msgid "Dashboard"
    msgstr "Panel de Control"

Step 3: Compile Translations

After editing, compile the .po file to create the .mo file:

    django-admin compilemessages

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:

  1. Extract messages to update all .po files:
    cd django_admin_dashboards
    django-admin makemessages -a

This updates all .po files with: - New strings (marked as needing translation) - Changed strings (marked as \"fuzzy\") - Removed strings (commented out)

  1. Review fuzzy matches: Fuzzy entries need manual review. Remove the #, fuzzy line and update the translation if needed.

  2. Translate new strings: Add translations for any new msgid entries.

  3. Compile messages:

    django-admin compilemessages

When Only Translations Need Updates

To update translations without extracting from source:

  1. Edit the .po file directly
  2. Update msgstr fields
  3. Compile messages

Translation Workflow

For Contributors

  1. Fork and clone the repository
  2. Create translation branch:

        git checkout -b translations/spanish
    
    3. Add or update translations (see steps above) 4. Test translations using the demo project 5. Commit changes:

        git add locale/
        git commit -m "feat(translations): add Spanish translations"
    
    6. Submit pull request

For Maintainers

  1. Review translation quality
  2. Verify format and placeholders
  3. Test with demo project
  4. 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

  1. Use context where ambiguous: Some words have multiple meanings.

        # Without context
    
        _("Date")  # Could be calendar date or fruit
    
        # With context
    
        pgettext("calendar", "Date")
        pgettext("fruit", "Date")
    
  2. Keep strings complete: Don\'t split sentences into multiple translations.

        # Bad
    
        _("Found ") + str(count) + _(" results")
    
        # Good
    
        _("Found %(count)s results") % {"count": count}
    
  3. Use named placeholders: More readable and order-independent.

        # Better than positional placeholders
    
        _("User %(username)s created at %(time)s")
    
  4. Avoid HTML in translations: Keep markup outside translated strings when possible.

Testing Translations

Demo Project Setup

The demo project includes language 配置 for testing:

  1. Enable languages in settings.py:
    LANGUAGES = [
        ('en', 'English'),
        ('zh-hans', '简体中文'),
        ('es', 'Español'),  # Add new languages here

    ]

    LOCALE_PATHS = [
        BASE_DIR / 'locale',  # Project translations

    ]
  1. Add middleware (already included):
    MIDDLEWARE = [
        # ...

        'django.middleware.locale.LocaleMiddleware',
        # ...

    ]
  1. Set language prefix in URLs (optional):
    urlpatterns = [
        path('i18n/', include('django.conf.urls.i18n')),
        path('<str:language>/admin/', admin.site.urls),
    ]

Manual Testing

  1. Start 开发 server:

        python manage.py runserver
    
  2. Access with language prefix:

  3. English: http://localhost:8000/en/admin/

  4. Chinese: http://localhost:8000/zh-hans/admin/

  5. Spanish: http://localhost:8000/es/admin/

  6. 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

  1. Poedit: Desktop application with translation memory
  2. Virtaal: Open-source translation tool
  3. VS Code: With Gettext extension
  4. 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:

    # Build package

    python -m build

    # List files in wheel

    unzip -l dist/*.whl | grep locale

Should show paths like:

    django_admin_dashboards/locale/zh_Hans/LC_MESSAGES/django.mo

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:

  1. Add to LANGUAGES in demo/settings.py:
    LANGUAGES = [
        ('en', 'English'),
        ('zh-hans', '简体中文'),
        ('es', 'Español'),  # New language

        ('fr', 'Français'),  # Another new language

    ]
  1. Create project-level translations (if needed):
    cd django_admin_dashboards_demo
    django-admin makemessages -l es
  1. Translate demo-specific strings

  2. Compile messages:

    django-admin compilemessages
  1. Test with language prefix or Django admin language switcher

Translation Maintenance

Regular Updates

Schedule periodic translation updates:

  1. Quarterly review of fuzzy translations
  2. Update after major releases with new features
  3. Community contributions via GitHub

Quality Assurance

  1. Native speaker review for each language
  2. Consistency checks across similar strings
  3. Context validation for ambiguous terms
  4. Format testing with real data

Community Contributions

Encourage community translations by:

  1. Documenting the process (this guide)
  2. Providing translation templates
  3. Recognizing contributors in README
  4. Making it easy with clear instructions

Resources

Next Steps