Reputation: 590
I've added a select2 field to my webpage and I want to load the records into it using ajax. So I've declared a url field.
$(document).ready(function() {
$("#field_id").select2({
placeholder: "Search...",
ajax: {
url: '{{ url }}',
dataType: 'json',
...
templateResult: formatItem,
This url points to a method, that should return the matching products, but I don't have any idea how to serialize them so that it works. This is my method:
def get_ajax(self, request, *args, **kwargs):
query = request.GET.get('q', None)
if query:
products = Product.objects.filter(name__icontains=query)
return JsonResponse(products, safe=False)
else:
return JsonResponse(data={'success': False,
'errors': 'No mathing items found'})
But I get only undefined values. My JS formatItem() method looks like this:
function formatItem (item) {
console.log(item);
if (item.loading) return item.name || item.text;
var markup = '<div class="clearfix">' +
'<div class="col-sm-12">' + item.name +
'</div>' +
'</div>';
return markup;
}
What am I doing wrong? Thanks in advance.
Upvotes: 3
Views: 1808
Reputation: 3636
you can use .values
to get the result as dict.
def get_ajax(self, request, *args, **kwargs):
query = request.GET.get('q', None)
if query:
products = Product.objects.filter(name__icontains=query).values("pk","name")
products = list(products)
return JsonResponse(products, safe=False)
else:
return JsonResponse(data={'success': False,
'errors': 'No mathing items found'})
in your js file
$(document).ready(function(){
$("#field_id").select2({
tags: true,
multiple: true,
// tokenSeparators: [',', ' '],
minimumInputLength: 2,
minimumResultsForSearch: 10,
ajax: {
url: '{% url 'product:suggest_product' %}',
dataType: "json",
type: "GET",
data: function (params) {
var queryParameters = {
q: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.product,
id: item.pk
}
})
};
}
}
});
});
Upvotes: 4