简体   繁体   中英

How to autocomplete a search form?

I have a search form and it works fine. Now I would like my search form autocomplete.I tried using django autocomplete light but I have a problem implementing it.

Is it possible to use my existing code, add JavaScript and make it work? I tried to do it myself but I came to a wall.

I would really appreciate if someone could help me with this, give me a hint or a link for a working demo or tutorial.

This is my current code. Thanks for your time.

views.py

def search(request):
    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        search_list = Book.objects.filter(
    Q(title__icontains=q) | Q(description__icontains=q))
        return render_to_response('books/search_results.html', {'search_list': search_list, 'query': q}, context_instance=RequestContext(request))
    else:
        return render_to_response('books/please_submit.html', {}, context_instance=RequestContext(request))

urls.py

urlpatterns = patterns('', 
    url(r'^search/$','papers.views.search', name='search'),
)

search.html

    <form method='get' action='/search/'>
        <input type='text' name='q'  class="btn btn-theme btn-sm btn-min-block biggerForm"> 
        <input type='submit' value='Search'  class="btn btn-theme btn-sm btn-min-block">
    </form>

Django-autocomplete-light is tricky to set up and in my opinion its easier using other autocompletes.

Here is how I got it working using bootstrap 2. (There is a bootstrap 3 compatible library as well, and the configuration is more or less the same https://github.com/bassjobsen/Bootstrap-3-Typeahead ).

You need a few things to work together.

1: Create a view that will process the autocomplete request and return suggestions. so in views.py

def book_autocomplete(request, **kwargs):
    term = request.GET.__getitem__('query')
    books = [str(book) for book in    book.objects.filter(Q(title__icontains=q) | Q(description__icontains=q))] 
    return  HttpResponse(json.dumps(books))     

And in urls.py add an entry:

url(r'^autocomplete/book_autocomplete/' , booking.ebsadmin.book_autocomplete , name='book_autocomplete'),

2: Load the bootstrap typeahead/autocomplete code into your page. The project I inherited was already using bootstrap 2, so this code was already there. So in your template in the head section (this will probably differ depending on the the directory structure of your static files):

<script type="text/javascript"  src="{{ STATIC_URL }}bootstrap/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}bootstrap/css/bootstrap.min.css" />

3: Connect the bootstrap typeahead/autcomplete to your view. I created a file book_autocomplete.js, and added it to my static files folder. This tells it to attach the autocomplete to the element with id book-search (you will have to give the search box on your form and id equivalent to the '#book-search' that I have used here. An example on how to do this in your form definition https://stackoverflow.com/a/5827671/686016 ):

book_search_typeahead.js

$(document).ready(function() {
    $('#book-search').typeahead({source: function (query, process) {
        return $.getJSON(
            '/autocomplete/book_autocomplete/', // this is the url for the view we created in step 1
             { query : query },
             function (data) {
                console.log(data) ; 
                return process(data);
             });
        }});    
 });

back to your template and add this line to load the javascript that we just created:

  <script type='text/javascript' src='{{ STATIC_URL }}book_search_typeahead.js' ></script>

I think that is everything.

@wobbily_col answer works obviously but generally you want to avoid hitting a relational database to create autocomplete results. I have made an autocomplete library that works fast and is easy to use. But all it does is to give you text results back. It is up to you to feed it data and make its responses in your API. Checkout: https://github.com/wearefair/fast-autocomplete And here is an explanation of how it works: http://zepworks.com/posts/you-autocomplete-me/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM