Search code examples
pythondjangodjango-modelsdjango-sessions

Unable to figure out the cause of a Django KeyError


I am trying to make an eCommerce site and I am using Django sessions to store items in the cart, initially, it was all working perfectly fine until I decided to do something stupid and changed the session token in the inspection in chrome. And from then onwards I am thrown with a KeyError.

Django Version: 3.0.8
Exception Type: KeyError
Exception Value: 'order1'

I then ran the following code in my terminal...

from django.contrib.sessions.models import Session
Session.objects.all().delete()

That cleared out my table but still didn't seem to sort out this error. I even tried to host it in Heroku and access the website from a different device and a still thrown with this error. Is there anything I can do about this?

And just in case here is my views.py...

def shop(request):

    if not request.session['order1']:
        request.session['order1'] = []


    if request.method == "POST":
        quantity = int(request.POST.get('quantity'))
        name = request.POST.get('name')

        if quantity >= 1:
            new_order = {"quantity":quantity, "name":name}

            request.session['order1'].append(new_order)
            
            # request.session['order'] = order
            context = {
                "check":request.session['order1'],
            }
        else:
            messages.warning(request, "You have entered an invalid quantity")
            context={}
    else:
        context={}
    return render(request, "store/shop.html", context)

Any help would be greatly appreciated. Thanks!


Solution

  • Looking up a key using the square bracket syntax will raise a KeyError if the key doesn't exist in the dictionary/collection

    if not request.session['order1']:
    

    Should be

    if not request.session.get('order1'):
    

    Using try/except KeyError would also work...