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

Django项目搜索栏问题:调用API按产品编码搜索后无法显示结果

问题分析与解决方案

核心问题1:模板遍历单个对象导致无输出

你的视图中selected_product是单个产品对象(不是列表),但模板里用了{% for search in product %}循环遍历,单个对象无法被循环迭代,所以页面不会显示任何内容。

核心问题2:未处理搜索无结果的情况

如果没有匹配的产品,selected_product为None,此时product变量未定义,会直接抛出NameError,导致页面报错。

核心问题3:URL中多余的action=参数(不影响功能,但可优化)

表单里没有name="action"的输入,但URL出现该参数,是因为你的按钮里嵌套了<i>标签,部分浏览器会把按钮内的额外元素解析为表单数据,给按钮添加name属性即可规避。


修复后的Views.py代码

def search(request):
    code = request.GET.get('search', '')  # 给默认值避免None
    product = None
    all_products = []
    
    if code:  # 只有当搜索关键词存在时才调用API
        url = 'http://myAPI/Product/GetProducts'
        try:
            x = requests.post(url)
            x.raise_for_status()  # 捕获API请求异常
            content = x.json()
            all_products = content.get('products', [])
            selected_product = next((item for item in all_products if item['code'] == code), None)
            if selected_product:
                product = selected_product
        except requests.exceptions.RequestException as e:
            # 可添加日志记录异常,这里简化处理
            pass

    # 把单个对象包装成列表,方便模板统一遍历
    context = {'products': [product] if product else []}
    return render(request, 'cart/search.html', context)

修复后的search.html代码

<h3>Results:</h3>

{% if products %}
  {% for item in products %}
    <p>{{ item.code }}</p>
    <p>{{ item.designation }}</p>
  {% endfor %}
{% else %}
  <p>未找到匹配的产品</p>
{% endif %}

修复后的表单代码(解决URL多余action参数)

<form method="GET" action="/cart/search/">
    <input type="search" name="search" placeholder="示例产品编码">
    <button class="btn waves-effect waves-light" type="submit" name="submit">Search
        <i class="material-icons right">search</i>
    </button>
</form>

额外优化建议

  • API请求改为缓存:每次搜索都调用API会影响性能,可把产品数据缓存到Django的缓存系统(如Redis),定期更新。
  • 编码匹配改为大小写不敏感:如果API返回的编码是大小写混合,可改成item['code'].lower() == code.lower()增强兼容性。
  • 表单action使用Django的url模板标签:避免硬编码路径,比如action="{% url 'cart:search' %}"(需先在urls.py中命名URL)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 05:10:36