【问题标题】:django - storing session values after user logoutdjango - 用户注销后存储会话值
【发布时间】:2011-06-26 11:06:08
【问题描述】:

当用户注销时使用 Django logout,所有会话值都会被刷新。 即使用户注销,我有办法保留一些会话值吗?

【问题讨论】:

  • “保持”是什么意思?会话是针对特定用户的,因此当用户注销时,离开他的会话没有意义。如果您需要在django.contrib.auth.logout 刷新会话数据之前在数据库中存储一些值,您可以通过简单地覆盖django.contrib.auth.views.logout 来实现。
  • 这是想要做的。当用户注销时,我想将用户名保留在会话变量中,这样当他回到网站时,我可以“识别”用户,这样我就可以看到“hello user”的内容。

标签: django django-views django-authentication django-sessions


【解决方案1】:

您可能希望使用 cookie 而不是 session 来实现这一点。

# 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)

在您的登录视图中:

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

将上面推送到模板中显示:

Hello {{ remembered_username }}

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

【讨论】:

  • 我得到一个“未定义全局名称'set_cookie'”。我需要导入什么?
  • set_cookie 是一个 HttpResponse 对象的方法,你不需要导入任何东西。你能粘贴一份你的示例代码吗?
猜你喜欢
  • 2023-03-27
  • 2012-09-28
  • 1970-01-01
  • 2015-04-02
  • 1970-01-01
  • 2020-02-05
  • 2018-03-01
  • 2015-08-14
  • 2018-02-25
相关资源
最近更新 更多