【问题标题】:Select2 parameter for templateResult and templateSelection different (django)模板结果和模板选择的Select2参数不同(django)
【发布时间】:2017-10-07 02:27:58
【问题描述】:

我遇到了一个奇怪的问题。我的 Web 应用程序中有一个产品选择元素项。因为数据库中有很多产品,所以我决定使用 select2 动态加载它们。问题是我想传递一个附加参数(单位),该参数将显示在选择框的对面。所以为了找到一个产品,我使用 Django 作为后端,我的方法看起来像这样。

class FindProductAjaxView(AjaxableResponseMixin, CreateView):
    model = Product
    form_class = ProductForm

    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", "unit")
            results = list(products)
            return JsonResponse(data={'items': results}, safe=False)
        else:
            return JsonResponse(data={'success': False,
                                      'errors': 'No mathing items found'})

所以它会正确返回 pk、name 和 unit 字段。这是我用来创建我的 select2 产品输入的脚本。

<script>
    function initProductSelect2 (select) {
        select.select2({
            placeholder: "Wyszukaj...",
            ajax: {
                url: '/recipes/find_product',
                dataType: 'json',
                delay: 250,
                language: 'pl',
                data: function (params) {
                  return {
                    q: params.term, // search term
                    page: params.page
                  };
                },
                processResults: function (data) {
                    data = data.items.map(function (item) {
                        return {
                            id: item.pk,
                            text: item.name,
                            name: item.name,
                            unit: item.unit
                        };
                    });
                    return { results: data };
                },
                cache: true
          },
          escapeMarkup: function (markup) { return markup; },
          minimumInputLength: 1,
          templateResult: formatItem,
          templateSelection: formatItemSelection
        });
        select.siblings('span').find('.select2-selection').addClass('form-control');
    }

    function formatItem (item) {
        console.log(item)
        if (item.loading) return item.name || item.text;
        var markup = '<div class="clearfix" data-unit=' + item.unit + '>' + item.name + '</div>';
        return markup;
    }

    function formatItemSelection (item) {
        console.log(item);
        return item.name || item.text;
    }
</script>

问题在于formatItemformatItemSelection 方法。传递给formatItem 的项目是可以的。它包含我需要的所有字段(pk、名称、单位)。但进入formatItemSelection 的项目只有 id 和 text 字段。

我已经为这个问题苦苦挣扎了几个小时,但我不知道。我尝试(如您在代码中看到的)将 unit 参数作为 jQuery 数据元素传递,但我不知道如何检索它。最好的解决方案是传递给formatItemSelection 的项目将具有从控制器传递的所有字段(pk、名称、单位)。

提前致谢!

编辑:我在最新版本 4.0.3 中使用 select2

【问题讨论】:

    标签: jquery python django jquery-select2


    【解决方案1】:

    好的,我有一个答案。在 initProductSelect2() 的上下文中,我创建了一个填充在 ProcessResults 中的 options 对象,然后在触发 select 事件时从那里检索我的选项。我还更改了 processResults 方法。这是我更新的代码,带有一个显示所选产品单位的警报。我像之前一样初始化了我的 select2,但使用了第二个参数,例如 initProductSelect2(select, []):

    function initProductSelect2 (select, options) {
            select.select2({
                placeholder: "Wyszukaj...",
                ajax: {
                    url: '/recipes/find_product',
                    dataType: 'json',
                    delay: 250,
                    language: 'pl',
                    data: function (params) {
                      return {
                        q: params.term, // search term
                        page: params.page
                      };
                    },
                    processResults: function (data, params) {
                        params.page = params.page || 1;
                        data.items.forEach(function (entry, index) {
                            entry.id = entry.pk;
                        });
                        options = data.items;
                        return {
                            results: data.items,
                            pagination: {
                                more: (params.page * 30) < data.total_count
                        }
                      };
                    },
                    cache: true
              },
              escapeMarkup: function (markup) { return markup; },
              minimumInputLength: 1,
              templateResult: formatItem,
              templateSelection: formatItemSelection
            });
            select.on("select2:select", function(e) {
                var id = $(this).val();
                var result = $.grep(options, function(e){ return e.id == id; });
                if (result.length != 0) {
                    alert(result[0].unit);
                }
            });
            select.siblings('span').find('.select2-selection').addClass('form-control');
        }
    

    【讨论】:

    • 在触发选择时我不得不做同样的事情,这让我很沮丧。在 on select 事件中没有理由不存在 params。
    猜你喜欢
    • 1970-01-01
    • 2021-12-27
    • 2013-11-15
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多