Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery autocomplete plugin using a Django database/model

Does anybody know how to implement the jQuery autocomplete plugin in Django, using databases instead of local values?

Specifically I want to implement the "Search Page Replacement" feature mentioned at bottom of the page, the dataset will be approx a thousand or more entries, but I cannot workout how to get it to interact with the necessary fields of my database.

(Am also on the lookout for a good Python/Django search solution to use for my site - which is just a very simple website.)


Thank you for your help.

like image 758
Jon Cox Avatar asked Feb 12 '11 21:02

Jon Cox


1 Answers

I rencently did something with jQuery.autocomplete with one model.

funcionality of seach city when user starts to write the name:

according the jqueryui docs to make work the autocomplete you need an input like this:

<input id="n" type="text" name="n"/>

so, the javascript in my template to attach the lib to this input looks like:

$(document).ready(function(){
     $( "input#n" ).autocomplete({
                            source: "{% url autocomplete_city %}",
                            minLength: 2
        });
});

to resolve that URL you have to write something like this in your urls.py

urlpatterns = patterns('cities.views',
    url(r'^autocomplete_city/$', 'autocomplete_city', name='autocomplete_city'),
)

that mean that I have something like cities.views.autocomplete_city view:

def autocomplete_city(request):
    term = request.GET.get('term') #jquery-ui.autocomplete parameter
    cities = City.objects.filter(name__istartswith=term) #lookup for a city
    res = []
    for c in cities:
         #make dict with the metadatas that jquery-ui.autocomple needs (the documentation is your friend)
         dict = {'id':c.id, 'label':c.__unicode__(), 'value':c.__unicode__()}
         res.append(dict)
    return HttpResponse(simplejson.dumps(res))

what else de you need? start testing and remember DOCUMENTATIONS ARE YOUR FRIEND please TRY to make the things for yourself first, google it, read the docs, try 3 times, if cant, stackoverflow is your friend.

like image 74
panchicore Avatar answered Nov 02 '22 12:11

panchicore