开发者

Django : make a variable persistent

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开发者_StackOverflow社区 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


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:

SESSION_ENGINE = 'django.contrib.sessions.backends.cookies'

And then in a view you can do this:

request.session['project'] = 'Some Project'

And in templates you can then use:

{{ request.session.project }}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜