2

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

Johanna
  • 1,343
  • 4
  • 25
  • 44

2 Answers2

5

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 }}
Sam Starling
  • 5,298
  • 3
  • 35
  • 52
  • For now, users don't need to log in the site, my auth_users table is not filled in yet. Is it necessary to know the user to use session variables ? – Johanna Aug 24 '11 at 09:56
  • No, there's no need for a user to register for this. They'll just be given a cookie to identify them. – Sam Starling Aug 24 '11 at 10:03
  • Thanks, that seems simple enough :) – Johanna Aug 24 '11 at 10:09
  • maybe it's a bit off topic, but how can I display a form (the one used to get the session variable) appear in all the templates? – Johanna Aug 24 '11 at 13:19
  • Put it into a base template, and have all your other templates extend that template. It's called [template inheritance](https://docs.djangoproject.com/en/dev/topics/templates/#id1). – Sam Starling Aug 24 '11 at 13:30
  • I did that, but in the base template I call it like {{form}} because it is generated from a view. So when the template is not called from this view it doesn"t show up. Don't know if I'm clear .. – Johanna Aug 24 '11 at 14:01
  • @Johanna let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/2807/discussion-between-sam-and-johanna) – Sam Starling Aug 24 '11 at 14:29
1

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.

Tomasz Zieliński
  • 16,136
  • 7
  • 59
  • 83