Search code examples
pythondjangodjango-viewssavedjango-sessions

request.session is not saved in Django


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

  • 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