jquery - templateResult 和 templateSelection 的 Select2 参数不同 (django)

标签 jquery python django jquery-select2

我遇到了一个奇怪的问题。我的 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、名称和单位字段。这是我用来创建 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 和文本字段。

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

提前致谢!

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

最佳答案

好的,我有一个答案。在 initProductSelect2() 的上下文中,我创建了一个 options 对象,该对象填充在 ProcessResults 中,然后在触发选择事件时从那里检索我的选项。我还更改了 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');
    }

关于jquery - templateResult 和 templateSelection 的 Select2 参数不同 (django),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43858602/

相关文章:

javascript - 如何格式化txt文件并导入jquery以在变量内使用

javascript - 创建部分 View 以在索引页面中创建新内容

python - 为什么 __init__() 总是在 __new__() 之后调用?

javascript - 容器的内容忽略移动 View 中的导航栏和主横幅

javascript - 如何在 jQuery ajax 调用中使用数组字符串?

javascript - 使用 Javascript/jQuery 的同步 GET 请求

python - 这两个文件的类型有什么区别?

python - Python 解释器嵌入段错误的最小示例

django-allauth 社交帐户 "full"注销?

python - Django “TypeError: list() got an unexpected keyword argument ' ID ''” 错误