Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Dashboard forms & templates & widgets
Pacu2fd43af11a1a7
diff --git a/saleor/core/weight.py b/saleor/core/weight.pynew file mode 100644index 0000000000..c181c9329f--- /dev/null+++ b/saleor/core/weight.py@@ -0,0 +1,84 @@+from django import forms+from django.conf import settings+from django.template.loader import render_to_string+from django.utils.translation import pgettext_lazy+from measurement.measures import Mass+++def zero_weight():+ """Function used as a model's default."""+ return Mass(kg=0)+++class MassUnits:+ KILOGRAM = 'kg'+ POUND = 'lb'+ OUNCE = 'oz'+ GRAM = 'g'++ CHOICES = [+ (KILOGRAM, pgettext_lazy('Kilogram mass unit symbol', 'kg')),+ (POUND, pgettext_lazy('Pound mass unit symbol', 'lb')),+ (OUNCE, pgettext_lazy('Ounce mass unit symbol', 'oz')),+ (GRAM, pgettext_lazy('Gram mass unit symbol', 'g'))]++ dict_choices = dict(CHOICES)+++class WeightInput(forms.TextInput):+ template = 'dashboard/shipping/weight_widget.html'+ input_type = 'number'++ def __init__(+ self, unit_choice=settings.DEFAULT_WEIGHT_UNITS[0][0],+ *args, **kwargs):+ self.unit_choice = unit_choice+ super().__init__(*args, **kwargs)++ def format_value(self, value):+ if isinstance(value, Mass):+ return value.value+ return value++ def render(self, name, value, attrs=None):+ widget = super().render(name, value, attrs=attrs)+ return render_to_string(self.template, {+ 'widget': widget, 'value': value, 'unit': self.unit_choice})+++class WeightField(forms.DecimalField):+ def __init__(+ self, unit_choice=settings.DEFAULT_WEIGHT_UNITS[0][0],+ widget=WeightInput, *args, **kwargs):+ self.unit_choice = unit_choice+ if isinstance(widget, type):+ widget = widget(+ unit_choice=self.unit_choice,+ attrs={'type': 'number', 'step': 'any'})+ super().__init__(*args, widget=widget, **kwargs)++ def to_python(self, value):+ value = super().to_python(value)+ if value is None:+ return value+ return Mass(**{self.unit_choice: value})++ def validate(self, mass):+ if mass in self.empty_values:+ super().validate(mass)+ return mass+ elif not isinstance(mass, Mass):+ raise Exception('%r is not a valid mass.' % (mass,))+ elif mass.unit != self.unit_choice:+ raise forms.ValidationError(+ 'Invalid unit_choice: %r (expected %r).' % (+ mass.unit, self.unit_choice))+ elif mass.value < 0:+ raise forms.ValidationError(+ 'Weight should be larger or equal 0 %(unit)s.' % {+ 'unit': self.unit_choice})++ def clean(self, value):+ value = self.to_python(value)+ self.validate(value)+ return valuediff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex dc976f4d56..96aade7677 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -13,6 +13,7 @@ from mptt.forms import TreeNodeChoiceFieldfrom . import ProductBulkActionfrom ...core.i18n import VAT_RATE_TYPE_TRANSLATIONSfrom ...core.utils.taxes import DEFAULT_TAX_RATE_NAME, include_taxes_in_prices+from ...core.weight import WeightFieldfrom ...product.models import (AttributeChoiceValue, Category, Collection, Product, ProductAttribute,ProductImage, ProductType, ProductVariant, VariantImage)@@ -68,6 +69,12 @@ class ProductTypeForm(forms.ModelForm):tax_rate = forms.ChoiceField(required=False,label=pgettext_lazy('Product type tax rate type', 'Tax rate'))+ weight = WeightField(+ label=pgettext_lazy('ProductType weight', 'Weight'),+ help_text=pgettext_lazy(+ 'ProductVariant weight help text',+ 'Default weight that will be used for calculating shipping'+ ' price for products of that type.'))class Meta:model = ProductType@@ -87,14 +94,7 @@ class ProductTypeForm(forms.ModelForm):'Attributes common to all variants'),'is_shipping_required': pgettext_lazy('Shipping toggle',- 'Require shipping'),- 'weight': pgettext_lazy(- 'Product type weight', 'Weight')}- help_texts = {- 'weight': pgettext_lazy(- 'Weight help text',- 'Default weight that will be used for calculating shipping'- ' price for products of that type.')}+ 'Require shipping')}def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)@@ -215,6 +215,13 @@ class ProductForm(forms.ModelForm, AttributesMixin):label=pgettext_lazy('Add to collection select', 'Collections'))description = RichTextField(label=pgettext_lazy('Description', 'Description'))+ weight = WeightField(+ required=False,+ label=pgettext_lazy('ProductType weight', 'Weight'),+ help_text=pgettext_lazy(+ 'Product weight field help text',+ 'Weight will be used to calculate shipping price, '+ 'if empty, equal to default value used on the ProductType.'))model_attributes_field = 'attributes'@@ -230,11 +237,6 @@ class ProductForm(forms.ModelForm, AttributesMixin):'Product published toggle', 'Published'),'charge_taxes': pgettext_lazy('Charge taxes on product', 'Charge taxes on this product')}- help_texts = {- 'weight': pgettext_lazy(- 'Weight field help text',- 'Weight will be used to calculate shipping price, '- 'if empty, equal to default value used on the ProductType.')}def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)@@ -284,6 +286,13 @@ class ProductForm(forms.ModelForm, AttributesMixin):class ProductVariantForm(forms.ModelForm, AttributesMixin):model_attributes_field = 'attributes'+ weight = WeightField(+ required=False,+ label=pgettext_lazy('ProductVariant weight', 'Weight'),+ help_text=pgettext_lazy(+ 'ProductVariant weight help text',+ 'Weight will be used to calculate shipping price. '+ 'If empty, weight from Product or ProductType will be used.'))class Meta:model = ProductVariant@@ -292,7 +301,6 @@ class ProductVariantForm(forms.ModelForm, AttributesMixin):'quantity', 'cost_price', 'track_inventory']labels = {'sku': pgettext_lazy('SKU', 'SKU'),- 'weight': pgettext_lazy('ProductVariant weight', 'Weight'),'price_override': pgettext_lazy('Override price', 'Selling price override'),'quantity': pgettext_lazy('Integer number', 'Number in stock'),@@ -302,11 +310,7 @@ class ProductVariantForm(forms.ModelForm, AttributesMixin):help_texts = {'track_inventory': pgettext_lazy('product variant handle stock field help text',- 'Automatically track this product\'s inventory'),- 'weight': pgettext_lazy(- 'ProductVariant weight help text',- 'Weight will be used to calculate shipping price. '- 'If empty, weight from Product or ProductType will be used.')}+ 'Automatically track this product\'s inventory')}def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)diff --git a/saleor/dashboard/shipping/forms.py b/saleor/dashboard/shipping/forms.pyindex 010b65d866..59d5b760e0 100644--- a/saleor/dashboard/shipping/forms.py+++ b/saleor/dashboard/shipping/forms.py@@ -1,6 +1,7 @@from django import formsfrom django.utils.translation import pgettext_lazy+from ...core.weight import WeightFieldfrom ...shipping import ShippingMethodTypefrom ...shipping.models import ShippingMethod, ShippingZone@@ -54,10 +55,9 @@ class ShippingZoneForm(forms.ModelForm):class ShippingMethodForm(forms.ModelForm):-class Meta:model = ShippingMethod- exclude = ['shipping_zone', 'type']+ fields = ['name', 'price']labels = {'name': pgettext_lazy('Shipping Method name', 'Name'),'price': pgettext_lazy('Currency amount', 'Price')}@@ -68,14 +68,84 @@ class ShippingMethodForm(forms.ModelForm):def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)- if self.instance.type == ShippingMethodType.WEIGHT_BASED:- del self.fields['minimum_order_price']- del self.fields['maximum_order_price']- else:- del self.fields['minimum_order_weight']- del self.fields['maximum_order_weight']- self.fields['minimum_order_price'].required = False- self.fields['maximum_order_price'].widget.attrs['placeholder'] = \- pgettext_lazy(- 'Placeholder for maximum order price set to unlimited',- 'No limit')+++class PriceShippingMethodForm(forms.ModelForm):+ class Meta(ShippingMethodForm.Meta):+ labels = {+ 'minimum_order_price': pgettext_lazy(+ 'Minimum order price to use this shipping method',+ 'Minimum order price'),+ 'maximum_order_price': pgettext_lazy(+ 'Maximum order price to use this order',+ 'Maximum order price')}+ labels.update(ShippingMethodForm.Meta.labels)+ fields = [+ 'name', 'price', 'minimum_order_price', 'maximum_order_price']++ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self.fields['maximum_order_price'].widget.attrs['placeholder'] = (+ pgettext_lazy(+ 'Placeholder for maximum order price set to unlimited',+ 'No limit'))+ self.fields['minimum_order_price'].widget.attrs['placeholder'] = '0'++ def clean_minimum_order_price(self):+ return self.cleaned_data['minimum_order_price'] or 0++ def clean(self):+ data = super().clean()+ min_price = data.get('minimum_order_price')+ max_price = data.get('maximum_order_price')+ if min_price and max_price is not None and max_price <= min_price:+ self.add_error('maximum_order_price', pgettext_lazy(+ 'Price shipping method form error',+ 'Maximum order price should be larger'+ ' than the minimum order price.'))+ return data+++class WeightShippingMethodForm(forms.ModelForm):+ minimum_order_weight = WeightField(+ required=False, label=pgettext_lazy(+ 'Minimum order weight to use this shipping method',+ 'Minimum order weight'))+ maximum_order_weight = WeightField(+ required=False, label=pgettext_lazy(+ 'Maximum order weight to use this shipping method',+ 'Maximum order weight'))++ class Meta(ShippingMethodForm.Meta):+ fields = [+ 'name', 'price', 'minimum_order_weight', 'maximum_order_weight']++ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self.fields['maximum_order_weight'].widget.attrs['placeholder'] = (+ pgettext_lazy(+ 'Placeholder for maximum order weight set to unlimited',+ 'No limit'))+ self.fields['minimum_order_weight'].widget.attrs['placeholder'] = '0'++ def clean_minimum_order_weight(self):+ return self.cleaned_data['minimum_order_weight'] or 0++ def clean(self):+ data = super().clean()+ min_weight = data.get('minimum_order_weight')+ max_weight = data.get('maximum_order_weight')+ if min_weight and max_weight is not None and max_weight <= min_weight:+ self.add_error('maximum_order_weight', pgettext_lazy(+ 'Price shipping method form error',+ 'Maximum order price should be larger'+ ' than the minimum order price.'))+ return data+++def get_shipping_form(type):+ if type == ShippingMethodType.WEIGHT_BASED:+ return WeightShippingMethodForm+ elif type == ShippingMethodType.PRICE_BASED:+ return PriceShippingMethodForm+ raise TypeError('Unknown form type: %s' % type)diff --git a/saleor/dashboard/shipping/views.py b/saleor/dashboard/shipping/views.pyindex 6bab671ec7..de98db99d1 100644--- a/saleor/dashboard/shipping/views.py+++ b/saleor/dashboard/shipping/views.py@@ -9,7 +9,7 @@ from ...core.utils import get_paginator_itemsfrom ...shipping.models import ShippingMethod, ShippingZonefrom ..views import staff_member_requiredfrom .filters import ShippingZoneFilter-from .forms import ShippingMethodForm, ShippingZoneForm+from .forms import ShippingZoneForm, get_shipping_form@staff_member_required@@ -92,7 +92,8 @@ def shipping_method_add(request, shipping_zone_pk, type):shipping_zone = get_object_or_404(ShippingZone, pk=shipping_zone_pk)shipping_method = ShippingMethod(shipping_zone_id=shipping_zone_pk, type=type)- form = ShippingMethodForm(request.POST or None, instance=shipping_method)+ form = get_shipping_form(shipping_method.type)+ form = form(request.POST or None, instance=shipping_method)if form.is_valid():shipping_method = form.save()msg = pgettext_lazy(@@ -114,8 +115,8 @@ def shipping_method_edit(request, shipping_zone_pk, shipping_method_pk):shipping_zone = get_object_or_404(ShippingZone, pk=shipping_zone_pk)shipping_method = get_object_or_404(ShippingMethod, pk=shipping_method_pk)- form = ShippingMethodForm(- request.POST or None, instance=shipping_method)+ form = get_shipping_form(shipping_method.type)+ form = form(request.POST or None, instance=shipping_method)if form.is_valid():country = form.save()msg = pgettext_lazy(diff --git a/saleor/order/models.py b/saleor/order/models.pyindex b6686ee8e9..2c63717955 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -21,6 +21,7 @@ from ..account.models import Addressfrom ..core.models import BaseNotefrom ..core.utils import build_absolute_urifrom ..core.utils.taxes import ZERO_TAXED_MONEY+from ..core.weight import zero_weightfrom ..discount.models import Voucherfrom ..shipping.models import ShippingMethod@@ -96,7 +97,7 @@ class Order(models.Model):customer_note = models.TextField(blank=True, default='')weight = MeasurementField(measurement=Weight, unit_choices=settings.DEFAULT_WEIGHT_UNITS,- default=0)+ default=zero_weight)objects = OrderQueryset.as_manager()class Meta:diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 6e35de66ea..ed82534003 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -24,6 +24,7 @@ from ..core.exceptions import InsufficientStockfrom ..core.models import SortableModelfrom ..core.utils.taxes import DEFAULT_TAX_RATE_NAME, apply_tax_to_pricefrom ..core.utils.translations import TranslationProxy+from ..core.weight import zero_weightfrom ..discount.utils import calculate_discounted_pricefrom ..seo.models import SeoModel, SeoModelTranslation@@ -82,7 +83,7 @@ class ProductType(models.Model):max_length=128, default=DEFAULT_TAX_RATE_NAME, blank=True)weight = MeasurementField(measurement=Weight, unit_choices=settings.DEFAULT_WEIGHT_UNITS,- default=0)+ default=zero_weight)class Meta:app_label = 'product'diff --git a/saleor/shipping/models.py b/saleor/shipping/models.pyindex aadb00580c..4a8ba95fb7 100644--- a/saleor/shipping/models.py+++ b/saleor/shipping/models.py@@ -11,6 +11,8 @@ from prices import MoneyRangefrom . import ShippingMethodTypefrom ..core.utils import format_moneyfrom ..core.utils.taxes import get_taxed_shipping_price+from ..core.utils.translations import TranslationProxy+from ..core.weight import zero_weightfrom .utils import (applicable_price_based_methods, applicable_weight_based_methods,get_price_type_display, get_weight_type_display)@@ -84,12 +86,13 @@ class ShippingMethod(models.Model):decimal_places=settings.DEFAULT_DECIMAL_PLACES, blank=True, null=True)minimum_order_weight = MeasurementField(measurement=Weight, unit_choices=settings.DEFAULT_WEIGHT_UNITS,- default=0, blank=True, null=True)+ default=zero_weight, blank=True, null=True)maximum_order_weight = MeasurementField(measurement=Weight, unit_choices=settings.DEFAULT_WEIGHT_UNITS,blank=True, null=True)objects = ShippingMethodQueryset.as_manager()+ translated = TranslationProxy()def __str__(self):return self.name@@ -123,3 +126,13 @@ class ShippingMethod(models.Model):self.minimum_order_price, self.maximum_order_price)return get_weight_type_display(self.minimum_order_weight, self.maximum_order_weight)+++class ShippingMethodTranslation(models.Model):+ language_code = models.CharField(max_length=10)+ name = models.CharField(max_length=255, null=True, blank=True)+ shipping_method = models.ForeignKey(+ ShippingMethod, related_name='translations', on_delete=models.CASCADE)++ class Meta:+ unique_together = (('language_code', 'shipping_method'),)diff --git a/templates/dashboard/shipping/methods/form.html b/templates/dashboard/shipping/methods/form.htmlindex da79d21225..758297a26c 100644--- a/templates/dashboard/shipping/methods/form.html+++ b/templates/dashboard/shipping/methods/form.html@@ -69,7 +69,7 @@{% csrf_token %}<div class="card-content"><span class="card-title">- {% trans "Shipping zone price for country " context "Shipping zone price for country form title" %}+ {% trans "Shipping method" context "Shipping method form title" %}</span><div class="row">{{ form|materializecss }}diff --git a/templates/dashboard/shipping/weight_widget.html b/templates/dashboard/shipping/weight_widget.htmlnew file mode 100644index 0000000000..802c4156e0--- /dev/null+++ b/templates/dashboard/shipping/weight_widget.html@@ -0,0 +1,4 @@+<div class="input-with-suffix">+ {{ widget }}+ <div class="input-text-suffix">{{ unit }}</div>+ </div>diff --git a/tests/dashboard/test_product.py b/tests/dashboard/test_product.pyindex c414aa7531..2f34603182 100644--- a/tests/dashboard/test_product.py+++ b/tests/dashboard/test_product.py@@ -291,7 +291,7 @@ def test_view_product_type_create('product_attributes': [color_attribute.pk],'variant_attributes': [size_attribute.pk],'has_variants': True,- 'weight_0': ['3.47'], 'weight_1': ['kg']}+ 'weight': ['3.47']}response = admin_client.post(url, data)@@ -310,7 +310,7 @@ def test_view_product_type_create_invalid('product_attributes': [size_attribute.pk],'variant_attributes': [color_attribute.pk, size_attribute.pk],'has_variants': True,- 'weight_0': ['3.47'], 'weight_1': ['kg']}+ 'weight': ['3.47']}response = admin_client.post(url, data)@@ -326,7 +326,7 @@ def test_view_product_type_create_missing_variant_attributes('product_attributes': [color_attribute.pk],'variant_attributes': [size_attribute.pk],'has_variants': False,- 'weight_0': ['3.47'], 'weight_1': ['kg']}+ 'weight': ['3.47']}response = admin_client.post(url, data)assert response.status_code == 200@@ -341,7 +341,7 @@ def test_view_product_type_create_variantless('product_attributes': [color_attribute.pk],'variant_attributes': [],'has_variants': False,- 'weight_0': ['3.47'], 'weight_1': ['kg']}+ 'weight': ['3.47']}response = admin_client.post(url, data)assert response.status_code == 302@@ -359,7 +359,7 @@ def test_view_product_type_create_variantless_invalid('product_attributes': [color_attribute.pk],'variant_attributes': [size_attribute.pk],'has_variants': False,- 'weight_0': ['3.47'], 'weight_1': ['kg']}+ 'weight': ['3.47']}response = admin_client.post(url, data)assert response.status_code == 200@@ -383,7 +383,7 @@ def test_view_product_type_edit_to_no_variants_valid(admin_client, product):'variant_attributes': product_type.variant_attributes.values_list('pk', flat=True),'has_variants': False,- 'weight_0': ['3.47'], 'weight_1': ['kg']}+ 'weight': ['3.47']}response = admin_client.post(url, data)@@ -413,7 +413,7 @@ def test_view_product_type_edit_to_no_variants_invalid(admin_client, product):'variant_attributes': product_type.variant_attributes.values_list('pk', flat=True),'has_variants': False,- 'weight_0': ['3.47'], 'weight_1': ['kg']}+ 'weight': ['3.47']}response = admin_client.post(url, data)diff --git a/tests/dashboard/test_shipping.py b/tests/dashboard/test_shipping.pyindex 48df506229..5690b9ccde 100644--- a/tests/dashboard/test_shipping.py+++ b/tests/dashboard/test_shipping.py@@ -1,7 +1,9 @@from django.urls import reversefrom prices import Money+import pytestfrom saleor.dashboard.shipping.forms import (- ShippingMethodForm, ShippingZoneForm, currently_used_countries)+ PriceShippingMethodForm, ShippingZoneForm, WeightShippingMethodForm,+ currently_used_countries)from saleor.shipping import ShippingMethodTypefrom saleor.shipping.models import ShippingMethod, ShippingZone@@ -29,6 +31,42 @@ def test_shipping_zone_form():assert 'countries' in form.errors+ 'min_price, max_price, result',+ (+ (10, 20, True),+ (None, None, True),+ (None, 10, True),+ (0, None, True),+ (20, 20, False)))+def test_price_shipping_method_form(min_price, max_price, result):+ data = {+ 'name': 'Name',+ 'price': 10,+ 'minimum_order_price': min_price,+ 'maximum_order_price': max_price}+ form = PriceShippingMethodForm(data=data)+ assert form.is_valid() == result+++ 'min_weight, max_weight, result',+ (+ (10, 20, True),+ (None, None, True),+ (None, 10, True),+ (0, None, True),+ (20, 20, False)))+def test_weight_shipping_method_form(min_weight, max_weight, result):+ data = {+ 'name': 'Name',+ 'price': 10,+ 'minimum_order_weight': min_weight,+ 'maximum_order_weight': max_weight}+ form = WeightShippingMethodForm(data=data)+ assert form.is_valid() == result++def test_shipping_zone_list(admin_client, shipping_zone):url = reverse('dashboard:shipping-zones')response = admin_client.get(url)diff --git a/tests/test_translation.py b/tests/test_translation.pyindex c3aebd88df..2371eb33b0 100644--- a/tests/test_translation.py+++ b/tests/test_translation.py@@ -4,6 +4,7 @@ from saleor.product.models import (AttributeChoiceValueTranslation, CategoryTranslation,CollectionTranslation, ProductAttributeTranslation, ProductTranslation,ProductVariantTranslation)+from saleor.shipping.models import ShippingMethodTranslation@pytest.fixture@@ -21,6 +22,13 @@ def attribute_choice_translation_fr(translated_product_attribute):name='French name')+def shipping_method_translation_fr(shipping_method):+ return ShippingMethodTranslation.objects.create(+ language_code='fr', shipping_method=shipping_method,+ name='French name')++def test_translation(product, settings, product_translation_fr):assert product.translated.name == 'Test product'assert not product.translated.description@@ -111,3 +119,10 @@ def test_voucher_translation(settings, voucher, voucher_translation_fr):assert not voucher.translated.name == 'French name'settings.LANGUAGE_CODE = 'fr'assert voucher.translated.name == 'French name'+++def shipping_method_translation(+ settings, shipping_method, shipping_method_translation_fr):+ assert not shipping_method.translated.name == 'French name'+ settings.LANGUAGE_CODE = 'fr'+ assert shipping_method.translated.name == 'French name'