Search code examples
jsondjangoajaxtypeahead.jsbloodhound

Supplying remote JSON data for Typeahead / Bloodhound with Django / Python


I'm trying to replicate functionality of this Typeahead remote example, but I can't figure out how to supply the data in the way Typeahead / Bloodhound wants it, nor what datumTokenizer or queryTokenizer are for.

In Python / Django views.py I've got:

nouns = ['apple', 'banana', 'pear']
return JsonResponse({'results': nouns})

reaching the site as:

{"results": ["apple", "banana", "pear"]}

Yet for 'kings' the example returns:

[{"year": "1949","value":"All the Kings Men","tokens":["All","the","Kings","Men"]}]

Need we return it in this format? If so, how? How can we make a simple replication of the example?


Solution

  • Figured it out: for practical use return HttpResponse(nouns), or return JsonResponse(nouns, safe=False).

    If concerned for security send it as a dict:

    noun_dicts = [{'suggestion':x} for x in nouns]
    return JsonResponse({'results':noun_dicts})
    

    And then parse the dict in JS.