基于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
相关产品推荐
相关产品推荐

