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

搜索栏报错UnboundLocalError:变量'product'未赋值引用

解决UnboundLocalError:local variable 'product' referenced before assignment

错误原因

当未找到匹配产品时,代码的else分支仅添加了错误消息,但未对product变量进行赋值。而函数最后直接引用product构建上下文context,此时该变量未被定义,因此触发UnboundLocalError。

解决方案

  1. 确保product变量在所有分支中都被初始化,避免未定义就引用
  2. 模板中增加判断逻辑,防止article为None时访问属性报错

修改后的代码

Views.py

@login_required
def search(request):
    code = request.GET.get('search')
    url = 'http://myAPI/Product/GetProduct'
    x = requests.post(url)
    contenu = x.json()
    all_products = contenu['products']
    # 直接将查询结果赋值给product,找不到则为None
    product = next((item for item in all_products if item['code'] == code), None)
    if product is None:
        messages.error(request, 'Article not found.')

    context = {'article': product}
    return render(request, 'panier/search.html', context)

search.html

{% if messages %}
    {% for message in messages %}
        <p {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</p>
    {% endfor %}
{% endif %}

<!-- 仅当article存在时,才渲染产品信息 -->
{% if article %}
    {{ article.code }}
    {{ article.name }}
{% endif %}

内容的提问来源于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 07:26:07