In my Django project, I have a Search field. I used Select2 autocomplete with it. I needed to fetch the product_list from my Product model. So I created a rest API that returns the product in json formats.
Here is my rest API code:
serializer.py:
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = ProductList
fields = ('product_id', 'product_name', 'product_image', 'product_available',
'product_description')
views.py:
class JSONResponse(HttpResponse):
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
def list(request):
if request.method == 'GET':
products = ProductList.objects.filter(product_name__icontains=request.GET.get('q'))
serializer = ProductSerializer(products, many=True)
serializer_data = serializer.data
customData = {'results': serializer_data}
return JSONResponse(customData)
Now in my html, in the javascript portion I used this code mentioned in this Select2 doc. The code I used, looks like this:
base.html:
<script type="text/javascript">
$(document).ready(function() {
$('.js-data-example-ajax').select2({
ajax: {
url: "/api.alif-marine.com/search/products",
dataType: 'json',
delay: 250,
type: 'GET',
data: function (params) {
return{
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.results,
};
},
cache: true
},
placeholder: 'Search for a product',
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
function formatRepo (repo) {
if (repo.loading) {
return repo.text;
}
var markup = "<div class='select2-result-repository clearfix'>" +
{# "<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +#}
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>" + repo.product_name + "</div>";
if (repo.product_description) {
markup += "<div class='select2-result-repository__description'>" + repo.product_description + "</div>";
}
return markup;
}
function formatRepoSelection (repo) {
return repo.product_name || repo.text;
}
});
</script>
When I used Postman to check if the rest API works or not, it worked perfectly. For my query in the Postman like these:
localhost:8000/api.alif-marine.com/search/products?q=t
or
localhost:8000/api.alif-marine.com/search/products?q=tho
or
localhost:8000/api.alif-marine.com/search/products?q=thomas
The retrieved json data is given below for query localhost:8000/api.alif-marine.com/search/products?q=t :
{
"results":[
{
"product_id":9,
"product_name":"thomas",
"product_image":"/media/media/tom_dushtu.jpg",
"product_available":"available",
"product_description":"jah dushtu"
},
{
"product_id":8,
"product_name":"ami dissapointed",
"product_image":"/media/media/dissapointment.jpg",
"product_available":"available",
"product_description":"I ma kinda dissapointed, you know.................."
}
]
}
Now with all those, I couldn’t make it work. The autocomplete is not working. Nothing is shown when I press one key or write the name of the whole product.
Here is an image.
It always has shown Searching… I tried reading the issues on the Github repo and some other things but couldn’t solve it.
What am I doing wrong?