Django:使变量持久化
基本上我想让一个变量永久存在于 Django 中,但我不知道如何做。
更准确地说,我希望用户在登录网站时选择一个特定的项目(例如通过 ChoiceField)。然后,只要他没有选择另一个项目,站点就“知道”他选择了什么项目,这样他就可以执行一些与该项目相关的操作。
这怎么可能?会话变量是正确的方法吗?或者也许是缓存系统? 一些提示:)
如果我不够清楚,请告诉我
Basically I want to make a variable persitent in Django and I don't know how.
To be more precise, I want a user to choose a specific project when he logs in the site (via a ChoiceField for example). Then, for as long as he does not select another project, the site "knows" what project he selected so he can do some actions related to this project.
How is that possible ? Are sessions variables the way to go ? Or maybe the cache system ? A few hints would be greatly appreciated :)
Please let me know if I'm not being clear enough
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只要会话存储可用,会话就很好,这意味着如果您需要此功能可靠,则必须使用数据库会话后端(或Redis之类的东西)。
您还可以将
ForeignKey(Project, on_delete=SET_NULL)
添加到 用户配置文件模型并用它来存储当前项目。Session is good as long as the session storage is up, which means that if you need this functionality to be reliable, you have to use the database session backend (or something like Redis).
You could also add
ForeignKey(Project, on_delete=SET_NULL)
to user profile model and use it to store the current project.是的 - 您需要使用会话变量,因为这些变量会持续存在,但仅限于每个用户。缓存将为所有用户保留。
查看:Django 文档中的“如何使用会话”。
本质上,您只需在
settings.py
中设置会话引擎:然后在视图中您可以执行以下操作:
然后在模板中您可以使用:
Yes - you'll want to use a session variable, as these persist but only per-user. A cache will persist for all users.
Check this out: 'How to use sessions' from Django documentation.
Essentially, you just have to set the session engine in
settings.py
:And then in a view you can do this:
And in templates you can then use: