I am trying to implement typeahead.js for my application. I followed through with some of the following examples stackoverflow and Twitter typeahead official doc. I created a Django Rest API which works perfectly well, I have also been able to get the typeahead to pop up suggestions. After all these, I am faced with two difficulties that I have been unable to resolve on my own. The first is that instead of showing string results, the script is returning total object count
, while the second problem is that the pop-up suggestion is not selectable.
Is there a way to solve these issues?
main.js
//live search
$(document).ready(function(){
var searchResults = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('lead'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: '../auth/api/data/',
remote: {
url: "/auth/api/data/",
wildcard: '%QUERY',
}
});
$('.typeahead').typeahead(null,
{
name: 'leads-display',
display: 'lead',
source: searchResults,
templates: {
empty: [
'<div class="empty-message">',
'No user found',
'</div>'
].join('\n'),
suggestion: function(data){
return '<div class="live-search-results">'
+ '<strong>' + data + '</strong>'
+ '</div>';
}
}
}
);
});
I found a solution to my issue. The first thing I did was that I discarded my DRF API because I was faced with too many issues around it. So, instead of rest API, I created a
JSONview in myviews.pyas seen belowI also ensured that I serialised my FileField using
simplejsonbecause I want to show images in my search results.encoder.pyFinally, in my
.jsfile, I did the followingI hope this helps anyone that is faced or might face a similar issue.