Django页面头部搜索框自动补全功能失效求助
问题排查与修复方案
以下是导致自动补全功能失效的关键问题及对应修复:
1. 缺少jQuery核心库
jQuery UI依赖jQuery核心库,但代码中仅引入了jQuery UI,未加载jQuery本身,会导致$未定义, autocomplete无法初始化。
修复:在引入jQuery UI前添加jQuery核心库:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
2. 自动补全接口逻辑与URL问题
get_titles视图在无term参数时返回页面而非空JSON,不符合接口预期;- 未限制返回
Category='Sell'的藏品,与搜索逻辑不一致; - 未添加登录验证,可能导致未授权访问。
修复views.py:
@login_required(login_url="/login/") def get_titles(request): if 'term' in request.GET: qs = ComicInput.objects.filter(Title__icontains=request.GET.get('term'), Category='Sell') titles = list(qs.values_list('Title', flat=True).distinct()) # 去重避免重复结果 return JsonResponse(titles, safe=False) return JsonResponse([], safe=False) # 返回空数组而非页面
确认layout.html中的source路径:
source: "{% url 'get_titles' %}", // 确保Django正确解析URL,或直接使用"/layout/get_titles/"绝对路径
3. 错误的CSS链接导致资源加载异常
layout.html中有两个未闭合的<link rel="stylesheet">标签,会干扰后续资源加载,同时缺少jQuery UI的样式文件,导致自动补全菜单无样式。
修复layout.html的head部分:
{% load static %} <head> <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'app/content/bootstrap.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'app/content/site.css' %}" /> <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="{% static 'app/scripts/modernizr-2.6.2.js' %}"></script> </head>
4. 输入框占位符的不规范处理
当前用value和onFocus实现占位符效果,容易导致提交默认文本,不符合HTML标准。
修复搜索输入框:
<input type="search" id="search" name="search" pattern=".*\S.*" placeholder="按标题搜索藏品" required>
完成以上修复后,自动补全功能即可正常工作。
内容的提问来源于stack exchange,提问作者johnperc
相关产品推荐
相关产品推荐

