找回密码
 立即注册
首页 业界区 业界 Django国际化

Django国际化

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

1.1 基本配置

在 settings.py中启用国际化支持:
  1. # settings.py
  2. # 启用国际化
  3. USE_I18N = True
  4. USE_L10N = True  # 本地化格式(数字、日期等)
  5. USE_TZ = True    # 时区支持
  6. # 支持的语言
  7. LANGUAGES = [
  8.     ('en', 'English'),
  9.     ('zh-hans', '简体中文'),
  10. ]
  11. # 默认语言
  12. LANGUAGE_CODE = 'en'
  13. # 翻译文件位置
  14. LOCALE_PATHS = [
  15.     os.path.join(BASE_DIR, 'locale'),
  16. ]
  17. # 中间件配置(确保顺序正确)
  18. MIDDLEWARE = [
  19.     # ...
  20.     'django.middleware.locale.LocaleMiddleware',  # 在SessionMiddleware之后,CommonMiddleware之前
  21.     # ...
  22. ]
复制代码
1.2 项目结构建议
  1. my_project/
  2. ├── locale/           # 翻译文件目录
  3. │   ├── en/
  4. │   │   └── LC_MESSAGES/
  5. │   │       ├── django.po
  6. │   │       └── django.mo
  7. │   ├── zh_Hans/
  8. │   └── ja/
  9. ├── templates/
  10. │   ├── base.html
  11. │   └── includes/
  12. │       └── language_switcher.html
  13. ├── my_app/
  14. │   ├── locale/      # 应用特定翻译(可选)
  15. │   └── views.py
  16. └── manage.py
复制代码
2、模板中的国际化
  1. {% load i18n %}
  2. <!DOCTYPE html>
  3. <html lang="{{ request.LANGUAGE_CODE }}">
  4. <head>
  5.     <title>{% trans "Welcome to our site" %}</title>
  6. </head>
  7. <body>
  8.     <h1>{% trans "Hello, World!" %}</h1>
  9.    
  10.     {# 带变量的翻译 #}
  11.     <p>{% blocktrans with name=user.name %}Hello, {{ name }}!{% endblocktrans %}</p>
  12.    
  13.     {# 复数形式 #}
  14.     <p>
  15.         {% blocktrans count counter=item_count %}
  16.             You have {{ counter }} item.
  17.         {% plural %}
  18.             You have {{ counter }} items.
  19.         {% endblocktrans %}
  20.     </p>
  21. </body>
  22. </html>
复制代码
3、Python 代码中的国际化

3.1 视图和模型中的翻译
  1. # views.py
  2. from django.utils.translation import gettext as _
  3. from django.utils.translation import gettext_lazy, ngettext
  4. from django.http import JsonResponse
  5. from django.shortcuts import render
  6. def welcome_view(request):
  7.     # 简单翻译
  8.     message = _("Welcome to our application")
  9.    
  10.     # 带变量的翻译
  11.     username = request.user.username
  12.     greeting = _("Hello, %(username)s") % {'username': username}
  13.    
  14.     # 复数形式
  15.     item_count = 5
  16.     items_message = ngettext(
  17.         "You have %(count)d item",
  18.         "You have %(count)d items",
  19.         item_count
  20.     ) % {'count': item_count}
  21.    
  22.     return render(request, 'welcome.html', {
  23.         'message': message,
  24.         'greeting': greeting,
  25.         'items_message': items_message
  26.     })
  27. # API响应国际化
  28. def api_view(request):
  29.     return JsonResponse({
  30.         'message': _("Operation completed successfully"),
  31.         'error': _("Invalid input provided")
  32.     })
  33. # models.py
  34. from django.db import models
  35. from django.utils.translation import gettext_lazy as _
  36. class Product(models.Model):
  37.     name = models.CharField(_("Product name"), max_length=100)
  38.     description = models.TextField(_("Product description"))
  39.    
  40.     class Meta:
  41.         verbose_name = _("Product")
  42.         verbose_name_plural = _("Products")
  43.    
  44.     def __str__(self):
  45.         return _("Product: %(name)s") % {'name': self.name}
复制代码
3.2 表单和验证错误
  1. # forms.py
  2. from django import forms
  3. from django.utils.translation import gettext_lazy as _
  4. from django.core.validators import ValidationError
  5. class ContactForm(forms.Form):
  6.     name = forms.CharField(label=_("Your name"))
  7.     email = forms.EmailField(label=_("Email address"))
  8.     message = forms.CharField(
  9.         label=_("Message"),
  10.         widget=forms.Textarea,
  11.         error_messages={
  12.             'required': _("Please enter your message")
  13.         }
  14.     )
  15.    
  16.     def clean_email(self):
  17.         email = self.cleaned_data.get('email')
  18.         if not email.endswith('.com'):
  19.             raise ValidationError(_("Email must be from a .com domain"))
  20.         return email
  21.    
  22.     # 表单级别的错误消息
  23.     def clean(self):
  24.         cleaned_data = super().clean()
  25.         # 自定义验证逻辑
  26.         if cleaned_data.get('name') == cleaned_data.get('email'):
  27.             raise ValidationError(_("Name and email cannot be the same"))
复制代码
4、翻译文件

4.1 .po 文件
  1. # locale/zh_Hans/LC_MESSAGES/django.po
  2. # 清晰的注释说明上下文
  3. #. This message appears on the homepage banner
  4. msgid "Welcome to our site"
  5. msgstr "欢迎访问我们的网站"
  6. # 带变量的翻译
  7. msgid "Hello, %(username)s"
  8. msgstr "你好,%(username)s"
  9. # 复数形式
  10. msgid "You have %(count)d item"
  11. msgid_plural "You have %(count)d items"
  12. msgstr[0] "您有 %(count)d 个项目"
  13. msgstr[1] "您有 %(count)d 个项目"
  14. # 包含开发者注释
  15. # Translators: This message appears in the email subject
  16. msgid "Password reset request"
  17. msgstr "密码重置请求"
复制代码
4.2 提取和编译翻译
  1. # windows需要先安装gettext
  2. django-admin makemessages -l zh_Hans  # 简体中文
  3. django-admin makemessages -l en
  4. # 编译翻译文件
  5. django-admin compilemessages
  6. # 查看所有支持的语言
  7. python manage.py show_languag
复制代码
来源:豆瓜网用户自行投稿发布,如果侵权,请联系站长删除

相关推荐

您需要登录后才可以回帖 登录 | 立即注册