Django JQuery Autocomplete for two forms on one page
Found this autocomplete code on the web, but it works for one form on the page. How to make it work for two forms with different data for each one?
views.py
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
from core.models import Product
def autocomplete(request):
if 'term' in request.GET:
qs = Product.objects.filter(title__icontains=request.GET.get('term'))
titles = list()
for product in qs:
titles.append(product.title)
return JsonResponse(titles, safe=False)
return render(request, 'core/home.html')
models.py
class Product(models.Model):
title = models.CharField(max_length=124)
qty = models.IntegerField()
def __str__(self):
return self.title
home.html
<form>
<label for="product">Product</label>
<input type="text" name="product" id="product">
</form>
<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>
urls.py
urlpatterns = [
path('', views.autocomplete, name='autocomplete'),
]