I am trying to implement an autocomplete functionality in django application. My view is as following
@require_POST
@login_required
def search_players(request):
search_query = request.POST.get('search_query')
team_ids = request.POST.getlist('team_ids[]')
players = PlayerData.player.filter(name__icontains=search_query, current_team_id__in=team_ids)
results = [{'id': player.id, 'name': player.name} for player in players]
return JsonResponse({'results': results})
it is returning results in following format
{'results': [{'id': 317144, 'name': 'Sharne Mayers'}]}
Below is the autocomplete code that I have implemented
$('#player-search').autocomplete({
source: function(request, response) {
$.ajax({
url: 'search-players/',
method: 'POST',
headers: {"X-CSRFToken": csrftoken},
data: {
'search_query': request.term,
'team_ids[]': [$("#team-one-info").data("team-id"),$("#team-two-info").data("team-id")] // Replace with your list of team IDs
},
dataType: 'json',
success: function(data) {
console.log(data.results)
response(data.results);
}
});
},
minLength: 3, // Minimum number of characters to trigger search
select: function(event, ui) {
// Add selected player to the list of selected players
var selectedPlayers = $('#selected-players');
var selectedPlayersIds = $('#selected-players-ids');
var playerPill = $('<span class="badge badge-pill badge-primary ml-1"></span>');
playerPill.text(ui.item.name);
playerPill.data('player-id', ui.item.id);
selectedPlayers.append(playerPill);
// Update the hidden field with the list of selected player IDs
var playerIds = selectedPlayersIds.val().split(',');
playerIds.push(ui.item.id);
selectedPlayersIds.val(playerIds.join(','));
// Clear the search field
$(this).val('');
return false;
}
});
I am getting the proper results back. I have checked using console.log

But I am not able to see the results properly in the autocomplete dropdown. All is see is this
I have ensured the the following css files are indeed loaded
<link rel="stylesheet" href="/static/css/jquery-ui.min.css">
<link rel="stylesheet" href="/static/css/jquery-ui.structure.min.css">
<link rel="stylesheet" href="/static/css/jquery-ui.theme.min.css">
I have also tried different variations of success method such as
success:response
or using a map function but nothing seems to work. What am I missing? Please help
'name'to'value'in your backend code when generating json and try again ?