'Django - request.session not being saved

I have a pretty simply utility function that gets an open web order if their is a session key called 'orderId', and will create one if there is no session key, and the parameter 'createIfNotFound' is equal to true in the function. Stepping through it with my debugger I can see that the piece of code that sets the session key after an order has been created does get hit with no exceptions, but when I check the Http request object' session field, it does not have that attribute ?

Utility

def get_open_web_order(request, createIfNotFound=False):
    # Check for orderId in session
    order_id = request.session.get('orderId')
    web_order = None

    if None != order_id:
        try:
            web_order = WebOrder.objects.get(id=order_id, status='O')
            logging.info('Found open web order')
        except WebOrder.DoesNotExist:
            logging.info('Web order not found')

    if (None == web_order) and (createIfNotFound == True):
        logging.info('Creating new web order')

        web_order = WebOrder()
        web_order.status = 'O'

        web_order.save()
        request.session['orderId'] = web_order.id

        # Assign logged in user and default billing and shipping
        if request.user.is_authenticated() and hasattr(request.user, 'customer'):
            customer = request.user.customer
            web_order.customer = customer
            web_order.set_defaults_from_customer()
            web_order.save()

    return web_order


Solution 1:[1]

In some cases you need to explicitly tell the session that it has been modified.

You can do this by adding request.session.modified = True to your view, after changing something in session

You can read more on this here - https://docs.djangoproject.com/en/1.10/topics/http/sessions/#when-sessions-are-saved

Solution 2:[2]

I had a similar issue, turns out I had set SESSION_COOKIE_DOMAIN in settings.py to the incorrect domain so it would not save any of my new session data. If you are using SESSION_COOKIE_DOMAIN, try checking that!

For example, if I am running the server on my localhost but I have in my settings SESSION_COOKIE_DOMAIN = "notlocalhost", then nothing I change in request.session will save.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 4140tm
Solution 2