我在从表单中检索用户提交的数据时遇到了一些困难。我能够硬编码'term'并成功搜索数据库,但是使用我现在拥有的当前代码,我会在动态填充结果时收到MultiValueDictKeyError。所以,我想知道我应该用什么方法处理这一行:“term = request.GET ['term']”。
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)
urlpatterns = [
path('', views.table_content, name='table_content'),
path('search_form', views.search_bar, name='search_bar')]
<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>
答案 0 :(得分:0)
在处理提交空查询的默认情况后,我能够解决我的问题。以下是更正后的代码。
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)