django - Ajax Live Search, What Am I Doing Wrong?

Viewed 1997

I'm trying to have a live search feature where as soon as you type something in a search box, the results automatically appear right below. I've been following this tutorial with no luck. Nothing seems to be happening when I type a query.

Could anybody tell me what I'm doing wrong?

urls.py

urlpatterns = [
    url(r'^$', views.list_of_post, name='list_of_post'),
    [...]
    url(r'^search/$', views.search_titles),
]

# this is my blog app views. Original view contains
# url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),

views.py

# Main view that displays all my posts

def list_of_post(request):
    post = Post.objects.filter(status='published')
    categories = Category.objects.all()

    template = 'blog/post/list_of_post.html'

    context = {
        'posts': posts,
        'categories': categories,

        [...]
    }
    return render(request, template, context)

# View that should return my results?

def search_titles(request):
    if request.method == 'POST':
        search_text = request.POST['search_text']
    else:
        search_text = ''

    classes = Post.objects.filter(title__contains=search_text)

    return render_to_response('blog/ajax_search.html', {'classes': classes})

template

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

ajax_search.html

{% if classes %}
        {% for class in classes %}
            <p>{{ class.title }}</p>
        {% endfor %}
{% else %}
    <p>No classes found.</p>
{% endif %}

and finally, ajax.js

$(function() {

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

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

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

all my files are loaded up properly, a quick console check confirms ajax.js & jquery being loaded with no errors. When I type anything in my search box, nothing appears below. I have followed the tutorial pretty consistently and I can't see where I might have gone wrong. If anybody could help, it would be appreciated!

2 Answers

The problem might have occurred in the URL pattern definition. By default, Django parses URLs from top to bottom. So you can change the pattern from

urlpatterns = [
url(r'^$', views.list_of_post, name='list_of_post'),
[...]
url(r'^search/$', views.search_titles),]

to the below one and try once again. Make sure that there are no URLs before the search that have other patterns and view functions that take arguments from URLs. The preferable position for search URL would be right after the first URL. Please also do cross check the ajax and jquery source file linking in the head section.

urlpatterns = [
url(r'^$', views.list_of_post, name='list_of_post'),
url(r'^search/$', views.search_titles),
[...]
]
Related