Using Sessions in Views

When SessionMiddleware is activated, each HttpRequest object-the first argument to any Django view function-will have a session attribute, which is a dictionary-like object. You can read it and write to request.session at any point in your view. You can edit it multiple times.

All session objects inherit from the base class backends.base.SessionBase. It has the following standard dictionary methods:

  • __getitem__(key)
  • __setitem__(key, value)
  • __delitem__(key)
  • __contains__(key)
  • get(key, default=None)
  • pop(key)
  • keys()
  • items()
  • setdefault()
  • clear()

It also has these methods:

flush()

Delete the current session data from the session and delete the session cookie. This is used if you want to ensure that the previous session data can't be accessed ...

Get Mastering Django: Core now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.