4

Using the Django logout when the user is logging out all the sessions values get flushed. I there a way to keep some of the session values even though the user logs out?

avatar
  • 12,087
  • 17
  • 66
  • 82
  • What do you mean by "keep"? A session is for a particular user, so when the user logs out, leaving his session doesn't make sense. If you need to store some values in the db before `django.contrib.auth.logout` flushes the session data, you can do so by simply overriding `django.contrib.auth.views.logout`. – Cloud Artisans Feb 13 '11 at 17:35
  • 2
    Here is what want to do. When the user logs out I want to keep the user name in a session variable so when he comes back to the web site I can "recognize" the user so I can see something "hello user". – avatar Feb 13 '11 at 20:52

1 Answers1

4

You might want to use cookie instead of session to achieve this.

# views.py, login view
# After you have authenticated a user
username = 'john.smith'  # Grab this from the login form

# If you want the cookie to last even if the user closes his browser,
# set max_age to a very large value, otherwise don't use max_age.
response = render_to_response(...)
response.set_cookie('the_current_user', username, max_age=9999999999)

In your login view:

remembered_username = request.COOKIES.get('the_current_user', '')

Push the above to the template to display:

Hello {{ remembered_username }}

Reference: http://docs.djangoproject.com/en/1.2/ref/request-response/#django.http.HttpResponse.set_cookie

Thierry Lam
  • 45,304
  • 42
  • 117
  • 144
  • I'm getting a "global name 'set_cookie' is not defined". What do I need to import? – avatar Feb 16 '11 at 04:51
  • set_cookie is a method of a HttpResponse object, you don't need to import anything. Can you paste a copy of your sample code? – Thierry Lam Feb 16 '11 at 05:11