typehead.js to get the refreshed list of data from the database in python django

27 views Asked by At

file.js


  var source = new Bloodhound({
    hint: false,
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("description"),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    // /a_c/p_s/?term=d&category=all
    remote: "/a_c/p_s/" + "?term=mobile&category=store",
  });

  source.initialize();

  $("#search-bar").typeahead(null, {
    name: "suggestion",
    displayKey: "search_text",
    source: source.ttAdapter(),
  });
});

urls.py

path('a_c/p_s/<term>/<category>', views.product_search,name='product_search'),

views.py

def product_search(request, term, category):
    pass

I have a category dropdown and an input field for search text. I have to get the suggestion list from the database based on the changed value of the category dropdown and input the search text value I'm using typeahead. I don't know whether I'm doing it right or not with typehead bloodhound. Please if anyone could help me with that.

I'm getting an error of URL not found in the console.

1

There are 1 answers

0
sandeepsinghnegi On

file.js

var source = new Bloodhound({
    hint: false,
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("description"),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    // /a_c/p_s/?term=d&category=all
    remote:
      "/a_c/p_s/?term=" +
      $("#search-bar").val() +
      "&category=" +
      $(".serach_category").val(),
  });

  source.initialize();

  $("#search-bar").typeahead(null, {
    name: "suggestion",
    displayKey: "search_text",
    source: source.ttAdapter(),
  });

urls.py

path('a_c/p_s/', views.product_search,name='product_search'),

views.py

def product_search(request):
    """
        autocomplete feature
    """
    try:
        search_key = request.GET.get('term', '').lower().split(" ")
        print("search_key", search_key)
        request.session["serach_category"] = request.GET.get('category', '').title()

    except Exception as e:

this is what i'm doing now. but still can't say whether it is the correct way of doing it or not. feel free to suggest if i'm doing something wrong in it.