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

Django Rest Framework:Django实现下拉选单提交调用外部API取数问题

Django 调用外部API获取产品信息实现方案

1. 依赖安装

首先安装HTTP请求库requests:
pip install requests

2. 表单类定义

在应用下的forms.py中创建表单类,匹配你需要的字段:

from django import forms

PRODUCT_CHOICES = [
    ('perfume', 'perfume'),
    ('bodyspray', 'bodyspray'),
    ('scents', 'scents'),
]

class ProductQueryForm(forms.Form):
    product = forms.ChoiceField(choices=PRODUCT_CHOICES, label="Product")
    expiry = forms.DateField(label="Expiry", widget=forms.DateInput(attrs={'type': 'date'}))

3. 配置API地址

在项目settings.py中添加外部API配置,方便后续统一修改:

EXTERNAL_PRODUCT_API_URL = "替换为你的实际API地址"

4. 视图层逻辑编写

在应用下的views.py中编写请求处理逻辑,包含表单渲染、API调用、结果返回三个部分:

import requests
from django.conf import settings
from django.shortcuts import render
from .forms import ProductQueryForm

def query_product(request):
    result = None
    error = None
    if request.method == "POST":
        form = ProductQueryForm(request.POST)
        if form.is_valid():
            # 提取选中的产品值
            product = form.cleaned_data["product"]
            payload = {"product": product}
            try:
                # 调用外部API,设置10秒超时避免服务卡死
                response = requests.post(
                    settings.EXTERNAL_PRODUCT_API_URL,
                    json=payload,
                    timeout=10
                )
                # 校验请求状态
                response.raise_for_status()
                # 解析返回的JSON数据
                result = response.json()
            except requests.exceptions.RequestException as e:
                error = f"API调用失败:{str(e)}"
    else:
        form = ProductQueryForm()
    return render(request, "product_query.html", {"form": form, "result": result, "error": error})

5. 模板页面编写

在templates目录下新建product_query.html,实现表单展示、错误提示、结果渲染:

<!DOCTYPE html>
<html>
<head>
    <title>产品查询</title>
</head>
<body>
    <h1>产品信息查询</h1>
    {% if error %}
    <p style="color: red;">{{ error }}</p>
    {% endif %}
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">提交查询</button>
    </form>
    {% if result %}
    <h2>查询结果</h2>
    <div>
        <!-- 可根据API实际返回的字段调整展示逻辑 -->
        {{ result }}
    </div>
    {% endif %}
</body>
</html>

6. 路由配置

在应用的urls.py中添加访问路由:

from django.urls import path
from . import views

urlpatterns = [
    path('query-product/', views.query_product, name='query_product'),
]

注意事项

  • 如果外部API需要鉴权,可在requests.post方法中添加headers参数传入鉴权信息,例如携带Token的写法为headers={"Authorization": "Bearer 实际Token值"}
  • 若业务需要将Expiry字段也传入API,直接在payload中添加对应键值对即可
  • 生产环境建议对API返回结果做格式校验,避免异常数据导致页面渲染错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 20:27:04