Often times it’s necessary to have data stored PER user. A perfect example of this (and my particular problem) is/was a shopping cart: the core of any e-commerce site.
How do we do that? One of the problems is that the users in question are anonymous users. If they were registered users, we could easily take
request.user and identify them that way. For anonymous users, we need cookies to identify who’s who.
Luckily Django automatically generates nice cookies that ID the user in a secure fashion (not anything like: logged_in=1) so most of the work is done.
Basically, request.session is a mutable dictionary. Fantastic!
That means you can literally do something like this:
request.session['Arbitrary'] = 'This is Arbitrary Data'
and retrieve it any time you wish in the same fashion:
data = request.session['Arbitrary']
This is useful for a shopping cart because you can create a cart, and put its ID in request.session to know which user session it belongs to.
newcart = Cart()
request.session['shopping_cart'] = newcart.id
and every time you need to access a users cart
request.session['shopping_cart']identifies the cart they are using!
Note: You would have write a statement so that a new cart is created if request.session[‘cart’] is blank. You should have a check in place to do that.
If not request.session['shopping_cart'], create cart, else get cart.
This clearly isn’t limited to shopping carts though… Cool stuff.