首页 > 解决方案 > 为什么我的 Active Search 设置在 Django 应用程序中不起作用?

问题描述

我尝试在我的应用程序中实现主动搜索,但似乎有什么地方出错了。这是我的看法。

def view_books(request):
    subjects = Subjects.objects.all()

    query = request.GET.get('q')
    if query:
        books = Books.objects.filter(Q(book_name__icontains=query) | Q(reg_no__icontains=query)))
    else:
        books = []
           
    return render(request, 'libman/all_books_view.html', 
        {'books': books,'subjects':subjects,})

模板在这里。

<div>SEARCH BOOK</div>

<div class="container">
    <form method="GET" action="{% url 'view_books' %}" id="formed">
      <input type="text" id="search" name="q" value="{{ request.GET.q }}" >
      <input type="submit" value="Search">
    </form>
<div>
{% if books %}
  <form method="post" action="{% url 'delete_books' %}">
    {% csrf_token %}
    
  <table class="layout container tablesorter" id="search-results">
    <thead>
      <th> Book Name</a></th>
      <th>Book Registration no.</th>
      
      <th><input type="checkbox" id="select-all"></th>
    </thead>
   
  {% for book in books %}
    <tr >
      <td> <a href="{% url 'get_book_details' book.pk %}" style="color:blue">{{ book.book_name }}</a></td>
      <td> {{ book.reg_no }}</td>
    
      <td name="marked_delete">
          <input type="checkbox" name="marked_delete" value="{{ book.pk }}">
      </td>
    </tr>
  {% endfor %}
</table>
  {% else %}
  
  {% endif %}
  <div class="container text-right">
    <button class="btn btn-dark" id="delete_all" hidden="hidden" onclick="return confirm('The selected items will be deleted. Are you sure about this?')">Delete Selected</button>
  </div>
  </form>

还有剧本

<script>
$(function() {
        $('#search').keyup(function() {
            $.ajax({
                type: "GET",
                url: "books/view/",
                data: {
                    'search-text' : $('#search').val(),
                    'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
                },
                success: searchSuccess,
                dataType: 'html'
            });
        });
    });

    function searchSuccess(data, textStatus, jqXHR)
    {
        $('#search-results').html(data)
    }


  </script>

我对 Ajax 很陌生,它的使用,所以我猜这就是我的代码不好的原因。任何能够帮助我的人都非常感谢。

标签: ajaxdjango-views

解决方案


推荐阅读