官厌 发表于 昨天 15:54

Django国际化

Django 提供了强大的国际化 (i18n) 和本地化 (l10n) 支持,让开发者能够轻松创建多语言网站。
1、核心概念与配置

1.1 基本配置

在 settings.py中启用国际化支持:
# settings.py

# 启用国际化
USE_I18N = True
USE_L10N = True# 本地化格式(数字、日期等)
USE_TZ = True    # 时区支持

# 支持的语言
LANGUAGES = [
    ('en', 'English'),
    ('zh-hans', '简体中文'),
]

# 默认语言
LANGUAGE_CODE = 'en'

# 翻译文件位置
LOCALE_PATHS = [
    os.path.join(BASE_DIR, 'locale'),
]

# 中间件配置(确保顺序正确)
MIDDLEWARE = [
    # ...
    'django.middleware.locale.LocaleMiddleware',# 在SessionMiddleware之后,CommonMiddleware之前
    # ...
]1.2 项目结构建议

my_project/
├── locale/         # 翻译文件目录
│   ├── en/
│   │   └── LC_MESSAGES/
│   │       ├── django.po
│   │       └── django.mo
│   ├── zh_Hans/
│   └── ja/
├── templates/
│   ├── base.html
│   └── includes/
│       └── language_switcher.html
├── my_app/
│   ├── locale/      # 应用特定翻译(可选)
│   └── views.py
└── manage.py2、模板中的国际化

{% load i18n %}

<!DOCTYPE html>
<html lang="{{ request.LANGUAGE_CODE }}">
<head>
    <title>{% trans "Welcome to our site" %}</title>
</head>
<body>
    <h1>{% trans "Hello, World!" %}</h1>
   
    {# 带变量的翻译 #}
    <p>{% blocktrans with name=user.name %}Hello, {{ name }}!{% endblocktrans %}</p>
   
    {# 复数形式 #}
    <p>
      {% blocktrans count counter=item_count %}
            You have {{ counter }} item.
      {% plural %}
            You have {{ counter }} items.
      {% endblocktrans %}
    </p>
</body>
</html>3、Python 代码中的国际化

3.1 视图和模型中的翻译

# views.py
from django.utils.translation import gettext as _
from django.utils.translation import gettext_lazy, ngettext
from django.http import JsonResponse
from django.shortcuts import render

def welcome_view(request):
    # 简单翻译
    message = _("Welcome to our application")
   
    # 带变量的翻译
    username = request.user.username
    greeting = _("Hello, %(username)s") % {'username': username}
   
    # 复数形式
    item_count = 5
    items_message = ngettext(
      "You have %(count)d item",
      "You have %(count)d items",
      item_count
    ) % {'count': item_count}
   
    return render(request, 'welcome.html', {
      'message': message,
      'greeting': greeting,
      'items_message': items_message
    })

# API响应国际化
def api_view(request):
    return JsonResponse({
      'message': _("Operation completed successfully"),
      'error': _("Invalid input provided")
    })

# models.py
from django.db import models
from django.utils.translation import gettext_lazy as _

class Product(models.Model):
    name = models.CharField(_("Product name"), max_length=100)
    description = models.TextField(_("Product description"))
   
    class Meta:
      verbose_name = _("Product")
      verbose_name_plural = _("Products")
   
    def __str__(self):
      return _("Product: %(name)s") % {'name': self.name}3.2 表单和验证错误

# forms.py
from django import forms
from django.utils.translation import gettext_lazy as _
from django.core.validators import ValidationError

class ContactForm(forms.Form):
    name = forms.CharField(label=_("Your name"))
    email = forms.EmailField(label=_("Email address"))
    message = forms.CharField(
      label=_("Message"),
      widget=forms.Textarea,
      error_messages={
            'required': _("Please enter your message")
      }
    )
   
    def clean_email(self):
      email = self.cleaned_data.get('email')
      if not email.endswith('.com'):
            raise ValidationError(_("Email must be from a .com domain"))
      return email
   
    # 表单级别的错误消息
    def clean(self):
      cleaned_data = super().clean()
      # 自定义验证逻辑
      if cleaned_data.get('name') == cleaned_data.get('email'):
            raise ValidationError(_("Name and email cannot be the same"))4、翻译文件

4.1 .po 文件

# locale/zh_Hans/LC_MESSAGES/django.po

# 清晰的注释说明上下文
#. This message appears on the homepage banner
msgid "Welcome to our site"
msgstr "欢迎访问我们的网站"

# 带变量的翻译
msgid "Hello, %(username)s"
msgstr "你好,%(username)s"

# 复数形式
msgid "You have %(count)d item"
msgid_plural "You have %(count)d items"
msgstr "您有 %(count)d 个项目"
msgstr "您有 %(count)d 个项目"

# 包含开发者注释
# Translators: This message appears in the email subject
msgid "Password reset request"
msgstr "密码重置请求"4.2 提取和编译翻译

# windows需要先安装gettext
django-admin makemessages -l zh_Hans# 简体中文
django-admin makemessages -l en

# 编译翻译文件
django-admin compilemessages

# 查看所有支持的语言
python manage.py show_languag
来源:豆瓜网用户自行投稿发布,如果侵权,请联系站长删除
页: [1]
查看完整版本: Django国际化