How do I jQuery ajax live search for the models in Django?

风流意气都作罢 提交于 2019-12-03 08:04:06

I had to indent the else statement and the return statement in the views.py. And also to put statuss in the second if statement. And then it worked as I expected! Please guide me if there's any improvements to make. Thank you!

views.py:

def search_status(request):

    if request.method == "GET":
        search_text = request.GET['search_text']
        if search_text is not None and search_text != u"":
            search_text = request.GET['search_text']
            statuss = Status.objects.filter(status__contains = search_text)
        else:
            statuss = []

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

This was the ajax script:

$(function() {

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

        $.ajax({
            type: "GET",
            url: "/status/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)
}

Snippet of index.html:

    <input type="text" id="search" name="search" />
    <ul id="search-results">
    </ul>

The included html:

{% if statuss > 0 %}
    <ul class="statuss">
        {% for status in statuss %}
            <li>
                <p>{{status}}</p>
            </li>
        {% endfor %}    
    </ul>
{% else %}
    <p>No status found.</p>
{% endif %}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!