更改语言前缀时i18n不起作用

时间:2016-04-20 11:09:52

标签: django internationalization django-i18n

我的i18n语言环境测试无法正常工作,目录如下:

enter image description here mysite.urls.py

from django.contrib import admin
from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns

urlpatterns = patterns('',
    url(r'^i18n/', include('django.conf.urls.i18n')),
)


urlpatterns += i18n_patterns(
    url(r'^admin/', include(admin.site.urls)),
    url(r'^localedemo/$', include('localedemo.urls')),

    # url(r'^$', 'localedemo.views.home', name='home'),
    # url(r'^i18n/', include('django.conf.urls.i18n')),
)

localedemo / urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name="index"),
    # url(r'^set-language/', views.set_language, name='set-language'),
]

localedemo / views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.utils.translation import ugettext_lazy as _
from django.utils import translation
def index(request):
    translation.activate('zh_CN')
    language = translation.get_language_from_request(request)
    print("language:" + language)
    #Translators: This message appears on the home page only
    output = _("Welcome to my site.")
    str = {'mystr': output}
    return render(request, 'localedemo/index.html',str)

运行服务器时,结果为:

result image

当我更改语言前缀时,它不起作用: the result not work

每个语言子辅助工具中的django.po是

msgid "Welcome to my site."
msgstr "this is english website"

msgid "Welcome to my site."
msgstr "中文网站"

msgid "Welcome to my site."
msgstr "中文繁体网站"

和localedemo / templates / index.html

 

   {% load i18n %}
    <html !DOCTYPE=html>
    <head><title>hi</title></head>
    <body>
    <div>
    	<h1>Hello, world!</h1>.

    	<h1>{% trans mystr %}</h1>
    	<h1>{{ mystr }}</h1>
    </div>

    <div>

    <form action="/i18n/setlang/" method="post">
    {% csrf_token %}
        <input name="next" type="hidden" value="/" />

        <select name="language">

            {% for lang in LANGUAGES %}

                    <option value="{{ lang.0 }}" {% if lang.0 == SELECTEDLANG %}selected{% endif %}>{% if lang.1 == 'Spanish' %}Español{% else %}{{ lang.1 }}{% endif %}</option>

            {% endfor %}

        </select>

        <input type="submit" value="Go" />

    </form>

    </div>

    <div>

        {% get_current_language as LANGUAGE_CODE %}
    <!-- Current language: {{ LANGUAGE_CODE }} -->
    <p>{% trans "Welcome to my site." %}</p>

    {% language 'en' %}
        {% get_current_language as LANGUAGE_CODE %}
        <!-- Current language: {{ LANGUAGE_CODE }} -->
        <p>{% trans "Welcome to my site." %}</p>
    {% endlanguage %}
    </div>
    </body>
    </html>

当我在列表框中选择语言时: enter image description here

我错过了什么或者我做错了吗?有人可以帮帮我吗?提前谢谢

1 个答案:

答案 0 :(得分:0)

检查mysite/urls.py。您的索引网址以localedemo

开头
url(r'^localedemo/$', include('localedemo.urls')) 

您将next值传递为/。 因此,要么将其更改为localedemo/,要么将索引网址移至mysite/urls.py