Django Autocomplete with jQuery UI | AJAX | Search | Filter from Database

Viewed 247

By using database categories. I am trying to make an input field to be autocomplete in postad form. I have written this code and while execuiting i am facing the issue. The error which i got i have pasted below. So i want to make my field to autocomplete

views.py

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

postad.html

<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({
            //console.log("some");
            source: '{% url 'autocomplete' %}',
            minLength: 2
        });
    });
</script>

html

<form class="valid_form" action="" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <div class="container5 postadd">
        <h1>Post Ad</h1>
        <p>
            <input type="text" placeholder="Title" name="title" maxlength="60">
        </p>
        <p><textarea type="text" placeholder="Write your description.." maxlength="600" name="description"> 
        </textarea></p>
        <input type="text" name="type" id="Categories" placeholder="Search for your categories">
        <p><input type="number" placeholder="Price" name="price" min="0.00" max="100000000000.00" 
step="0.01"/>
        <p class="select_p">
            <input name="state" placeholder="State" type="text">
            <input type="text" placeholder="Zip Code" name="zip">
        </p>
        <p><input type="file" class="myfile" name="image">
        <input type="file" class="myfile" name="image1"></p
        <p><input type="file" class="myfile" name="image2">
        <input type="file" class="myfile" name="image3"></p>
        <input type="submit" value="Submit">
    </div>
</form>

see below i attached a error what i getting in console error screenshot

1 Answers

Try this:

-go to https://jqueryui.com/autocomplete/

  • click on "view source"
  • you will find something like this:

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

select and paste before end of your file header.

  • Also, copy the 2 lines:

<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>

and paste before the end of the body.

Related