Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Use asynchronous ajax field for selecting products to collection
akjanik175acab92cc2
diff --git a/saleor/dashboard/collection/forms.py b/saleor/dashboard/collection/forms.pyindex 3d3dad0510..921ba0046c 100644--- a/saleor/dashboard/collection/forms.py+++ b/saleor/dashboard/collection/forms.py@@ -1,13 +1,19 @@from text_unidecode import unidecodefrom django import forms+from django.urls import reverse_lazyfrom django.utils.text import slugifyfrom django.utils.translation import pgettext_lazy-from ...product.models import Collection+from ...product.models import Collection, Product+from ..forms import AjaxSelect2MultipleChoiceFieldclass CollectionForm(forms.ModelForm):+ products = AjaxSelect2MultipleChoiceField(+ queryset=Product.objects.all(),+ fetch_data_url=reverse_lazy('dashboard:ajax-products'), required=False)+class Meta:model = Collectionexclude = ['slug']@@ -19,7 +25,13 @@ class CollectionForm(forms.ModelForm):'Products selection','Products')}+ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ if self.instance.pk:+ self.fields['products'].set_initial(self.instance.products.all())++def save(self, commit=True):self.instance.slug = slugify(unidecode(self.instance.name))- super(CollectionForm, self).save(commit=commit)+ super().save(commit=commit)return self.instancediff --git a/saleor/dashboard/collection/urls.py b/saleor/dashboard/collection/urls.pyindex 323652c0b1..e7542e30c8 100644--- a/saleor/dashboard/collection/urls.py+++ b/saleor/dashboard/collection/urls.py@@ -6,8 +6,8 @@ from . import viewsurlpatterns = [url(r'^$', views.collection_list, name='collection-list'),url(r'^add/$', views.collection_create, name='collection-add'),- url(r'^(?P<collection_pk>[0-9]+)/edit/$',+ url(r'^(?P<pk>[0-9]+)/edit/$',views.collection_update, name='collection-update'),- url(r'^(?P<collection_pk>[0-9]+)/delete/$',+ url(r'^(?P<pk>[0-9]+)/delete/$',views.collection_delete, name='collection-delete'),]diff --git a/saleor/dashboard/collection/views.py b/saleor/dashboard/collection/views.pyindex d5be8c2a46..657a26a64f 100644--- a/saleor/dashboard/collection/views.py+++ b/saleor/dashboard/collection/views.py@@ -4,7 +4,7 @@ from django.contrib.auth.decorators import permission_requiredfrom django.core.urlresolvers import reversefrom django.http import JsonResponsefrom django.shortcuts import redirect, get_object_or_404-from django.utils.translation import ugettext_lazy as _+from django.utils.translation import pgettext_lazyfrom ...product.models import Collectionfrom ...core.utils import get_paginator_items@@ -29,7 +29,8 @@ def collection_create(request):form = CollectionForm(request.POST or None)if form.is_valid():collection = form.save()- messages.success(request, _('Added collection %s') % collection)+ msg = pgettext_lazy('Collection message', 'Added collection')+ messages.success(request, msg)return redirect('dashboard:collection-list')ctx = {'collection': collection, 'form': form}return TemplateResponse(request, 'dashboard/collection/detail.html', ctx)@@ -37,23 +38,26 @@ def collection_create(request):@staff_member_required@permission_required('product.edit_product')-def collection_update(request, collection_pk=None):- collection = get_object_or_404(Collection, pk=collection_pk)+def collection_update(request, pk=None):+ collection = get_object_or_404(Collection, pk=pk)form = CollectionForm(request.POST or None, instance=collection)if form.is_valid():collection = form.save()- messages.success(request, _('Updated collection %s') % collection)+ msg = pgettext_lazy('Collection message', 'Updated collection')+ messages.success(request, msg)+ return redirect('dashboard:collection-update', pk=collection.pk)ctx = {'collection': collection, 'form': form}return TemplateResponse(request, 'dashboard/collection/detail.html', ctx)@staff_member_required@permission_required('product.edit_product')-def collection_delete(request, collection_pk=None):- collection = get_object_or_404(Collection, pk=collection_pk)+def collection_delete(request, pk=None):+ collection = get_object_or_404(Collection, pk=pk)if request.method == 'POST':collection.delete()- messages.success(request, _("Deleted collection %s") % collection)+ msg = pgettext_lazy('Collection message', 'Deleted collection')+ messages.success(request, msg)if request.is_ajax():response = {'redirectUrl': reverse('dashboard:collection-list')}return JsonResponse(response)diff --git a/saleor/dashboard/forms.py b/saleor/dashboard/forms.pyindex 4df7a96f32..ad3ff3ce6a 100644--- a/saleor/dashboard/forms.py+++ b/saleor/dashboard/forms.py@@ -57,6 +57,9 @@ class AjaxSelect2MultipleChoiceField(forms.MultipleChoiceField):self.widget.attrs['multiple'] = Truedef to_python(self, value):+ # Allow to set empty list for non required case+ if value == []:+ return valueif value in self.empty_values:return Noneelif not isinstance(value, (list, tuple)):diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex c1db9f7978..4206bc0468 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -127,11 +127,11 @@ class ProductForm(forms.ModelForm):'Product published toggle', 'Published'),'is_featured': pgettext_lazy('Featured product toggle', 'Feature this product on homepage'),- 'collections' :pgettext_lazy(+ 'collections': pgettext_lazy('Include in collection select', 'Collections')}- collections = forms.ModelMultipleChoiceField(required=False,- queryset=Collection.objects.all())+ collections = forms.ModelMultipleChoiceField(+ required=False, queryset=Collection.objects.all())def __init__(self, *args, **kwargs):self.product_attributes = []@@ -142,7 +142,8 @@ class ProductForm(forms.ModelForm):'values')self.prepare_fields_for_attributes()self.fields['description'].widget = RichTextEditorWidget()- self.fields["collections"].initial = Collection.objects.filter(products__name=self.instance)+ self.fields["collections"].initial = Collection.objects.filter(+ products__name=self.instance)def prepare_fields_for_attributes(self):for attribute in self.product_attributes:@@ -173,9 +174,9 @@ class ProductForm(forms.ModelForm):instance = super().save(commit=False)def save_collections():- instance.collections.clear()- for collections in self.cleaned_data['collections']:- instance.collections.add(collections)+ instance.collections.clear()+ for collections in self.cleaned_data['collections']:+ instance.collections.add(collections)self.save_collections = save_collectionsif commit:diff --git a/saleor/product/views.py b/saleor/product/views.pyindex 1e65981257..9e31d35556 100644--- a/saleor/product/views.py+++ b/saleor/product/views.py@@ -133,4 +133,3 @@ def category_index(request, path, category_id):'now_sorted_by': now_sorted_by,'is_descending': is_descending}return TemplateResponse(request, 'category/index.html', ctx)-diff --git a/tests/test_collection.py b/tests/test_collection.pyindex 10039a3f89..d3a67e8541 100644--- a/tests/test_collection.py+++ b/tests/test_collection.py@@ -22,7 +22,7 @@ def test_list_view(admin_client, collection):@pytest.mark.django_dbdef test_collection_form_name():- data = {'name': 'Test Collection'}+ data = {'name': 'Test Collection', 'products': []}form = CollectionForm(data)assert form.is_valid()@@ -58,14 +58,14 @@ def test_collection_create_view(admin_client):def test_collection_update_view(admin_client, collection, product_in_stock):url = reverse('dashboard:collection-update',- kwargs={'collection_pk': collection.id})+ kwargs={'pk': collection.id})response = admin_client.get(url)assert response.status_code == 200current_name = collection.namedata = {'name': 'New name', 'products': [product_in_stock.id]}response = admin_client.post(url, data)- assert response.status_code == 200+ assert response.status_code == 302collection.refresh_from_db()assert not current_name == collection.name@@ -76,14 +76,14 @@ def test_collection_delete_view(admin_client, collection):# Test Http404 when collection doesn't existpk = 500url404 = reverse('dashboard:collection-delete',- kwargs={'collection_pk': pk})+ kwargs={'pk': pk})response404 = admin_client.post(url404)assert response404.status_code == 404# Test deleting objectcollections_count = Collection.objects.count()url = reverse('dashboard:collection-delete',- kwargs={'collection_pk': collection.id})+ kwargs={'pk': collection.id})response = admin_client.post(url)assert response.status_code == 302assert Collection.objects.count() == (collections_count - 1)