简体   繁体   English

无法找出 Django KeyError 的原因

[英]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.我正在尝试创建一个电子商务网站,并且我正在使用 Django 会话将物品存储在购物车中,最初,一切都很好,直到我决定做一些愚蠢的事情并在 chrome 中更改 session 令牌。 And from then onwards I am thrown with a KeyError .从那时起,我被抛出一个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.我什至尝试将它托管在 Heroku 并从不同的设备访问该网站,但仍然抛出此错误。 Is there anything I can do about this?对此我能做些什么吗?

And just in case here is my views.py...以防万一这是我的意见.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!谢谢!

Looking up a key using the square bracket syntax will raise a KeyError if the key doesn't exist in the dictionary/collection如果字典/集合中不存在该键,则使用方括号语法查找键将引发KeyError

if not request.session['order1']:

Should be应该

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

Using try/except KeyError would also work...使用 try/except KeyError 也可以...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM