当我使用 Django 的注销功能注销经过身份验证的用户时,它将语言环境切换为 en_US,这是默认设置。
from django.contrib.auth import logout
def someview(request):
logout(request)
return HttpResponseRedirect('/')
注销后如何保留用户的语言环境?
当我使用 Django 的注销功能注销经过身份验证的用户时,它将语言环境切换为 en_US,这是默认设置。
from django.contrib.auth import logout
def someview(request):
logout(request)
return HttpResponseRedirect('/')
注销后如何保留用户的语言环境?
我通过将 django.contrib.auth.views.logout 包装在自定义视图中并在注销后重置会话语言来解决问题。有一些代码。
我有一个名为 login 的应用程序,带有以下 urls.py:
# myproject/login/urls.py
from django.conf.urls.defaults import patterns
urlpatterns = patterns('myproject.login.views',
...
(r'^logout/$', 'logoutAction'),
...
)
所以现在 URL /logout/ 在 views.py 中调用了一个名为 logoutAction 的视图。在 logoutAction 中,旧语言代码被临时存储,并在调用 Django 的 contrib.auth.views.logout 后插入回会话中。
# myproject/login/views.py
...
from django.contrib.auth.views import logout as auth_logout
def logoutAction(request):
# Django auth logout erases all session data, including the user's
# current language. So from the user's point of view, the change is
# somewhat odd when he/she arrives to next page. Lets try to fix this.
# Store the session language temporarily if the language data exists.
# Its possible that it doesn't, for example if session middleware is
# not used. Define language variable and reset to None so it can be
# tested later even if session has not django_language.
language = None
if hasattr(request, 'session'):
if 'django_language' in request.session:
language = request.session['django_language']
# Do logout. This erases session data, including the locale language and
# returns HttpResponseRedirect to the login page. In this case the login
# page is located at '/'
response = auth_logout(request, next_page='/')
# Preserve the session language by setting it again. The language might
# be None and if so, do nothing special.
if language:
request.session['django_language'] = language
# Now user is happy.
return response
LAN Quake 问题结束 :)
您可以尝试在用户注销时显式设置语言 cookie,在djangodocs中有一些关于 django 如何确定语言设置的内容。
我会假设语言设置在注销时会保留为会话值,如果 django 在注销用户时完全破坏会话,则可能需要重新初始化。
您可以创建一个 UserProfile 模型(对用户具有唯一的外键)并在那里保存用户的语言首选项(以及任何其他额外的用户特定设置)。然后在每次用户登录时,可以将语言环境设置为保存在用户的 UserProfile 中的语言代码。
Django 有一个设置 AUTH_PROFILE_MODULE,您可以在其中将模型设置为 django.contrib.auth 的“官方”用户配置文件模型