Home > Net >  Django and Jquery Autocomplete Issues
Django and Jquery Autocomplete Issues

Time:12-29

I know there are several posts regarding autocomplete and django, but I'm recently entering in to the realm of jquery and somehow I'm lost. As you can imagine, I need an autocomplete for the following field:

HTML file

<div >
     <input name="user_name"id="company-search">
</div>

  <script type="text/javascript">
            $(function() {
                $("#company-search").autocomplete({
                    source: '{% url 'autocomplete' %}',
                    minLength: 1,
                });
            });
    </script>

URL

path('autocomplete/',views.autocomplete, name='autocomplete')

Views

def autocomplete(request):
    data  = request.GET['term']
    forecast = LeadEntry.objects.select_related('lead_id')
    companies = [str(i.lead_id.company).lower() for i in forecast]
    search = [i for i in companies if i.startswith(data.lower()) ]

    result = []
    for company in search:
        data = {}
        data['label'] = company
        data['value'] = company
        result.append(data)
    print(json.dumps(result))
    mimeetype='application/json'
    return HttpResponse(json.dumps(result),mimeetype)

Please note that the ajax portion works well, I can see the view working every time, I type a new letter, I'm getting a json file with the correct data.

I can actually see the results, but the actual value is on the top right corner

enter image description here

I'm getting the following errors on the javascript side:

enter image description here

Regards

CodePudding user response:

The answer in the comments section seems to have solved the problem, to help others I write here:

Problem is with the jQuery UI version, use the CDN version 1.13.0 jQuery UI:

<script src = "https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"> </script>  

CodePudding user response:

From the jQuery docs the source property of autocomplete expects a list of keywords but you are passing it a django url.

You need to first hit your django url most probably with ajax GET call to get list of keywords and then put that list of keywords in the autocomplete source property.

  • Related