Django Views出现MultiValueDictKeyError无法返回无GET请求首页如何解决
报错修复方案
错误根源
MultiValueDictKeyError 报错是因为首次访问首页(无GET请求参数)时,代码直接用 request.GET['city'] 读取不存在的键,Django会直接抛出异常终止运行。
修复后的完整代码
修改你的views.py文件如下:
from django.shortcuts import render import requests def index(request): # 先判断是否存在非空的city GET参数 if 'city' in request.GET and request.GET['city'].strip(): # 携带用户输入请求API payload = {'q': request.GET['city'].strip(), 'appid': 'API-KEY'} response = requests.get('http://api.openweathermap.org/data/2.5/weather', params=payload) # 请求成功时解析返回数据 if response.status_code == 200: e = response.json() context = { 'city_name': e['name'], 'weather':e['weather'][0]['main'], 'description' : e['weather'][0]['description'], 'temp' : e['main']['temp'], 'pressure':e['main']['pressure'], 'humidity':e['main']['humidity'], 'visibility':e['visibility'], 'wind_speed':e['wind']['speed'], 'wind_deg':e['wind']['deg'] } return render(request, 'index.html', {'context': context}) # 所有异常/无参数场景都直接返回空首页 return render(request, 'index.html')
逻辑说明
修改后代码完全覆盖你需要的4种首页场景:
- 场景1(无GET请求的默认首页):无
city参数,直接返回带搜索栏的空首页 - 场景2(传入合法城市名且API返回正常):正常请求API返回带数据的页面
- 场景3(传入的城市名API无对应结果):请求返回非200状态码,返回空首页
- 场景4(输入为空点击提交):
city参数为空,直接返回空首页
内容的提问来源于stack exchange,提问作者IOIOIOIOIOIOI
相关产品推荐
相关产品推荐

