借助Ajax在Django中进行实时搜索

时间:2019-02-26 21:15:38

标签: ajax django

我有一个与此类似的问题:How do I jQuery ajax live search for the models in Django?。 我想在Ajax的帮助下在Django中创建实时搜索,但是由于某些原因,它不起作用。 在我的项目中,我有以下信息。 在文件 locallibrary \ catalog \ urls.py

urlpatterns += [
    url(r'^search-user/$', views.SearchUser, name='search_user'),
    url(r'^search_status/$', views.search_status, name='search_status'),
]

在文件 locallibrary \ catalog \ views.py

def search_status(request):
    if request.method == "GET":
        search_text = request.GET.get('search_text', None)
    else:
        search_text = ''

    statuss = Trip.objects.filter(town__icontain=search_text)

    return render(request, 'search_user.html', {'statuss':statuss})

在文件 locallibrary \ catalog \ static \ js \ ajax.js

$(function () {

    $('#search').keyup(function () {

        $.ajax({
            type: "GET",
            url: "/catalog/search_status/",
            data: {
                'search_text': $('#search').val(),
                'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
            },
            success: searchSuccess,
            dataType: 'html'
        });

    });

});

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

在文件 locallibrary \ catalog \ templates \ catalog \ search_user.html

<!DOCTYPE html>
<html>
<head>
    <title>Простой живой поиск</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>


</head>

<body>

    <h3>Search</h3>
    {% csrf_token %}
    <input type="text" id="search" name="search" />

    <ul id="search-results">

    </ul>
{% if statuss.count > 0 %}

{% for status in statuss %}
    <li><a ">{{ status.town }}</a></li>
{% endfor %}

{% else %}

<li>None to show!</li>

{% endif %}

    {% load staticfiles %}
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
    <script src="{% static 'js/ajax.js' %}"></script>

</body>
</html>

当我尝试打印某些东西时发生错误:

FieldError at /catalog/search_status/
Unsupported lookup 'icontain' for CharField or join on the field not permitted.
Request Method: GET
Request URL:    http://127.0.0.1:8000/catalog/search_status/
Django Version: 2.1
Exception Type: FieldError
Exception Value:    
Unsupported lookup 'icontain' for CharField or join on the field not permitted.
Exception Location: C:\...\PycharmProjects\locallibrary\venv\lib\site-packages\django\db\models\sql\query.py in try_transform, line 1126
Python Executable:  C:\...\PycharmProjects\locallibrary\venv\Scripts\python.exe
Python Version: 3.7.0

请找到屏幕截图。该错误的原因可能是什么?

enter image description here

0 个答案:

没有答案