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

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top