Django:错误的语言偏好 [英] Django: wrong language preference

查看:68
本文介绍了Django:错误的语言偏好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Django创建两种语言的Web项目:英语和德语. 该文档的默认语言是英语,我自己翻译成德语,并创建了一个.po文件.

I use Django to create a web project in two languages: english and german. The default language of the document is english and I translated it in german by my own and created a .po file.

我的想法是,如果有人说德语,并且浏览器的语言环境设置为"de",则Django应该切换到德语(我提供的翻译).但在其他所有情况下,都应切换为英语.

My idea is that if someone speaks german and the browser's locale is set to "de", Django should switch to german (the translation i provide). BUT in every other case, it should switch to english.

问题是,它正好相反,我不知道为什么!

状态:如果浏览器的语言环境设置为英语,则网站以英语显示.但在任何其他情况下,它都以德语显示.

Status quo: If the browser's locale is set to english, the website is displayed in english. but in any other case it is displayed in german.

LANGUAGE_CODE = 'en-us'

_ = lambda s: s
LANGUAGES = (
      ('en', _('English')),
      ('de', _('German')),
)

正确设置了中间件,还设置了语言环境路径! 在测试网站时,我会清除所有cookie和缓存. 我试图提供两种翻译(德语和英语,即使它已经用英文写了),但效果还是一样.

The middlewares are correctly set, the locale-path as well! When I test the website, I clear all the cookies and the cache. I tried to provide two translations (germand AND english, even though it is already written in english), but still the same effect.

感谢您的帮助.

推荐答案

如果您希望用户能够指定语言,请确保已启用LocaleMiddleware:

If you want your users to be able to specify language, make sure that LocaleMiddleware is enabled:

MIDDLEWARE_CLASSES = (
   ...
   'django.middleware.locale.LocaleMiddleware',
   ...
)

然后Django将按该顺序查找用户的语言偏好设置:

Then Django will look for the user's language preference in that order:

因此,在Django会话中显式设置语言的最直接方法是重写request.session ['django_language']:

So the most straightforward way to set language explicitly in Django session, is to rewrite request.session['django_language']:

def someview (request):
    ...
    request.session['django_language'] = 'en'
    ...

这篇关于Django:错误的语言偏好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆