开发者

Where to initialize Django session variables?

开发者 https://www.devze.com 2023-02-01 08:23 出处:网络
In my Django project I am building a shopping cart system.I want to store the shopping cart data in a session variable, but I don\'t know where to initialize it.

In my Django project I am building a shopping cart system. I want to store the shopping cart data in a session variable, but I don't know where to initialize it.

I have tried doing something like this:

if 'cart' not in request.session:
    requ开发者_如何学运维est.session['cart'] = {}

in a custom context processor, but the context processor does not seem to modify the session data. Where else would I put an initialization like this? I don't want to have to put it in every place where I get values from the cart.


You could put it in a piece of custom request middleware, but to be honest, I think that would be overkill here. It's probably easier to just initialize the cart when you need it in your view function. Note that you can use request.session.get to automatically grab a default value if the value doesn't already exist. Something like:

def my_view(request):
    cart = request.session.get('cart', {})
    # Do stuff with cart
    request.session['cart'] = cart


Doing this in middleware (underneath the session middleware, obviously) will make certain that it's always set.


Your code should work as is with a context_processor, assuming your views are always using RequestContext.

I'm doing exactly the same thing for my cart, based on Satchmo of a few years back. I have a context_processor where I find the Cart from the session and pass it to the template. A lot of other session modification is done there too...

So.. your code should work as is. Is it executing at all? Is it installed?


Why do you need to test if cart is in the request.session. Why not do something like this:

cart_value = request.session.get('cart',{})

Basically what that will do is return the value at 'cart' in session and if there are no values in the cart then return the empty dictionary.

0

精彩评论

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