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

基于Django的电商网站搜索功能无结果问题求助

问题诊断与修复方案

核心问题:上下文变量名不匹配

你的views.py中把查询到的产品列表以product为键传给模板,但模板里循环的是products,变量名不一致导致模板无法读取产品数据。

修复views.py

将上下文里的'product': products改为'products': products:

def search(request):
    if 'searched' in request.GET:
        searched = request.GET['searched']
        products = Product.objects.filter(title__icontains=searched)
        # 修正键名,与模板变量名保持一致
        return render(request, 'epharmacyweb/search.html', {'searched': searched, 'products': products})

次要问题:搜索参数的空格转义

URL中searched=throat-spray的横杠,与数据库中产品标题的空格不匹配,导致icontains无法命中。可在处理关键词时将横杠替换为空格:

def search(request):
    if 'searched' in request.GET:
        searched = request.GET['searched']
        # 替换横杠为空格,适配URL参数格式
        searched = searched.replace('-', ' ')
        products = Product.objects.filter(title__icontains=searched)
        return render(request, 'epharmacyweb/search.html', {'searched': searched, 'products': products})

额外优化:show-product的URL参数问题

你的urls.py中show-product路径未定义参数,但模板传递了product.title,会导致URL生成错误。修改urls.py:

path('search/', views.search, name='search'),
path('search-error/', views.search_error, name='search_error'),
# 添加标题参数,接收字符串类型
path('show-product/<str:title>/', views.show_product, name='show-product'),

同时确保show_product视图正确接收参数:

def show_product(request, title):
    product = Product.objects.get(title=title)
    return render(request, 'epharmacyweb/show_product.html', {'product': product})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:55:17