python - 基本的 Django 搜索实现
问题描述
我在从表单中检索用户提交的数据时遇到了一些困难。我能够对“术语”进行硬编码并成功搜索数据库,但是使用我现在拥有的当前代码,当动态填充结果时,我会收到 MultiValueDictKeyError。所以,我想知道我应该使用什么方法来处理该行:“term = request.GET['term']”。
视图.py
def search(self, request):
try:
r = requests.get(
self.URL + 'company/contacts?childConditions=communicationItems/value=' + request,
headers=self.Header)
r.raise_for_status()
except:
print(r.text)
raise
return r.json()
def search_bar(request):
term = request.GET['term']
results = objCW.search(term)
context = {'results': results}
return render(request, 'uccx/search.html', context)
网址.py
urlpatterns = [
path('', views.table_content, name='table_content'),
path('search_form', views.search_bar, name='search_bar')]
搜索.html
<html>
<head>
<meta charset="utf-8">
<title>SEARCH</title>
</head>
<body>
<form action="" method="get">
<input type="text" name="term">
<input type="submit" value='Search'>
</form>
{% if results %}
Found the following items:
<table class="table">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Company</th>
<th>E-Mail</th>
</tr>
</thead>
<tbody>
{% for result in results %}
<tr>
<td> {{ result.id }}</td>
<td>{{ result.lastName }}</td>
<td> {{ result.company.name }}</td>
<td> {{ result.communicationItems.0.value }}</td>
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
</body>
</html>
解决方案
在处理了提交空查询的默认情况后,我能够解决我的问题。以下是更正后的代码。
def search_bar(request):
term = request.GET.get('term')
if term:
results = objCW.search(term)
context = {'results': results}
return render(request, 'uccx/search.html', context)
else:
context = {'': ''}
return render(request, 'uccx/search.html', context)
推荐阅读
- r - which() 用于多个值
- android - 如何在真正的 android 设备上运行 React 本机应用程序
- date - 如何获取 yyyy-MM-dd'T'HH: mm: ss.SSSZ 格式的日期
- asp.net - 徽标图像未在 vb.net 中通过邮件发送
- javascript - 在 Javascript 中处理大型数组的最佳方法是什么?
- jasper-reports - JasperReports - 时间序列图表 y 轴上的状态名称
- reactjs - React.memo 应用到 js 箭头函数组件时显示错误
- javascript - 将字符串解析为JS中的对象
- python - Selenium 加载所有帖子然后提取帖子的问题
- r - 计算最佳复利期(加密货币)