无法改变django

时间:2016-03-26 13:10:26

标签: python django internationalization

此方法应使用语言代码设置语言:

def set_language(request):
    if request.method == 'POST':
        response = HttpResponseRedirect(reverse('root'))
        lang_code = request.POST.get('language', None)
        if lang_code and check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session['django_language'] = lang_code
            else:
                response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
        return response
    return render(request, 'profile/change_language.html')

以下表格位于html change_language.html

<form action="{% url 'profile:language' %}" method="post">
            {% get_current_language as LANGUAGE_CODE %}
                <label for="new_lang">{% trans "Choose your language:" %}</label>
                 <fieldset>
                     <input type="radio" id="de" name="language" value="de" {% if LANGUAGE_CODE == 'de' %} checked {% endif %} >
                     <label for="de">German</label>

                     <input type="radio" id="uk" name="language" value="en" {% if LANGUAGE_CODE == 'en' %} checked {% endif %} >
                     <label for="en">English</label>
                 </fieldset>

                {{ form.newlang }}
                <input type="submit" value="Change language">
                {% csrf_token %}
</form>

在settings.py中,我有以下相关设置:

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.security.SecurityMiddleware',
)


LANGUAGE_CODE = 'en'
TIME_ZONE = 'CET'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# Languages available
LANGUAGES = (
    ('de', 'German'),
    ('en', 'English'),
)

当我启动网站时,我的语言是德语(我在德国)。当我进入change_language页面并尝试将语言从德语设置为英语时,它不会改变任何内容。有什么东西我可能会忘记吗?

1 个答案:

答案 0 :(得分:2)

您需要先激活语言。您所需要的只是:

from django.utils import translation
from django.shortcuts import redirect
from django.conf import settings

def set_language(request):
    language = request.POST.get('language', settings.LANGUAGE_CODE)
    translation.activate(language)
    request.session[translation.LANGUAGE_SESSION_KEY] = language
    return redirect('root')