我在django国际化(i18n)中遇到了问题。翻译不起作用。 我的django版本是:1.5.4 这是我的代码:
settings.py
ugettext = lambda s:s
LANGUAGES = [
('en','English'),
('fa','Farsi'),
]
LANGUAGE_CODE = 'en_us'
USE_I18N = True
USE_L10N = True
TEMPLATE_DIRS = (
os.path.join(PROJECT_PATH,'templates'),
)
urls.py
from django.conf.urls import patterns, include, url
from main import *
urlpatterns = patterns('',
url(r'$^',index),
)
main.py
from django.shortcuts import render
from django.utils.translation import ugettext_lazy as _
def index(request):
alert = _('this is my page')
return render(request,'index.html',{'alert':alert})
的index.html
{% load i18n %}
{{alert}}
然后:
$mkdir conf/locale -p
$django-admin.py makemessages -l fa
processing language fa
$django-admin.py compilemessages
processing file django.po in /home/mori/Desktop/salam/salam/locale/fa/LC_MESSAGES
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: 2013-10-15 13:12+0330\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"
#: main.py:4
msgid "this is my page"
msgstr "in safeye mane"
我在中间件类中有'django.middleware.locale.LocaleMiddleware',在TEMPLATE_COTEXT_PROCESSORS中有'django.core.context_processors.i18n'。
输出
this is my page
我该如何解决?
答案 0 :(得分:2)
使用国际化:
settings.py
。您需要set the language for the request,否则django会默认使用来自浏览器的语言请求,在您的情况下是英语。
您还需要修复模板,它应该是:
{% load i18n %}
{% trans alert %}
在您的视图中,_
函数仅标记您的字符串以进行翻译;它实际上并没有翻译它。将字符串标记为翻译使django将其导出到语言文件中,并使django在用户请求其他语言时查找它。
有a few ways that django detects the preferred language(它会在找到语言首选项的第一个位置停止)。按照检查顺序的这些方式是:
/en/foo/bar/
django_language
键。django_language
Cookie。Accept-Language
标题。LANGUAGE_CODE
设置。在你的情况下,它会捕获#4,因为你的浏览器正在发送它将接受的语言列表,第一个是英语。
有几种方法可以解决这个问题:
activate('fa')
您可以使用language
模板标记强制模板中的语言:
{% load i18n %}
{% language 'fa' %}
{% trans alert %}
set_language
重定向视图配对,以正确设置语言并将您的网址国际化。答案 1 :(得分:0)
我忘记在settings.py
中考虑过一件事:
LOCALE_PATHS