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

Django实现搜索无匹配结果时跳转error.html页面的问题

解决Django搜索无匹配时跳转error.html的问题

首先,你的代码存在逻辑漏洞:else块里不管是否找到部分匹配条目,都会直接返回search.html,最后那条返回错误页面的语句永远不会被执行。以下是修正后的代码:

error = {"message": "ERROR: This entry does not exist"}
entries = util.list_entries()

def search(request):
    searchquery = request.POST['q']
    content = md_to_html(searchquery)
    file = {"title": searchquery, "content": content}
    empty_list = []

    # 检查是否有完全匹配的条目
    if util.get_entry(searchquery):
        return render(request, "encyclopedia/entry.html", file)
    else:
        # 遍历查找部分匹配的条目
        for entry in entries:
            if searchquery.lower() in entry.lower():
                empty_list.append(entry)
        # 根据匹配结果分支处理
        if empty_list:
            did_you_mean = {"did_you_mean": empty_list}
            return render(request, "encyclopedia/search.html", did_you_mean)
        else:
            # 完全无匹配,返回自定义错误页面
            return render(request, "encyclopedia/error.html", error)

关键修改说明:

  • 把did_you_mean的定义移到循环外部,避免重复赋值的冗余操作
  • 在else块末尾增加判断逻辑:如果empty_list为空(完全无任何匹配),则返回error.html;否则返回带部分匹配结果的search.html
  • 移除了永远无法执行的冗余返回语句

如果希望和访问不存在路径时的效果完全一致,也可以使用Django内置的Http404异常,让系统自动调用你配置的404页面:

from django.http import Http404

def search(request):
    # 前面的逻辑保持不变
    else:
        for entry in entries:
            if searchquery.lower() in entry.lower():
                empty_list.append(entry)
        if empty_list:
            did_you_mean = {"did_you_mean": empty_list}
            return render(request, "encyclopedia/search.html", did_you_mean)
        else:
            raise Http404("ERROR: This entry does not exist")

(需确保你的模板目录中存在error.html,并在Django配置中正确关联404页面)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:10:42