2010-04-29 42 views
3

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

from django.contrib.auth import logout 

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

如何在注销后保持用户的语言环境?

回答

1

你可以尝试明确当用户注销设置语言Cookie“官方”用户配置文件的模式,有一个有关django如何确定djangodocs中的语言设置。

我会假设语言设置会在注销时保持为会话值,如果django在注销用户时完全破坏会话,则可能需要重新初始化。

0

您可以创建一个UserProfile模型(对用户具有唯一的外键),并在那里保存用户的语言偏好(以及任何其他额外的用户特定设置)。然后在每个用户登录时,语言环境可以设置为保存在用户UserProfile中的语言代码。

的Django有一个设置AUTH_PROFILE_MODULE,在这里你可以设置一个模型作为django.contrib.auth

+0

年底我不能完全肯定,将工作当用户登录_out_但defintely当他们登录标签:APIWinHTTP – NeonNinja 2010-04-29 08:41:26

+0

用户配置文件的用户不会帮助后登出。 – jack 2010-04-30 14:32:37

2

我通过在自定义视图中包装django.contrib.auth.views.logout并在注销后重置会话语言来解决了该问题。有一些代码。

我有以下urls.py一个名为登录应用程序:

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

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

所以现在URL /注销/调用一个名为logoutAction在views.py视图。在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 

局域网地震问题:)

+1

它为我工作,谢谢。你忘记在'if hasattr(..)'之前放置'language = None'。否则可能会失败。 – Menda 2012-08-01 13:57:16

+0

@Menda感谢您的通知!修复。 – 2012-08-03 10:53:39