How do I jQuery ajax live search for the models in Django?
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 %}