翻译django中的模板

时间:2015-07-07 17:11:09

标签: python django internationalization django-i18n

我在Django 1.8中有项目。 我想拥有3种语言的网站,但是当我选择语言时,没有任何事情发生:

我的模板中的代码:

    {% load i18n %}

    ...

<form action="{% url 'set_language' %}" method="post">
    {% csrf_token %}
    {% get_available_languages as LANGUAGES %}
    {% get_language_info_list for LANGUAGES as languages %}
    {% for language in languages %}
    <a href="{% url 'set_language' %}">{{ language.code }}</a>
    {% endfor %}
    <span class="glyphicon glyphicon-globe"></span>
</form>

我的网址:

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'website.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^i18n/', include('django.conf.urls.i18n')),
    url(r'', include("www.urls", namespace="www")),
    url(r'^blog/', include("blog.urls", namespace="blog")),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^ckeditor/', include('ckeditor.urls')),
)

我的设置(区域设置) - 我在这里使用django-rosetta:

LANGUAGE_CODE = 'en-us'

LANGUAGES = (
    ('pl', u'Poland'),
    ('en', u'US'),
    ('ru', u'Russia'),
)

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

1 个答案:

答案 0 :(得分:0)

您编写的代码无效。

内置django set_language视图接受language代码作为parateter的POST请求。即使在表单视图中单击a标记,也可以获取GET请求。

将模板更改为以下

<form action="{% url 'set_language' %}" method="post">{% csrf_token %}
    <select name="language">
        {% get_current_language as LANGUAGE_CODE %}
        {% get_available_languages as LANGUAGES %}
        {% get_language_info_list for LANGUAGES as languages %}
        {% for language in languages %}
            <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}>
                {{ language.name_local }} ({{ language.code }})
            </option>
        {% endfor %}
    </select>
    <input type="submit" value="Go" />
</form>

https://docs.djangoproject.com/en/1.8/topics/i18n/translation/#the-set-language-redirect-view