Using Select2 autocomplete with Django project does not work while fetching the data

242 views
Skip to first unread message

Sajid Samsad

unread,
Dec 25, 2017, 9:51:46 AM12/25/17
to Django users

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?

Jason

unread,
Dec 25, 2017, 11:23:41 AM12/25/17
to Django users
Couple questions:

Do you see the request going from the browser to the server and back?  Not using postman, but your browser dev tools network tab

you have just a `/` at your ajax url.  Shouldn't this be `//` for protocol-agnostic?


Message has been deleted

Sajid Samsad

unread,
Dec 25, 2017, 8:28:37 PM12/25/17
to Django users
To @Jason
1) Yeah. I used the url from the browser and it worked. Actually the whole url is
localhost:8000//api.alif-marine.com/search/products?q=product_name
As
?q=whatever I type
is supposed to be added by javascript so when I am manually doing this from my browser, I am using the above url.

2) Well I used `//` but didn't work

Jason

unread,
Dec 26, 2017, 9:00:28 AM12/26/17
to Django users
That;s not quite what I mean 

See above, there's a XHR (ajax) request going to reddit and you can see the headers of the request/response as well as the data sent back.  What do you see of this when you call your search api?

Because it seems to me your request isn't being hit in the server from the client code

Sajid Samsad

unread,
Dec 26, 2017, 9:46:08 AM12/26/17
to Django users
Well when I write something in the search options, I got this error:

But I didn't write the js. It is from select2.
And if the request is not hit then what should I write?
The request for the API is localhost:8000/api.alife-marine/search/products
 

Jason

unread,
Dec 26, 2017, 12:26:58 PM12/26/17
to Django users
As you can see at https://select2.org/data-sources/ajax#jquery-ajax-options, ajax parameters are passed to a jquery method.  So do you have a <script> tag with jquery on that page?

Sajid Samsad

unread,
Dec 26, 2017, 12:55:36 PM12/26/17
to Django users
I actually didn't understand your question. 
 
I have posted the codes above. 
 
Could you kindly take a look if it's anything with the code?your question.

I actually didn't understand your question. I have posted the codes above. Could you kindly take a look if it's to anything with the codes?

Jason

unread,
Dec 26, 2017, 5:03:22 PM12/26/17
to Django users
looks like something you should go to the select2 github issue tracker for, since this is not a django issue.  

In the meantime, try using the unminified version of select2, would be a more relevant stack trace for you to look through the errors without the transformed names.

Sajid Samsad

unread,
Dec 26, 2017, 9:48:05 PM12/26/17
to Django users
Could you kindly suggest me some autocomplete library which I can use for my Django Project? My deadline is coming fast and furiously and I have already spent too much time on this autocomplete library `Select2`. 
Reply all
Reply to author
Forward
0 new messages