[ django翻译功能 ]


django中使用多语言翻译

.
├── django_test
│   ├── asgi.py
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
├── locale
│   └── zh_Hans
│       └── LC_MESSAGES
│           ├── django.mo
│           └── django.po
└── manage.py

修改4个地方

USE_I18N
LANGUAGES
LOCALE_PATHS
MIDDLEWARE

settings.py

"""
Django settings for django_test project.

Generated by 'django-admin startproject' using Django 5.1.4.

For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/ref/settings/
"""

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-%($wz9wpq747o#0^84i8qp#xd3nj_)jpoowky5qu)&=hz)u$$*'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'django_test.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'django_test.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


USE_I18N = True

LANGUAGES = [
    ('en', 'English'),
    ('zh-hans', '简体中文'),
]

LOCALE_PATHS = [
    os.path.join(BASE_DIR, 'locale'),
]

views.py

from django.http import JsonResponse
from django.utils.translation import gettext as _
from django.utils.translation import activate, override
from django.utils.translation import get_language
from django.views import View

class TestView(View):
    def get(self, request):
        return test3()

def test1():
    current_language = get_language()
    print(f"当前语言: {current_language}")

    en_text = _("Hello, world!")
    print(f"英文翻译: {en_text}")

    print("-----切换到中文-----")
    activate('zh-hans')  # 注意这里用小写
    current_language = get_language()
    print(f"当前语言: {current_language}")

    zh_text = _("Hello, world!")
    print(f"中文翻译: {zh_text}")

    return JsonResponse({
        'code': 200,
        'message': 'success',
        'zh': zh_text,
        'en': en_text
    })

def test2():
    with override('zh-hans'):
        zh_text = _("Hello, world!")
    en_text = _("Hello, world!")
    return JsonResponse({
        'code': 200,
        'message': 'success',
        'zh': zh_text,
        'en': en_text
    })

def test3():
    with override('zh-hans'):
        zh_text = _("submit")
    return JsonResponse({
        'code': 200,
        'message': 'success',
        'zh': zh_text
    })

django.po

# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2025-02-12 03:15+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"
#: django_test/views.py:16
msgid "Hello, world!"
msgstr "你好,世界!"

#: django_test/views.py:17
msgid "text"
msgstr "文字"

#: django_test/views.py:46
msgid "submit"
msgstr "提交"
1. 创建文件夹
mkdir locale

2. 生成中文语言翻译模板 (会根据你代码需要翻译的内容, 自动生成的文件django.po)
python manage.py makemessages -l zh_Hans

3. 修改django.po英文对应的中文内容

4. 编译(生成的django.mo文件)
python manage.py compilemessages