Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django's logout function remove locale settings

When I use Django's logout function to log out an authenticated user, it switched locale to en_US, the default one.

from django.contrib.auth import logout

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

How to keep user's locale after logged out?

like image 811
jack Avatar asked Aug 09 '26 22:08

jack


2 Answers

I solved the problem by wrapping the django.contrib.auth.views.logout within a custom view and resetting the session language after logout. There's some code.

I have an app named login with following urls.py:

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

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

So now URL /logout/ calls a view named logoutAction in views.py. In logoutAction, the old language code is stored temporarily and inserted back to the session after calling Django's 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

The end of the LAN Quake problem :)

like image 97
Akseli Palén Avatar answered Aug 11 '26 17:08

Akseli Palén


You could try explicitly setting the language cookie when the user logs out, there's a bit about how django determines the language setting here in the djangodocs.

I would have presumed that the language setting would have remained as a session value on logging out, maybe it needs to be reinitialised if django completely destroys the session on logging out the user.

like image 22
NeonNinja Avatar answered Aug 11 '26 16:08

NeonNinja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!