JQuery autocomplete plugin using Django database / model

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

In particular, I want to implement the "Page Search" function, indicated at the bottom of the page, the data set will contain about a thousand or more records, but I can’t train how to make it interact with the necessary fields of my database.

(I also observe a good Python / Django search solution for use on my site - it's just a very simple site.)


Thank you for your help.

+4
source share
1 answer

I did something with jQuery.autocomplete with one model.

Functionality of the city of dating, when the user begins to write the name:

according to jqueryui docs, to make autocomplete work, you need this input:

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

so the javascript in my template for attaching a library to this input is as follows:

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

to resolve this url you have to write something like this in urls.py

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

which means that I have something like city.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 you need? start testing and remember DOCUMENTS - YOUR FRIEND, ASK first to do things for yourself, google, read the documents, try 3 times, if can not, stackoverflow is your friend.

+11
source

Source: https://habr.com/ru/post/1339492/


All Articles