Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Handle reorder images action in form
Anna Siwike7f27ceb4acd
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex ee75ade7b2..520541ef0e 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -290,6 +290,31 @@ AttributeChoiceValueFormset = inlineformset_factory(extra=1)+class OrderedModelMultipleChoiceField(forms.ModelMultipleChoiceField):+ def clean(self, value):+ qs = super(OrderedModelMultipleChoiceField, self).clean(value)+ return sorted(qs, key=lambda v: value.index(v.pk))+++class ReorderProductImagesForm(forms.ModelForm):+ ordered_images = OrderedModelMultipleChoiceField(+ queryset=ProductImage.objects.none())++ class Meta:+ model = Product+ fields = ()++ def __init__(self, *args, **kwargs):+ super(ReorderProductImagesForm, self).__init__(*args, **kwargs)+ if self.instance:+ self.fields['ordered_images'].queryset = self.instance.images.all()++ def save(self):+ for order, image in enumerate(self.cleaned_data['ordered_images']):+ image.order = order+ image.save()++class UploadImageForm(forms.ModelForm):class Meta:model = ProductImagediff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.pyindex e310317766..6a105e7652 100644--- a/saleor/dashboard/product/views.py+++ b/saleor/dashboard/product/views.py@@ -562,17 +562,16 @@ def stock_location_delete(request, location_pk):@staff_member_requireddef ajax_reorder_product_images(request, product_pk):product = get_object_or_404(Product, pk=product_pk)- data = json.loads(request.body)- order = data["order"]- for order, pk in enumerate(order):- try:- img = product.images.get(pk=pk)- except ProductImage.DoesNotExist:- pass- else:- img.order = order- img.save()- return JsonResponse({}, status=200)+ ordered_images = json.loads(request.body.decode('utf-8'))+ form = forms.ReorderProductImagesForm(ordered_images, instance=product)+ status = 200+ ctx = {}+ if form.is_valid():+ form.save()+ elif form.errors:+ status = 400+ ctx = {'error': form.errors}+ return JsonResponse(ctx, status=status)@require_POSTdiff --git a/saleor/static/dashboard/js/dashboard.js b/saleor/static/dashboard/js/dashboard.jsindex 1d63de6af8..19498acec0 100644--- a/saleor/static/dashboard/js/dashboard.js+++ b/saleor/static/dashboard/js/dashboard.js@@ -169,7 +169,7 @@ if (el) {dataType: 'json',contentType: 'application/json',data: JSON.stringify({- 'order': (function () {+ 'ordered_images': (function () {let postData = [];$(el).find('.product-gallery-item[data-id]').each(function () {postData.push($(this).data('id'));