我有一個奇怪的問題。我的web應用程序中有一個產品選擇元素項目。因爲數據庫中有很多產品,我決定用select2動態加載它們。問題是我想傳遞一個額外的參數(單位),將顯示在選擇框對面。所以要找到一個產品,我使用Django作爲後端,我的方法看起來像這樣。select2參數爲templateResult和templateSelection不同(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>
問題在於該formatItem
和formatItemSelection
方法中。傳遞給formatItem
的項目是可以的。它具有我需要的所有字段(PK,名稱,單位)。但是進入formatItemSelection
的項目只有id和文本字段。
我一直在努力解決這個問題幾個小時,但我不知道。我試過(正如你在代碼中看到的那樣)將單元參數作爲jQuery數據元素傳遞,但我不知道如何檢索它。最好的解決方案是,如果傳遞給formatItemSelection
的項目將擁有從控制器傳遞的所有字段(pk,name,unit)。
在此先感謝!
編輯:我用選擇2的最新版本4.0.3