你可以使用
i18n switcher在
settings.py
中更改和保存
LANGUAGE_CODE,这样即使你使用不同的浏览器,语言也不会改变。
首先,你需要完成以下3个步骤:
在User
模型中添加lang
字段,根据两种方式(我的答案)之一创建自定义User
模型。*我推荐更可定制的方式(我的答案)而不是较不可定制的方式(我的答案)
lang = models.CharField(max_length=20, blank=True)
按照我的答案设置Djnago的翻译(英语和法语)。
分别按照我的答案和我的答案为Django和/或Django Admin创建。
接下来,创建
special/middleware/
、
special/views/
和
special/conf/urls/
文件夹,并在其中分别添加
__init__.py
(空文件),然后将
django/middleware/locale.py
、
django/views/i18n.py
和
django/conf/urls/i18n.py
中的
locale.py
、
i18n.py
和
i18n.py
复制到您的虚拟环境中的
special/middleware/
、
special/views/
和
special/conf/urls/
文件夹中,如下所示:
django-project
|-core
| |-settings.py
| |-urls.py
| └-special
| |-middleware
| | |-__init__.py
| | └-locale.py # Here
| |-views
| | |-__init__.py
| | └-i18n.py # Here
| └-conf
| |-__init__.py
| └-urls
| |-__init__.py
| └-i18n.py # Here
|-my_app1
| |-views.py
| |-urls.py
| |-models.py
| |_admin.py
| └-apps.py
|-my_app2
|-templates
| └-index.html
└-locale
└-fr
└-LC_MESSAGES
└-django.po
然后,在core/settings.py中,将`'django...LocaleMiddleware'`替换为`'core...LocaleMiddleware'`,如下所示:
MIDDLEWARE = [
...
"django.contrib.sessions.middleware.SessionMiddleware",
'core.special.middleware.locale.LocaleMiddleware',
"django.middleware.common.CommonMiddleware",
]
然后,在core/urls.py
中将path(... include("django..."))
替换为path(... include("core..."))
,如下所示:
urlpatterns += [
path("i18n/", include("core.special.conf.urls.i18n"))
]
然后,按照下面的示例将以下代码添加到
core/special/middleware/locale.py
中:
...
from django.contrib import auth
...
class LocaleMiddleware(MiddlewareMixin):
...
def process_request(self, request):
...
if (
not language_from_path
and i18n_patterns_used
and not prefixed_default_language
):
language = settings.LANGUAGE_CODE
user = auth.get_user(request)
if user.is_authenticated and user.lang:
language = user.lang
user = auth.get_user(request)
if user.is_authenticated and user.userprofile.lang:
language = user.userprofile.lang
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
然后,按照下面的示例将以下代码添加到
core/special/views/i18n.py
中:
...
def set_language(request):
...
response.set_cookie(
settings.LANGUAGE_COOKIE_NAME,
lang_code,
max_age=settings.LANGUAGE_COOKIE_AGE,
path=settings.LANGUAGE_COOKIE_PATH,
domain=settings.LANGUAGE_COOKIE_DOMAIN,
secure=settings.LANGUAGE_COOKIE_SECURE,
httponly=settings.LANGUAGE_COOKIE_HTTPONLY,
samesite=settings.LANGUAGE_COOKIE_SAMESITE,
)
user = request.user
if user.is_authenticated:
user.lang = lang_code
user.save()
user = request.user
if user.is_authenticated:
user.userprofile.lang = lang_code
user.userprofile.save()
return response
最后,在`core/special/conf/urls/i18n.py`中,将
from django... import set_language
替换为
from core... import set_language
,如下所示。
...
from core.special.views.i18n import set_language