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

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

问题描述

到目前为止,Django的文档已经太技术性了。如何创建会话并存储变量或从中获取变量?我是Django框架的新手,因此为什么文档太技术性了。会话是我的最后一步。

解决方案

假设你想要基于数据库的会话(Django还提供基于文件的会话,会话):


  1. 打开settings.py并找到 MIDDLEWARE_CLASSES 。将'django.contrib.sessions.middleware.SessionMiddleware'添加到列表中。

  2. 查找 INSTALLED_APPS 在同一个文件中,并添加'django.contrib.sessions'

  3. 运行 manage.py syncdb 从命令行。

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



例如,这将存储信息:

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

,您可以轻松地检索:

  print request.session ['name' ] 

 code>如果request.session ['name'] =='Ludwik':
打印'你真棒!'

对于其他事情,您可以使用 request.session 对象参见文档


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'.

解决方案

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

  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.

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

For example this will store the information:

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

and you can retrieve it as easly:

print request.session['name']

or

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

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

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

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