基本的Django搜索实现

时间:2018-05-31 18:16:01

标签: python html django

我在从表单中检索用户提交的数据时遇到了一些困难。我能够硬编码'term'并成功搜索数据库,但是使用我现在拥有的当前代码,我会在动态填充结果时收到MultiValueDictKeyError。所以,我想知道我应该用什么方法处理这一行:“term = request.GET ['term']”。

views.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)

urls.py

urlpatterns = [
path('', views.table_content, name='table_content'),
path('search_form', views.search_bar, name='search_bar')]

search.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>

1 个答案:

答案 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)