首页 > 解决方案 > 基本的 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>

标签: pythonhtmldjango

解决方案


在处理了提交空查询的默认情况后,我能够解决我的问题。以下是更正后的代码。

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)

推荐阅读