基于Django实现用户搜索API结果渲染及选中值获取问题排查
COVID-19确诊数据查询功能修复方案
核心问题定位
- 下拉菜单
<option>未设置有效value属性,导致POST提交时无法传递选中的国家值 - 日期输入框缺少
name属性,后端无法接收起止日期参数 - 未实现基于用户选择参数调用目标API并渲染数据的逻辑
分步修复
1. 修复下拉菜单的value属性
修改home.html中的下拉选项代码,将value设置为国家名称,确保提交时能传递选中值:
<select name="selected_country"> {% for object in my_list %} <option value="{{object}}">{{object}}</option> {% endfor %} </select>
2. 为日期输入框添加name属性
给起止日期输入框补充name属性,让后端可以通过request.POST获取参数:
<input type="date" id="startdate" name="startdate"> <input type="date" id="enddate" name="enddate">
3. 后端实现API调用与数据传递
更新views.py,在POST请求分支中获取用户参数,格式化日期为API要求的ISO格式,调用目标API并将数据传给前端:
import requests from django.shortcuts import render def home(request): # 获取国家列表填充下拉菜单 summary_response = requests.get('https://api.covid19api.com/summary').json() country_list = [country['Country'] for country in summary_response['Countries']] confirmed_data = None selected_country = None if request.method == 'POST': # 获取用户提交的参数 selected_country = request.POST.get('selected_country') start_date = request.POST.get('startdate') end_date = request.POST.get('enddate') # 格式化为API要求的ISO时间格式 formatted_start = f"{start_date}T00:00:00Z" formatted_end = f"{end_date}T00:00:00Z" # 调用确诊数据API api_url = f"https://api.covid19api.com/country/{selected_country}/status/confirmed?from={formatted_start}&to={formatted_end}" try: confirmed_response = requests.get(api_url).json() # 提取需要的日期和确诊数,简化日期显示 confirmed_data = [{'date': item['Date'].split('T')[0], 'cases': item['Cases']} for item in confirmed_response] except Exception as e: print(f"API调用错误: {e}") return render(request, 'home.html', { 'my_list': country_list, 'confirmed_data': confirmed_data, 'selected_country': selected_country })
4. 前端添加数据展示区域
在home.html的表单下方添加数据渲染逻辑,用表格展示确诊数据:
<!-- 数据展示区域 --> {% if confirmed_data %} <div class="mt-4"> <h3>{{selected_country}} 确诊病例数据</h3> <table class="table table-striped"> <thead> <tr> <th>日期</th> <th>确诊病例数</th> </tr> </thead> <tbody> {% for item in confirmed_data %} <tr> <td>{{item.date}}</td> <td>{{item.cases}}</td> </tr> {% endfor %} </tbody> </table> </div> {% endif %}
功能说明
- 修复后,用户选择国家和日期点击搜索,后端会正确获取参数并调用目标API
- 前端会展示格式化后的日期(仅年月日)和对应确诊数
- 添加基础异常捕获,避免API调用失败导致页面崩溃
内容的提问来源于stack exchange,提问作者Batool Ragayah
相关产品推荐
相关产品推荐

