How to suggest similar words in autocomplete

后端 未结 2 1157
情书的邮戳
情书的邮戳 2021-01-03 12:03

I have an input field for locations with jquery-ui-autocomplete.



        
2条回答
  •  佛祖请我去吃肉
    2021-01-03 12:30

    After some additional research and many tries, I found a way to do it. This is specific for Django, so any other more generic proposal is of course more than welcome.

    The solution is based on this tutorial, although with some modifications.


    First of all, import jQuery and jQueryUI in the template:

    
    
    
    

    Afterwards, in the template itself, you need to assign an id to the input tag. Note that this id is how jquery will identify in which form to run the autocomplete.

    The javascript code is as follows:

    
    

    And urls.py file needs to be modified accordingly:

    # urls.py
    
    import yourapp.views
    
    urlpatterns = [
        ...,
        url(r'^api/get_city_names/', yourapp.views.get_city_names),
        ...,
    ]
    

    And finally create the django view. The name of the function has to be the same as the one written in urls.py and the one written in the source of the javascript.

    #views.py
    
    import json
    
    def get_city_names(request):
    
        #what was in the question an array is now a python list of dicts.
        #it can also be in some other file and just imported.
        all_city_names = [
        { good_name: 'Mallorca', input_name: 'Palma de Mallorca' },
        { good_name: 'Mallorca', input_name: 'Mallorca' },
        { good_name: 'Mallorca', input_name: 'Majorca' },
        # etc
        ]
    
        if request.is_ajax():
            q = request.GET.get('term', '')
    
            city_names = [c['good_name'] for c in all_city_names if q in c["input_name"]]
            city_names = set(city_names) #removing duplicates
    
            results = []
            for cn in city_names:
                cn_json = {'value': cn}
                results.append(cn_json)
            data = json.dumps(results)
        else:
            data = 'fail'
        mimetype = 'application/json'
        return HttpResponse(data, mimetype)
    

    And the autocomplete should work.

提交回复
热议问题