Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add generic product and variant
Marcin Gębala5b42d1184892
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex 6b98fc9d3f..e9f192d2c9 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -5,19 +5,26 @@ from django.forms.models import inlineformset_factoryfrom django.forms.widgets import ClearableFileInputfrom django.utils.translation import pgettext_lazy-from ...product.models import (ProductImage, Product, ShirtVariant, BagVariant,- Shirt, Bag)+from ...product.models import (ProductImage, Product, GenericProduct,+ GenericVariant, ShirtVariant, Shirt, Bag,+ BagVariant)PRODUCT_CLASSES = {'shirt': Shirt,- 'bag': Bag}+ 'bag': Bag,+ 'generic_product': GenericProduct+}++def get_verbose_name(model):+ return model._meta.verbose_nameclass ProductClassForm(forms.Form):product_cls = forms.ChoiceField(label=pgettext_lazy('Product class form label', 'Product class'),widget=forms.RadioSelect,- choices=[(name, name.capitalize()) for name in PRODUCT_CLASSES.keys()])+ choices=[(name, get_verbose_name(cls).capitalize()) for name, cls in+ PRODUCT_CLASSES.iteritems()])def __init__(self, *args, **kwargs):super(ProductClassForm, self).__init__(*args, **kwargs)@@ -30,6 +37,12 @@ class ProductForm(forms.ModelForm):fields = ['name', 'description', 'collection']+class GenericProductForm(ProductForm):+ class Meta:+ model = GenericProduct+ exclude = []++class ShirtForm(ProductForm):class Meta:model = Shirt@@ -57,15 +70,20 @@ ShirtVariantFormset = inlineformset_factory(Shirt, ShirtVariant, exclude=[], **formset_defaults)BagVariantFormset = inlineformset_factory(Bag, BagVariant, exclude=[], **formset_defaults)+GenericVariantFormset = inlineformset_factory(+ GenericProduct, GenericVariant, exclude=[], **formset_defaults+)def get_product_form(product):- if isinstance(product, Shirt):+ if isinstance(product, GenericProduct):+ return GenericProductForm+ elif isinstance(product, Shirt):return ShirtFormelif isinstance(product, Bag):return BagFormelse:- raise ValueError('Unknown product')+ raise ValueError('Unknown product class')def get_product_cls_by_name(cls_name):@@ -79,6 +97,8 @@ def get_variant_formset(product):return ShirtVariantFormsetelif isinstance(product, Bag):return BagVariantFormset+ elif isinstance(product, GenericProduct):+ return GenericVariantFormsetelse:raise ValueError('Unknown product')diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.pyindex 6e39ae967e..ad27adb7b8 100644--- a/saleor/dashboard/product/views.py+++ b/saleor/dashboard/product/views.py@@ -2,11 +2,9 @@ from __future__ import unicode_literalsfrom django.contrib import messagesfrom django.core.urlresolvers import reverse_lazy-from django.db import transactionfrom django.shortcuts import get_object_or_404, redirectfrom django.template.response import TemplateResponsefrom django.utils.translation import ugettext_lazy as _-from django.views.decorators.http import require_POSTfrom django.views.generic import DeleteViewfrom ...product.models import Product, ProductImage@@ -14,7 +12,7 @@ from ..utils import paginatefrom ..views import StaffMemberOnlyMixin, staff_member_requiredfrom .forms import (ProductClassForm, get_product_form,get_product_cls_by_name, get_variant_formset,- ProductImageForm, PRODUCT_CLASSES)+ ProductImageForm, get_verbose_name)@staff_member_required@@ -34,7 +32,7 @@ def product_details(request, pk=None, product_cls=None):creating = pk is Noneif creating:product = get_product_cls_by_name(product_cls)()- title = _('Add new %s') % product_cls+ title = _('Add new %s') % get_verbose_name(product)else:product = get_object_or_404(Product.objects.select_subclasses(), pk=pk)title = product.namediff --git a/saleor/product/migrations/0004_auto_20150616_0327.py b/saleor/product/migrations/0004_auto_20150616_0327.pynew file mode 100644index 0000000000..2af5cd0ce3--- /dev/null+++ b/saleor/product/migrations/0004_auto_20150616_0327.py@@ -0,0 +1,72 @@+# -*- coding: utf-8 -*-+from __future__ import unicode_literals++from django.db import models, migrations+from decimal import Decimal+import django_prices.models+import django.core.validators+import satchless.item+++class Migration(migrations.Migration):++ dependencies = [+ ('product', '0003_auto_20150610_0554'),+ ]++ operations = [+ migrations.CreateModel(+ name='GenericProduct',+ fields=[+ ('product_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='product.Product')),+ ('weight', models.DecimalField(max_digits=6, decimal_places=2)),+ ('price', django_prices.models.PriceField(currency=b'USD', verbose_name='price', max_digits=12, decimal_places=4)),+ ],+ bases=('product.product', models.Model),+ ),+ migrations.CreateModel(+ name='GenericVariant',+ fields=[+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),+ ('stock', models.IntegerField(default=Decimal('1'), verbose_name='stock', validators=[django.core.validators.MinValueValidator(0)])),+ ('sku', models.CharField(unique=True, max_length=32, verbose_name='SKU')),+ ('name', models.CharField(max_length=100, verbose_name='name')),+ ('product', models.ForeignKey(related_name='variants', to='product.GenericProduct')),+ ],+ bases=(models.Model, satchless.item.StockedItem, satchless.item.Item),+ ),+ migrations.RemoveField(+ model_name='bag',+ name='depth',+ ),+ migrations.RemoveField(+ model_name='bag',+ name='length',+ ),+ migrations.RemoveField(+ model_name='bag',+ name='width',+ ),+ migrations.RemoveField(+ model_name='shirt',+ name='depth',+ ),+ migrations.RemoveField(+ model_name='shirt',+ name='length',+ ),+ migrations.RemoveField(+ model_name='shirt',+ name='width',+ ),+ migrations.AlterField(+ model_name='product',+ name='categories',+ field=models.ManyToManyField(related_name='products', verbose_name='categories', to='product.Category'),+ ),+ migrations.AlterField(+ model_name='productimage',+ name='alt',+ field=models.CharField(max_length=128, verbose_name='short description', blank=True),+ ),+ ]diff --git a/saleor/product/models/__init__.py b/saleor/product/models/__init__.pyindex eb1d1ddbd5..78636d2a75 100644--- a/saleor/product/models/__init__.py+++ b/saleor/product/models/__init__.py@@ -1,11 +1,12 @@from .base import Category, Productfrom .discounts import FixedProductDiscount, get_product_discounts-from .products import Bag, BagVariant, Shirt, ShirtVariant-from .variants import (Color, ColoredVariant, StockedProduct, PhysicalProduct,- ProductVariant)+from .products import (Bag, BagVariant, GenericProduct, GenericVariant, Shirt,+ ShirtVariant, PhysicalProduct)+from .variants import (Color, ColoredVariant, StockedProduct, ProductVariant)from .images import ProductImage__all__ = ['Category', 'Product', 'FixedProductDiscount',- 'get_product_discounts', 'Bag', 'BagVariant', 'Shirt',- 'ShirtVariant', 'Color', 'ColoredVariant', 'StockedProduct',- 'PhysicalProduct', 'ProductVariant', 'ProductImage']+ 'get_product_discounts', 'Bag', 'BagVariant', 'GenericProduct',+ 'GenericVariant', 'Shirt', 'ShirtVariant', 'Color', 'ColoredVariant',+ 'StockedProduct', 'PhysicalProduct', 'ProductVariant',+ 'ProductImage']diff --git a/saleor/product/models/base.py b/saleor/product/models/base.pyindex 87447b4731..5ee131be22 100644--- a/saleor/product/models/base.py+++ b/saleor/product/models/base.py@@ -51,9 +51,12 @@ class Product(models.Model, ItemRange):app_label = 'product'def __iter__(self):- if not hasattr(self, '__variants'):- setattr(self, '__variants', self.variants.all())- return iter(getattr(self, '__variants'))+ if self.variants.exists():+ if not hasattr(self, '__variants'):+ setattr(self, '__variants', self.variants.all())+ return iter(getattr(self, '__variants'))+ else:+ return iter([self])def __repr__(self):class_ = type(self)diff --git a/saleor/product/models/products.py b/saleor/product/models/products.pyindex eb5b4a6763..01952ba427 100644--- a/saleor/product/models/products.py+++ b/saleor/product/models/products.py@@ -1,12 +1,52 @@from __future__ import unicode_literals+from django.conf import settingsfrom django.db import modelsfrom django.utils.encoding import python_2_unicode_compatiblefrom django.utils.translation import pgettext_lazy+from django_prices.models import PriceField+from .base import Product-from .variants import (ProductVariant, PhysicalProduct, ColoredVariant,- StockedProduct)+from .variants import (ProductVariant, ColoredVariant, StockedProduct)+++class PhysicalProduct(models.Model):+ weight = models.DecimalField(max_digits=6, decimal_places=2)+ price = PriceField(+ pgettext_lazy('Product field', 'price'),+ currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=4)++ class Meta:+ abstract = True+ app_label = 'product'++ def get_weight(self):+ try:+ return self.weight+ except AttributeError:+ return self.product.weight++ def is_available(self):+ if self.variants.exists():+ return any(variant.is_available() for variant in self)+ else:+ return False+++class GenericProduct(PhysicalProduct, Product):++ class Meta:+ app_label = 'product'+++class GenericVariant(ProductVariant, StockedProduct):+ product = models.ForeignKey(GenericProduct, related_name='variants')+ name = models.CharField(pgettext_lazy('Variant field', 'name'),+ max_length=100)++ class Meta:+ app_label = 'product'class Bag(PhysicalProduct, Product, ColoredVariant):diff --git a/saleor/product/models/variants.py b/saleor/product/models/variants.pyindex 7d635d9226..1a4c9ffc99 100644--- a/saleor/product/models/variants.py+++ b/saleor/product/models/variants.py@@ -5,8 +5,6 @@ from django.core.validators import MinValueValidatorfrom django.db import modelsfrom django.utils.translation import pgettext_lazyfrom satchless.item import Item, StockedItem-from django_prices.models import PriceField-from django.conf import settingsfrom django.core.urlresolvers import reversefrom django.utils.encoding import python_2_unicode_compatible@@ -43,32 +41,6 @@ class StockedProduct(models.Model, StockedItem):return self.get_stock() > 0-class PhysicalProduct(models.Model):- weight = models.DecimalField(max_digits=6, decimal_places=2)- length = models.DecimalField(- max_digits=6, decimal_places=2, blank=True, default=0)- width = models.DecimalField(- max_digits=6, decimal_places=2, blank=True, default=0)- depth = models.DecimalField(- max_digits=6, decimal_places=2, blank=True, default=0)- price = PriceField(- pgettext_lazy('Product field', 'price'),- currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=4)-- class Meta:- abstract = True- app_label = 'product'-- def get_weight(self):- try:- return self.weight- except AttributeError:- return self.product.weight-- def is_available(self):- return any(variant.is_available() for variant in self)--@python_2_unicode_compatibleclass ColoredVariant(models.Model):color = models.ForeignKey(Color)