Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fetch variants in add item modal in order by ajax
Anna Siwik4502b5f7ca42
diff --git a/saleor/core/forms.py b/saleor/core/forms.pynew file mode 100644index 0000000000..95206486c5--- /dev/null+++ b/saleor/core/forms.py@@ -0,0 +1,33 @@+from django import forms+++class AjaxSelect2ChoiceField(forms.ChoiceField):++ def __init__(self, fetch_data_url='', initial=None, *args, **kwargs):+ self.queryset = kwargs.pop('queryset')+ super(AjaxSelect2ChoiceField, self).__init__(*args, **kwargs)+ self.widget.attrs['class'] = 'enable-ajax-select2'+ self.widget.attrs['data-url'] = fetch_data_url+ if initial:+ self.set_initial(initial)++ def to_python(self, value):+ if value in self.empty_values:+ return None+ try:+ value = self.queryset.get(pk=value)+ except (ValueError, TypeError, self.queryset.model.DoesNotExist):+ raise forms.ValidationError(+ self.error_messages['invalid_choice'], code='invalid_choice')+ return value++ def valid_value(self, value):+ forms.Field.validate(self, value)+ return True++ def set_fetch_data_url(self, url):+ self.widget.attrs['data-url'] = url++ def set_initial(self, obj):+ self.widget.attrs['data-initial-display'] = str(obj)+ self.widget.attrs['data-initial-value'] = obj.pkdiff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex ced6d39fc8..f51821a719 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -3,12 +3,14 @@ from __future__ import unicode_literalsfrom django import formsfrom django.conf import settingsfrom django.core.validators import MinValueValidator, MaxValueValidator+from django.shortcuts import reversefrom django.utils.translation import npgettext_lazy, pgettext_lazyfrom django_prices.forms import PriceFieldfrom payments import PaymentError, PaymentStatusfrom satchless.item import InsufficientStockfrom ...cart.forms import QuantityField+from ...core.forms import AjaxSelect2ChoiceFieldfrom ...discount.models import Voucherfrom ...order import OrderStatusfrom ...order.models import DeliveryGroup, Order, OrderLine, OrderNote@@ -353,7 +355,7 @@ class ChangeStockForm(forms.ModelForm):class AddDeliveryGroupItemForm(forms.Form):- variant = forms.ModelChoiceField(queryset=ProductVariant.objects.all())+ variant = AjaxSelect2ChoiceField(queryset=ProductVariant.objects.all())quantity = QuantityField(label=pgettext_lazy('Variant quantity form label', 'Quantity'),validators=[MinValueValidator(1)])@@ -361,6 +363,8 @@ class AddDeliveryGroupItemForm(forms.Form):def __init__(self, *args, **kwargs):self.group = kwargs.pop('group')super(AddDeliveryGroupItemForm, self).__init__(*args, **kwargs)+ self.fields['variant'].set_fetch_data_url(+ reverse('dashboard:ajax-variants'))def clean(self):cleaned_data = super(AddDeliveryGroupItemForm, self).clean()diff --git a/saleor/dashboard/product/urls.py b/saleor/dashboard/product/urls.pyindex c9b2cda3bc..b88d88f853 100644--- a/saleor/dashboard/product/urls.py+++ b/saleor/dashboard/product/urls.py@@ -93,4 +93,7 @@ urlpatterns = [name='product-stock-location-edit'),url(r'stocklocations/(?P<location_pk>[0-9]+)/delete/$',views.stock_location_delete, name='product-stock-location-delete'),++ url(r'^ajax/variants/$',+ views.ajax_variants_list, name='ajax-variants'),]diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.pyindex 916a67183f..67ce66b562 100644--- a/saleor/dashboard/product/views.py+++ b/saleor/dashboard/product/views.py@@ -2,11 +2,13 @@ from __future__ import unicode_literalsfrom django.contrib import messagesfrom django.contrib.auth.decorators import permission_required+from django.db.models import Qfrom django.http import JsonResponsefrom django.shortcuts import get_object_or_404, redirectfrom django.template.response import TemplateResponsefrom django.utils.translation import npgettext_lazy, pgettext_lazyfrom django.views.decorators.http import require_POST+from django_prices.templatetags.prices_i18n import grossfrom ...core.utils import get_paginator_itemsfrom ...product.models import (@@ -666,3 +668,24 @@ def product_bulk_update(request):number=count) % {'count': count}messages.success(request, msg)return redirect('dashboard:product-list')+++@staff_member_required+def ajax_variants_list(request):+ queryset = ProductVariant.objects.prefetch_related('product')+ search_query = request.GET.get('q', '')+ if search_query:+ queryset = queryset.filter(+ Q(sku__icontains=search_query) |+ Q(name__icontains=search_query) |+ Q(price_override__icontains=search_query) |+ Q(product__name__icontains=search_query) |+ Q(product__price__icontains=search_query))+ variants = []+ for variant in queryset:+ variants.append({+ 'id': variant.id,+ 'text': '%s, %s' % (+ variant.display_product(), gross(variant.product.price))})+ results = {'results': variants}+ return JsonResponse(results)diff --git a/saleor/static/dashboard/js/components/utils.js b/saleor/static/dashboard/js/components/utils.jsindex ec0213f88d..56243ee5d2 100644--- a/saleor/static/dashboard/js/components/utils.js+++ b/saleor/static/dashboard/js/components/utils.js@@ -16,6 +16,28 @@ export function onScroll(func) {}export function initSelects() {- $('select:not(.browser-default):not([multiple])').material_select();- $('select[multiple]:not(.browser-default)').select2({width: '100%'});+ $('select:not(.browser-default):not(.enable-ajax-select2):not([multiple])').material_select();+ $('select[multiple]:not(.browser-default):not(.enable-ajax-select2)').select2({width: '100%'});++ let $ajaxSelect2Elements = $('select.enable-ajax-select2');+ $ajaxSelect2Elements.each(function() {+ let $select = $(this);+ if ($select.attr('data-initial-display') &&+ $select.attr('data-initial-value')) {+ let display = $select.data('initial-display');+ let value = $select.data('initial-value');++ $select.append($('<option></option>').attr('value', value).text(display));+ $select.val(value);+ };++ let url = $select.data('url');+ $select.select2({+ ajax: {+ url: url,+ delay: 250+ },+ width: '100%'+ });+ });}