5

I have tried to implement autocomplete exactly as this tutorial shows: https://www.youtube.com/watch?v=-oLVZp1NQVE

Here is the tutorial code, which is very similar to what I have here: https://github.com/akjasim/cb_dj_autocomplete

However, it is not working for me. The API url works, but nothing populates in the field, i.e. there is no autocomplete that shows up. What could I be doing wrong? I'm using yarn and yarn build and have collected static, but still does not work.

Here is the jquery:

 <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
        $(function () {
            $("#product").autocomplete({
                source: '{% url 'autocomplete' %}',
                minLength: 2
            });
        });
    </script>

Here is the html:

<title>Autocomplete</title>
</head>
<body>
<form>
    <label for="product">Product</label>
    <input type="text" name="product" id="product">
</form>

Here is the views:

def autocomplete(request):
    if 'term' in request.GET:
        qs = Model.objects.filter(title__icontains=request.GET.get('term'))
        titles = list()
        for product in qs:
            titles.append(product.title)
        # titles = [product.title for product in qs]
        return JsonResponse(titles, safe=False)
    return render(request, 'file_for_viewing.html')

Then here is the URL:

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

Even when source is a list, autocomplete not working:

source: '['chicago', 'new york',...,''] 

So the error is the request is getting canceled, because XMLHttpRequest cannot load XXX due to access control checks.

user10421193
  • 217
  • 2
  • 11
  • why don't you use JQuery's default autocomplete? It works like a charm and you're already loading the JQuery libraries. https://jqueryui.com/autocomplete/ – Sergio Jul 15 '21 at 08:05
  • could you post a screenshot of the browser inspect tool,in the network tab,about the ajax request – nay Jul 19 '21 at 07:58

1 Answers1

1

I tried your code and it is working fine with some corrections. I haven't faced any issues with the Access Control Headers.. If you haven't changed the code, the changes I made are.

  1. The Model is Product

    qs = Product.objects.filter(title__icontains=request.GET.get('term'))
    
  2. When testing with a list as source, source should be an array..

    source: ['chicago', 'new york',] 
    

If you are still facing issues with access control. setup django-cors-headers.

There are already a ton of answers there on stackoverflow about setting up django-cors-headers..

  1. Django-cors-headers

  2. How can I enable CORS on Django REST Framework

Dharman
  • 30,962
  • 25
  • 85
  • 135
All Іѕ Vаиітy
  • 24,861
  • 16
  • 87
  • 111