Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add base variant when creating product; move 'sku' and 'price' fields to variant
Marcin Gębala62a54f67b75c
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex c88cf8b5ef..1ee134e158 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -1,15 +1,18 @@from __future__ import unicode_literalsfrom django import forms+from django.conf import settingsfrom django.utils.translation import pgettext_lazy+from django_prices.forms import PriceFieldfrom ...product.models import (ProductImage, GenericProduct,- GenericVariant, Stock, ProductVariant)+ GenericVariant, Stock, ProductVariant, Product)PRODUCT_CLASSES = {'generic_product': GenericProduct}+def get_verbose_name(model):return model._meta.verbose_name@@ -29,23 +32,44 @@ class ProductClassForm(forms.Form):class StockForm(forms.ModelForm):class Meta:model = Stock- fields = ['product', 'variant', 'location', 'quantity', 'cost_price']+ exclude = []widgets = {'product': forms.HiddenInput()}def __init__(self, *args, **kwargs):+ product = kwargs.pop('product')super(StockForm, self).__init__(*args, **kwargs)- product = self.instance.product- self.fields['cost_price'].initial = product.price+ self.fields['cost_price'].initial = product.base_variant.price+ variants = product.variants.all()if product.has_variants():- self.fields['variant'].choices = [(variant.pk, variant) for variant- in product.variants.all()]- else:- del self.fields['variant']+ variants = variants.exclude(pk=product.base_variant.pk)+ self.fields['variant'].choices = [(variant.pk, variant) for variant in variants]+++class ProductForm(forms.ModelForm):+ price = PriceField(currency=settings.DEFAULT_CURRENCY,+ label=pgettext_lazy('Product field', 'Price'),+ max_digits=12, decimal_places=4)+ sku = forms.CharField(label=pgettext_lazy('Product field', 'SKU'),+ max_length=32)++ class Meta:+ model = Product+ exclude = []++ def save(self, *args, **kwargs):+ self.instance = super(ProductForm, self).save(*args, **kwargs)+ if not self.instance.base_variant:+ self.instance.variants.create(+ name=self.instance.name,+ sku=self.cleaned_data['sku'],+ price=self.cleaned_data['price'],+ product=self.instance)+ return self.instance-class GenericProductForm(forms.ModelForm):+class GenericProductForm(ProductForm):class Meta:model = GenericProductexclude = []diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.pyindex d8b154381a..1457f64828 100644--- a/saleor/dashboard/product/views.py+++ b/saleor/dashboard/product/views.py@@ -31,20 +31,25 @@ def product_list(request):@staff_member_requireddef product_details(request, pk=None, product_cls=None):creating = pk is None+ initial = {}if creating:product = get_product_cls_by_name(product_cls)()title = _('Add new %s') % get_verbose_name(product)+ variants = []else:product = get_object_or_404(Product.objects.select_subclasses().prefetch_related('images', 'variants',), pk=pk)title = product.name+ variants = product.variants.select_subclasses().exclude(+ pk=product.base_variant.pk)+ initial = {'sku': product.base_variant.sku,+ 'price': product.base_variant.price}images = product.images.all()- variants = product.variants.select_subclasses().all()stock_items = Stock.objects.filter(product=product)form_cls = get_product_form(product)- form = form_cls(instance=product)+ form = form_cls(instance=product, initial=initial)if 'product-form' in request.POST:form = form_cls(request.POST, instance=product)@@ -94,11 +99,11 @@ def stock_edit(request, product_pk, stock_pk=None):product = get_object_or_404(Product, pk=product_pk)if stock_pk:stock = get_object_or_404(product.stock, pk=stock_pk)- title = stock.variant if stock.variant else product+ title = stock.variantelse:stock = Stock(product=product)title = product- form = StockForm(request.POST or None, instance=stock)+ form = StockForm(request.POST or None, instance=stock, product=product)if form.is_valid():form.save()messages.success(request, _('Saved stock'))diff --git a/saleor/product/forms.py b/saleor/product/forms.pyindex 5ddf1a6a68..26a78a559b 100644--- a/saleor/product/forms.py+++ b/saleor/product/forms.py@@ -6,17 +6,19 @@ from ..product.models import GenericProductclass GenericProductForm(AddToCartForm):- name = forms.ChoiceField()+ variant = forms.ChoiceField()def __init__(self, *args, **kwargs):super(GenericProductForm, self).__init__(*args, **kwargs)- available_variants = [- (v.sku, v.name) for v in self.product.variants.all()]- self.fields['name'].choices = available_variants+ variants = self.product.variants.all()+ if self.product.has_variants():+ variants = variants.exclude(pk=self.product.base_variant.pk)+ variant_choices = [(v.pk, v) for v in variants]+ self.fields['variant'].choices = variant_choicesdef get_variant(self, cleaned_data):- name = cleaned_data['name']- self.product.variants.get(name=name)+ pk = cleaned_data['variant']+ return self.product.variants.get(pk=pk)class ProductVariantInline(forms.models.BaseInlineFormSet):diff --git a/saleor/product/migrations/0011_auto_20150618_0938.py b/saleor/product/migrations/0011_auto_20150618_0938.pynew file mode 100644index 0000000000..19446c632c--- /dev/null+++ b/saleor/product/migrations/0011_auto_20150618_0938.py@@ -0,0 +1,31 @@+# -*- coding: utf-8 -*-+from __future__ import unicode_literals++from django.db import models, migrations+++class Migration(migrations.Migration):++ dependencies = [+ ('product', '0010_genericvariant_weight'),+ ]++ operations = [+ migrations.RemoveField(+ model_name='product',+ name='price',+ ),+ migrations.RemoveField(+ model_name='product',+ name='sku',+ ),+ migrations.AlterField(+ model_name='stock',+ name='variant',+ field=models.ForeignKey(related_name='stock', verbose_name='variant', to='product.ProductVariant'),+ ),+ migrations.AlterUniqueTogether(+ name='stock',+ unique_together=set([('variant', 'location')]),+ ),+ ]diff --git a/saleor/product/models/base.py b/saleor/product/models/base.pyindex 0bc520199e..42e3c6c8df 100644--- a/saleor/product/models/base.py+++ b/saleor/product/models/base.py@@ -44,17 +44,12 @@ class Category(MPTTModel):class Product(models.Model, ItemRange):name = models.CharField(pgettext_lazy('Product field', 'name'), max_length=128)- sku = models.CharField(- pgettext_lazy('Product field', 'SKU'), max_length=32, unique=True)description = models.TextField(verbose_name=pgettext_lazy('Product field', 'description'))collection = models.CharField(db_index=True, max_length=100, blank=True)categories = models.ManyToManyField(Category, verbose_name=pgettext_lazy('Product field', 'categories'),related_name='products')- price = PriceField(pgettext_lazy('Product field', 'price'),- currency=settings.DEFAULT_CURRENCY, max_digits=12,- decimal_places=4)objects = InheritanceManager()@@ -62,13 +57,13 @@ class Product(models.Model, ItemRange):app_label = 'product'def __iter__(self):- if self.variants.exists():+ if self.get_variants():if not hasattr(self, '__variants'):- setattr(self, '__variants',- self.variants.select_subclasses().all())+ setattr(self, '__variants', self.get_variants())return iter(getattr(self, '__variants'))else:- return iter([self])+ variants = [self.base_variant] if self.base_variant else []+ return iter(variants)def __repr__(self):class_ = type(self)@@ -78,6 +73,17 @@ class Product(models.Model, ItemRange):def __str__(self):return self.name+ def get_variants(self):+ return self.variants.select_subclasses().exclude(pk=self.base_variant.pk)++ @property+ def base_variant(self):+ return self.variants.first() if self.variants.exists() else None++ @property+ def price(self):+ return self.base_variant.price if self.base_variant else None+def get_absolute_url(self):return reverse('product:details', kwargs={'slug': self.get_slug(),'product_id': self.id})@@ -90,7 +96,7 @@ class Product(models.Model, ItemRange):def get_price_per_item(self, item, discounts=None, **kwargs):price = self.price- if discounts:+ if price and discounts:discounts = list(get_product_discounts(self, discounts, **kwargs))if discounts:modifier = max(discounts)@@ -112,7 +118,7 @@ class Product(models.Model, ItemRange):'Product admin page', 'Maximum price')def is_available(self):- if self.variants.exists():+ if self.get_variants():return any(variant.is_item_available() for variant in self)else:return self.is_item_available()@@ -121,7 +127,7 @@ class Product(models.Model, ItemRange):return any([stock_item.is_available() for stock_item in self.stock.all()])def has_variants(self):- return self.variants.exists()+ return bool(self.get_variants())@python_2_unicode_compatible@@ -142,7 +148,7 @@ class ProductVariant(models.Model, Item):app_label = 'product'def __str__(self):- return '%s - %s - %s' % (self.product.name, self.name, self.sku)+ return '%s - %s' % (self.name, self.sku)def get_price_per_item(self, discounts=None, **kwargs):if self.price is not None:@@ -183,13 +189,12 @@ class Stock(models.Model):verbose_name=pgettext_lazy('Stock item field', 'product'))variant = models.ForeignKey(ProductVariant, related_name='stock',- verbose_name=pgettext_lazy('Stock item field', 'variant'),- blank=True, null=True)+ verbose_name=pgettext_lazy('Stock item field', 'variant'))+ location = models.CharField(+ pgettext_lazy('Stock item field', 'location'), max_length=100)quantity = models.IntegerField(pgettext_lazy('Stock item field', 'quantity'),validators=[MinValueValidator(0)], default=Decimal(1))- location = models.CharField(- pgettext_lazy('Stock item field', 'location'), max_length=100)cost_price = PriceField(pgettext_lazy('Stock item field', 'cost price'),currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=4,@@ -197,11 +202,10 @@ class Stock(models.Model):class Meta:app_label = 'product'- unique_together = ('product', 'variant', 'location')+ unique_together = ('variant', 'location')def __str__(self):- sku = self.variant.sku if self.variant else self.product.sku- return "%s - %s - %s" % (self.product.name, sku, self.location)+ return "%s - %s - %s" % (self.variant.name, self.variant.sku, self.location)def is_available(self):return self.quantity > 0