在 Django 中创建会话 [英] Create a Session in Django

查看:24
本文介绍了在 Django 中创建会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,Django 的文档太技术化了.如何创建会话并在其中存储变量或从中获取变量?我是 Django 框架的新手,因此文档太技术化了.会话是我的最后一步".

So far the Documentation for Django has been too technical. How do I create a session and store variables in it or get variables from it? I'm new to the Django framework, hence why the Documentation is too technical. Sessions are my 'last step'.

推荐答案

假设您想要基于数据库的会话(Django 也提供基于文件的会话和基于缓存的会话):

Assuming you want database based sessions (Django also offers file based sessions, and cache based sessions):

  1. 打开 settings.py 并找到 MIDDLEWARE_CLASSES.将 'django.contrib.sessions.middleware.SessionMiddleware' 添加到列表中.
  2. 在同一个文件中找到 INSTALLED_APPS 并在那里添加 'django.contrib.sessions'.
  3. 从命令行运行 manage.py syncdb.
  1. Open settings.py and find MIDDLEWARE_CLASSES. Add 'django.contrib.sessions.middleware.SessionMiddleware' to the list.
  2. Find INSTALLED_APPS in the same file and add 'django.contrib.sessions' there.
  3. Run manage.py syncdb from the command line.

初始设置后,您可以在视图中使用 request.session 来存储请求之间的信息.

After the initial setup you can use request.session in your views to store information between requests.

例如这将存储信息:

request.session['name'] = 'Ludwik'

您可以轻松检索它:

print request.session['name']

if request.session['name'] == 'Ludwik':
   print 'you are awesome!'

对于您可以使用 request.session 对象执行的其他操作,请参阅 文档.

For other things you can do with the request.session object see the documentation.

这篇关于在 Django 中创建会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆