帮助!Python中的键错误

0 投票
1 回答
1135 浏览
提问于 2025-04-16 23:50

我一直收到这个错误:

MultiValueDictKeyError at /search/

"Key 'name' not found in <'QueryDict: {}>"

我刚开始学习编程,才两天,所以能不能用简单的语言解释一下为什么会有这个问题,以及怎么解决它。谢谢!

这是我编程的部分:

def NameAndOrCity(request):
    NoEntry = False
    if 'name' in request.GET and request.GET['name']:
        name = request.GET['name']
        if len(Business.objects.filter(name__icontains=name)) > 0:
            ByName = Business.objects.filter(name__icontains=name)
            q = set(ByName)
            del ByName
            ByName = q

    if 'city' in request.GET and request.GET['city']:
        city = request.GET['city']
        if len(Business.objects.filter(city__icontains=city)) > 0:
            ByCity = Business.objects.filter(city__contains=city)
            p = set(ByCity)
            del ByCity
            ByCity = p


    if len(q) > 0 and len(p) > 0:
            NameXCity = q & p
            return render_to_response('search_results.html', {'businesses':NameXCity, 'query':name})
        if len(q) > 0 and len(p) < 1:
            return render_to_response('search_results.html', {'businesses':ByName, 'query':name})
        if len(p) > 0 and len(q) < 1:
            return render_to_response('search_results.html', {'businesses':ByCity, 'query':city})
        else:
            NoResults = True
            return render_to_response('search_form.html', {'NoResults': NoResults})
    else:
        name = request.GET['name']
        city = request.GET['city']
        if len(name) < 1 and len(city) < 1:
            NoEntry = True
        return render_to_response('search_form.html', {'NoEntry': NoEntry})

编辑

1) Business.object 是我的商家数据库。它们是一些对象,包含像名称、城市等属性。我想写一个程序,可以根据这些属性来搜索商家。

2) 这不是重复的帖子。

3) 我该怎么检查这些键是否存在,才能在使用它们之前确认一下?

1 个回答

2

看起来你遇到这个错误的地方就是这一行:

name = request.GET['name']

在你尝试像上面那样访问 'name' 之前,你并没有检查一下 'name' 是否在 request.GET 这个字典里。所以如果这个键在 request.GET 中不存在,你就会得到一个键错误。

所以你需要修改下面的部分,先检查一下 'name' 和 'city' 这两个键是否在你的 request.GET 字典里,然后再去访问它们的值:

name = request.GET['name']
city = request.GET['city']
if len(name) < 1 and len(city) < 1:
    NoEntry = True
return render_to_response('search_form.html', {'NoEntry': NoEntry})

撰写回答