Django Session KeyError when key exists

Viewed 5474

The following code works locally when I use Django's development server, but I am running into intermittent bugs in production with Nginx and Gunicorn.

views.py

def first_view(request):
    if request.method == "POST":
        # not using a django form in the template, so need to parse the request POST
        # create a dictionary with only strings as values
        new_post = {key:val for key,val in request.POST.items() if key != 'csrfmiddlewaretoken'}
        request.session['new_post'] = new_mappings # save for use within next view

        # more logic here (nothing involving views)
        return redirect('second_view')

def second_view(request):
    if request.method == 'POST':
        new_post = request.session['new_post']
        # ... more code below
        # render template with form that will eventually post to this view

I will sometimes receive a KeyError after posting to the second view. Based on the documentation on when sessions are saved, it seems like the session variable should be saved since it is modifying the session directly. Also, if I take the sessionid provided the error page's debug panel and access the session via Django's API, I can see the 'new_post' session variable

python manage.py shell
>>> from django.contrib.sessions.backends.db import SessionStore
>>> s = SessionStore(session_key='sessionid_from_debug_panel')
>>> s['new_post']
# dictionary with expected post items

Is there something I'm missing? Thanks in advance for your help!

1 Answers
Related