在获取数据时,使用带有Django项目的Select2自动完成功能不起作用

时间:2017-12-23 15:49:27

标签: ajax django django-rest-framework jquery-select2

在我的Django项目中,我有一个搜索字段。我用它来使用Select2自动完成功能。我需要从product_list模型中获取Product。因此,我创建了rest API,以json格式返回产品。

这是我的其余API代码:

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)

现在在我的html中,在javascript部分我使用了this Select2 doc中提到的代码。我使用的代码如下所示:

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>

当我使用Postman检查其余API是否有效时,它完美无缺。对于我在Postman中的查询,例如:

  

本地主机:8000 / api.alif-marine.com /搜索/产品Q =吨

     

     

本地主机:8000 / api.alif-marine.com /搜索/产品Q =寿

     

     

本地主机:8000 / api.alif-marine.com /搜索/产品Q =托马斯

下面给出了检索的json数据,用于查询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.................."
      }
   ]
}

现在有了这些,我无法使它发挥作用。自动完成功能无效。当我按一个键或写下整个产品的名称时,没有显示任何内容。

Here is an image。它始终显示Searching...。我尝试在Github repo和其他一些事情上阅读问题,但无法解决。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

这是处理select2库的方式:

views.py:

 class BurdenTypeAutocomplete(autocomplete.Select2QuerySetView):
     def get_result_label(self, obj):           
        return format_html(" {} / {}", obj.arabic_name,obj.englsh_name)
     def get_queryset(self):
        qs = BurdenTypeSales.objects.filter(effect_type="2")

        if self.q:
           qs = qs.filter(
               Q(arabic_name__icontains=self.q)
             | Q(account__number__icontains=self.q)
             | Q(englsh_name__icontains=self.q)
         )
        return qs[:10]

Url.py:

url(r'^burden_type_autocomplete/$',views.BurdenTypeAutocomplete.as_view(),name='burden_type_autocomplete'),

form.py:

burden_type_sales = forms.ModelChoiceField(queryset=BurdenTypeSales.objects.filter(effect_type='2'),
        widget=autocomplete.ModelSelect2(url='burden_type_autocomplete',attrs={'required':'required'}))