[Django]-Django โ€“ implementation of select2 with url

4๐Ÿ‘

โœ…

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
                    }
                })
            };
        }
    }
});

});
๐Ÿ‘คThameem

Leave a comment