代码之家  ›  专栏  ›  技术社区  ›  t0bi

基本django搜索实现

  •  2
  • t0bi  · 技术社区  · 6 年前

    我在从表单中检索用户提交的数据时遇到了一些困难。我可以硬编码一个“term”并成功搜索数据库,但是使用现在的代码,当结果被动态填充时,我会收到一个多值dictkeyerror。所以,我想知道我应该用什么方法来处理这一行:“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>
    1 回复  |  直到 6 年前
        1
  •  0
  •   t0bi    6 年前

    在处理了提交空查询的默认案例之后,我能够解决我的问题。下面是正确的代码。

    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)