问题描述
到目前为止,Django的文档已经太技术性了。如何创建会话并存储变量或从中获取变量?我是Django框架的新手,因此为什么文档太技术性了。会话是我的最后一步。假设你想要基于数据库的会话(Django还提供基于文件的会话,会话):
- 打开settings.py并找到
MIDDLEWARE_CLASSES
。将'django.contrib.sessions.middleware.SessionMiddleware'
添加到列表中。 - 查找
INSTALLED_APPS
在同一个文件中,并添加
'django.contrib.sessions'
。 - 运行
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):
- Open settings.py and find
MIDDLEWARE_CLASSES
. Add 'django.contrib.sessions.middleware.SessionMiddleware'
to the list. - Find
INSTALLED_APPS
in the same file and add 'django.contrib.sessions'
there. - 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中创建一个会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!