开发者

jQuery autocomplete plugin using a Django database/model

开发者 https://www.devze.com 2023-02-10 16:53 出处:网络
Does anybody know how to implement the jQuery autocomplete plugin in Django, using databases instead of local values?

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 go开发者_C百科od Python/Django search solution to use for my site - which is just a very simple website.)

Thank you for your help.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号