gpt4 book ai didi

Django 的注销功能删除语言环境设置

转载 作者:行者123 更新时间:2023-12-02 00:40:27 25 4
gpt4 key购买 nike

当我使用 Django 的注销功能注销经过身份验证的用户时,它会将区域设置切换为默认的 en_US。

from django.contrib.auth import logout

def someview(request):
logout(request)
return HttpResponseRedirect('/')

如何在退出后保留用户的语言环境?

最佳答案

我通过在自定义 View 中包装 django.contrib.auth.views.logout 并在注销后重置 session 语言解决了这个问题。有一些代码。

我有一个名为 login 的应用程序,其 urls.py 如下:

# myproject/login/urls.py
from django.conf.urls.defaults import patterns

urlpatterns = patterns('myproject.login.views',
...
(r'^logout/$', 'logoutAction'),
...
)

所以现在 URL/logout/在 vi​​ews.py 中调用了一个名为 logoutAction 的 View 。在 logoutAction 中,旧的语言代码被临时存储,并在调用 Django 的 contrib.auth.views.logout 后插入回 session 。

# 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 问题结束:)

关于Django 的注销功能删除语言环境设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2735476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com