You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django调用航班查询API时strptime触发TypeError错误求助

问题根源
  • 视图未区分GET/POST请求:首次打开页面时是GET请求,request.POST为空,dep_date取到的值为None,直接传入strptime方法就触发了参数类型错误。
  • 日期转换格式不匹配:你当前用%d/%m/%Y转换得到的是「日/月/年」格式,和API要求的MM/DD/YYYY(月/日/年)不符,就算解决了空值问题,后续调用接口也会报错。
修复方案

修改views.py代码如下:

from django.shortcuts import render
import requests
import datetime as dt

def home(request):
    # 初始化返回数据
    context = {'response': ''}
    # 仅处理POST请求
    if request.method == 'POST':
        origin = request.POST.get('Origin')
        destination = request.POST.get('Destination')
        dep_date = request.POST.get('Departuredate')
        adults = request.POST.get('Adults')
        # 改strftime格式为%m/%d/%Y 匹配API要求的MM/DD/YYYY
        departure_date = dt.datetime.strptime(dep_date,'%Y-%m-%d').strftime('%m/%d/%Y')
        kwargs = {
                    'apikey':'UkyTNeGok4791FIGnTeFMD6UrooUWXoI',
                    'fly_from':origin,
                    'fly_to':destination,
                    'date_from':departure_date,
                    'date_to':departure_date,
                    'adults':adults
                }
        r = requests.get('https://tequila-api.kiwi.com/',params=kwargs).json()
        context['response'] = r
    return render(request,'searchmyflight/home.html', context)
修改说明
  • 新增请求方法判断,只有用户提交表单时才执行参数解析、接口调用逻辑,GET请求直接返回空白表单,避免空参数报错
  • 调整日期转换格式为%m/%d/%Y,完全匹配API要求的参数格式
  • 提前初始化上下文变量,避免无POST数据时模板渲染报错

内容的提问来源于stack exchange,提问作者logicpro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 16:24:07