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

Django搜索框空提交引发UnboundLocalError问题求助

解决Django搜索功能的UnboundLocalError问题

当用户未输入任何内容提交搜索表单时,触发UnboundLocalError,错误提示为:local variable 'profiles' referenced before assignment。

相关代码

views.py

def paitent(request):
    
    search_query = ''
    
    if request.GET.get('search_query'):
        
        search_query = request.GET.get('search_query')
        if search_query == ' ':
            print('Ex')

        else:
            userprofile = Profile.objects.filter(id=search_query)
            profiles =  Totallcount.objects.filter(image_owner=search_query)
            

    context = {
       'profiles':profiles,
       'userprofile':userprofile,
     
    }
    return render(request, "medical_report/paitent.html",context)

paitent.html

<form class="d-flex ms-auto my-3 my-lg-0" id='searchForm' action="{% url 'paitent' %}" method="get">
  <div class="input-group">

    <input
      class="form-control"
      type="search"
      placeholder="Search by Name"
      aria-label="Search"
      id="formInput#search" type="text" name="search_query" value="" />
    <button class="btn btn-primary" type="submit" value="Search">
      <i class="bi bi-search"></i>
    </button>
    
  </div>
</form>

错误详情

UnboundLocalError at /paitent/
local variable 'profiles' referenced before assignment
Request Method: GET
Request URL:    http://127.0.0.1:8000/paitent/?search_query=
Django Version: 3.2.15
Exception Type: UnboundLocalError
Exception Value:    
local variable 'profiles' referenced before assignment
Exception Location: C:\Users\21100002\Desktop\myreports\medical_report\views.py, line 176, in paitent
Python Executable:  C:\Users\21100002\Desktop\ocr\env\Scripts\python.exe
Python Version: 3.7.0

问题原因与修复方案

问题根源

  1. 当用户提交空搜索时,request.GET.get('search_query')返回空字符串'',if ''判断为False,代码不会进入if块,导致profiles和userprofile从未被赋值。
  2. 即使进入if块,若搜索内容是单个空格' ',也只会执行print('Ex'),同样不会给两个变量赋值,最终在构建context时触发未定义错误。

修复代码

在函数开头初始化变量为空白QuerySet,确保无论是否执行搜索逻辑,变量都有合法值:

def paitent(request):
    # 初始化空QuerySet,避免未赋值报错
    profiles = Totallcount.objects.none()
    userprofile = Profile.objects.none()
    search_query = ''
    
    # 获取搜索参数,默认空字符串并去除首尾空白
    search_query = request.GET.get('search_query', '').strip()
    
    # 仅当搜索关键词非空时执行查询
    if search_query:
        userprofile = Profile.objects.filter(id=search_query)
        profiles = Totallcount.objects.filter(image_owner=search_query)
            
    context = {
       'profiles': profiles,
       'userprofile': userprofile,
    }
    return render(request, "medical_report/paitent.html", context)

优化说明

  • 使用request.GET.get('search_query', '')避免KeyError,同时设置默认值为空字符串。
  • 调用strip()去除关键词首尾空白,统一处理用户输入空格的情况。
  • 初始化变量为objects.none(),返回空QuerySet,模板中遍历这些变量时不会报错,保持逻辑一致性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 04:00:36