所有。在非常简单的应用程序中,语言切换存在一些问题:
settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
)
ROOT_URLCONF = 'lr.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.i18n',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
],
},
},
]
urls.py
urlpatterns = [
url(r'^$', home, name='home'),
url(r'^auth/(?P<cmd>.*)$', auth, name='auth'),
url(r'^i18n/(?P<lang>.*)$', i18n, name='i18n'),
url(r'^admin/', include(admin.site.urls)),
]
views.py
class HomePageView(TemplateView):
"""
Template view for Home page
"""
template_name = 'home.html'
def home(request):
"""
Site title page
"""
return HomePageView.as_view()(request)
def i18n(request, **kwargs):
"""
Change locale processing
"""
from django.utils.translation import check_for_language
if 'lang' in kwargs:
lang = kwargs['lang']
if lang and check_for_language(lang):
if hasattr(request, 'session'):
request.session[LANGUAGE_COOKIE_NAME] = lang
if request.method == 'POST' \
and 'redirect' in request.POST:
# Place hidden input, named 'redirect' in login form in html template
# for making redirect to the same page after login/logout
return HttpResponseRedirect(request.POST['redirect'])
return HttpResponseRedirect('/')
页面模板为空,它只是标题,登录表单和ru / eng开关表单(只有三个单词用于翻译)。
不知何故,模板中的语言代码(get_current_language)始终是&#39; en&#39;除非我放置django.middleware.locale.LocaleMiddleware&#39;在MIDDLEWARE_CLASSES的顶部 - 在这种情况下,他总是&#39; ru。 我试过使用django.conf.urls.i18n,translation.activate()等许多东西,但没有用。请告诉我一个问题,我做错了什么?
此处提供的整个项目代码:https://www.dropbox.com/s/a7nojxpxpajcbmu/lr.zip?dl=0
答案 0 :(得分:0)
我认为你缺少一个LANGUAGES设置。
列表是格式(语言代码,语言名称)的两元组列表 - 例如,(&#39; ja&#39;,&#39;日语&#39;)。这指定了哪些语言可用于语言选择。见国际化和本地化。