Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Drop base variants in favor of manually added variants; change behavior of price and weight in variants to override related fields from product

Marcin Gębala878198437097
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.py
index d2358718b8..542a1ce427 100644
--- a/saleor/dashboard/product/forms.py
+++ b/saleor/dashboard/product/forms.py
@@ -39,52 +39,24 @@ class StockForm(forms.ModelForm):
product = kwargs.pop('product')
super(StockForm, self).__init__(*args, **kwargs)
variants = product.variants.all()
- if product.has_variants():
- variants = variants.exclude(pk=product.base_variant.pk)
- self.fields['variant'].choices = [(variant.pk, variant) for variant in variants]
+ if variants:
+ self.fields['variant'].choices = [(variant.pk, variant) for variant in variants]
+ else:
+ self.fields['variant'].widget.attrs['disabled'] = True
class ProductForm(forms.ModelForm):
- 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.save_base_variant()
- return self.instance
-
- def save_base_variant(self, **kwargs):
- defaults = {
- 'name': '',
- 'sku': self.cleaned_data['sku'],
- 'price': self.instance.price,
- 'product': self.instance
- }
- defaults.update(kwargs)
- variant_cls = get_variant_cls(self.instance)
- return variant_cls(**defaults).save()
-
-
-class GenericProductForm(ProductForm):
- class Meta:
- model = GenericProduct
- exclude = []
-
def __init__(self, *args, **kwargs):
- super(GenericProductForm, self).__init__(*args, **kwargs)
+ super(ProductForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs['placeholder'] = pgettext_lazy('Product form labels', 'Give your awesome product a name')
self.fields['collection'].widget.attrs['placeholder'] = pgettext_lazy('Product form labels', 'e.g. Zombie apocalypse gear')
self.fields['categories'].widget.attrs['data-placeholder'] = pgettext_lazy('Product form labels', 'Search')
- def save_base_variant(self, **kwargs):
- return super(GenericProductForm, self).save_base_variant(
- weight=self.instance.weight)
-
class ProductVariantForm(forms.ModelForm):
class Meta:
@@ -94,12 +66,6 @@ class ProductVariantForm(forms.ModelForm):
'product': forms.HiddenInput()
}
- def save(self, commit=True):
- if not self.instance.product.has_variants():
- Stock.objects.filter(
- variant=self.instance.product.base_variant).delete()
- super(ProductVariantForm, self).save(commit=commit)
-
class GenericVariantForm(ProductVariantForm):
class Meta:
diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.py
index 267a2462b1..b168cd19e1 100644
--- a/saleor/dashboard/product/views.py
+++ b/saleor/dashboard/product/views.py
@@ -35,18 +35,14 @@ def product_details(request, pk=None, product_cls=None):
if creating:
product = get_product_cls_by_name(product_cls)()
title = _('Add new %s') % get_verbose_name(product)
- all_variants, ctx_variants = [], []
else:
product = get_object_or_404(
Product.objects.select_subclasses().prefetch_related(
'images', 'variants'), pk=pk)
title = product.name
- all_variants = product.variants.select_subclasses()
- ctx_variants = all_variants.exclude(pk=product.base_variant.pk)
- initial = {'sku': product.base_variant.sku,
- 'price': product.base_variant.price}
images = product.images.all()
- stock_items = Stock.objects.filter(variant__in=all_variants)
+ variants = product.variants.select_subclasses()
+ stock_items = Stock.objects.filter(variant__in=variants)
form_cls = get_product_form(product)
form = form_cls(instance=product, initial=initial)
@@ -59,7 +55,7 @@ def product_details(request, pk=None, product_cls=None):
ctx = {'title': title, 'product': product, 'images': images,
'product_form': form, 'stock_items': stock_items,
- 'variants': ctx_variants}
+ 'variants': variants}
if pk:
images_reorder_url = reverse_lazy('dashboard:product-images-reorder',
kwargs={'product_pk': pk})
@@ -104,15 +100,18 @@ def stock_edit(request, product_pk, stock_pk=None):
stock = Stock()
title = product
form = StockForm(request.POST or None, instance=stock, product=product)
- if form.is_valid():
- form.save()
- messages.success(request, _('Saved stock'))
- success_url = request.POST['success_url']
- return redirect(success_url)
+ if product.variants.exists():
+ if form.is_valid():
+ form.save()
+ messages.success(request, _('Saved stock'))
+ success_url = request.POST['success_url']
+ return redirect(success_url)
+ else:
+ if form.errors:
+ messages.error(request, _('Your submitted data was not valid - '
+ 'please correct the errors below'))
else:
- if form.errors:
- messages.error(request, _('Your submitted data was not valid - '
- 'please correct the errors below'))
+ messages.error(request, _('You have to add at least one variant before you can add stock'))
ctx = {'product': product, 'stock': stock, 'form': form, 'title': title}
return TemplateResponse(request, 'dashboard/product/stock_form.html', ctx)
@@ -189,8 +188,6 @@ def variant_edit(request, product_pk, variant_pk=None):
else:
variant = variant_cls(product=product)
title = _('Add variant')
- form_initial['price'] = product.price
- form_initial['weight'] = product.weight
form_cls = get_variant_form(product)
form = form_cls(request.POST or None, instance=variant,
@@ -213,7 +210,6 @@ def variant_edit(request, product_pk, variant_pk=None):
return TemplateResponse(request, 'dashboard/product/variant_form.html', ctx)
-
@staff_member_required
def variant_delete(request, product_pk, variant_pk):
product = get_object_or_404(Product, pk=product_pk)
@@ -225,4 +221,4 @@ def variant_delete(request, product_pk, variant_pk):
return redirect(success_url)
ctx = {'product': product, 'variant': variant}
return TemplateResponse(
- request, 'dashboard/product/product_variant_confirm_delete.html', ctx)
\ No newline at end of file
+ request, 'dashboard/product/product_variant_confirm_delete.html', ctx)
diff --git a/saleor/dashboard/templates/dashboard/product/product_form.html b/saleor/dashboard/templates/dashboard/product/product_form.html
index db7316f410..817d675c18 100644
--- a/saleor/dashboard/templates/dashboard/product/product_form.html
+++ b/saleor/dashboard/templates/dashboard/product/product_form.html
@@ -63,7 +63,7 @@
<ul class="collection">
{% for variant in variants %}
<li class="collection-item">
- {{ variant.name }}, SKU: {{ variant.sku }}, price: {% gross variant.price %}
+ {{ variant.name }}, SKU: {{ variant.sku }}, price: {% gross variant.get_price_per_item %}
<a class="light-blue-text text-lighten-1" title="{% trans "Edit variant" %}"
href="{% url 'dashboard:variant-update' product_pk=product.pk variant_pk=variant.pk %}">
<i class="mdi-content-create"></i>
diff --git a/saleor/product/forms.py b/saleor/product/forms.py
index a2b67b117e..d5a5b91d61 100644
--- a/saleor/product/forms.py
+++ b/saleor/product/forms.py
@@ -6,21 +6,15 @@ from ..product.models import GenericProduct
class GenericProductForm(AddToCartForm):
- base_variant = forms.CharField(widget=forms.HiddenInput())
variant = forms.ChoiceField(required=False)
def __init__(self, *args, **kwargs):
super(GenericProductForm, self).__init__(*args, **kwargs)
- self.fields['base_variant'].initial = self.product.base_variant.pk
-
- variants = self.product.variants.all().exclude(
- pk=self.product.base_variant.pk)
+ variants = self.product.variants.all()
self.fields['variant'].choices = [(v.pk, v) for v in variants]
- if not self.product.has_variants():
- self.fields['variant'].widget = forms.HiddenInput()
def get_variant(self, cleaned_data):
- pk = cleaned_data.get('variant') or cleaned_data.get('base_variant')
+ pk = cleaned_data.get('variant')
variant = self.product.variants.get(pk=pk)
return variant
diff --git a/saleor/product/migrations/0014_auto_20150622_0623.py b/saleor/product/migrations/0014_auto_20150622_0623.py
new file mode 100644
index 0000000000..c3733d4243
--- /dev/null
+++ b/saleor/product/migrations/0014_auto_20150622_0623.py
@@ -0,0 +1,49 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+import django_prices.models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('product', '0013_product_price'),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name='genericproduct',
+ name='weight',
+ ),
+ migrations.RemoveField(
+ model_name='genericvariant',
+ name='weight',
+ ),
+ migrations.RemoveField(
+ model_name='productvariant',
+ name='price',
+ ),
+ migrations.AddField(
+ model_name='product',
+ name='weight',
+ field=models.DecimalField(default=0, verbose_name='weight', max_digits=6, decimal_places=2),
+ preserve_default=False,
+ ),
+ migrations.AddField(
+ model_name='productvariant',
+ name='price_override',
+ field=django_prices.models.PriceField(decimal_places=4, currency=b'USD', max_digits=12, blank=True, null=True, verbose_name='price override'),
+ ),
+ migrations.AddField(
+ model_name='productvariant',
+ name='weight_override',
+ field=models.DecimalField(null=True, verbose_name='weight override', max_digits=6, decimal_places=2, blank=True),
+ ),
+ migrations.AlterField(
+ model_name='product',
+ name='price',
+ field=django_prices.models.PriceField(default=0, currency=b'USD', verbose_name='price', max_digits=12, decimal_places=4),
+ preserve_default=False,
+ ),
+ ]
diff --git a/saleor/product/models/__init__.py b/saleor/product/models/__init__.py
index 6d2e30215b..b2137272fe 100644
--- a/saleor/product/models/__init__.py
+++ b/saleor/product/models/__init__.py
@@ -1,9 +1,8 @@
from .base import Category, Product, Stock
from .discounts import FixedProductDiscount, get_product_discounts
-from .products import (GenericProduct, GenericVariant, PhysicalProduct,
- ProductVariant)
+from .products import (GenericProduct, GenericVariant, ProductVariant)
from .images import ProductImage
__all__ = ['Category', 'Product', 'FixedProductDiscount',
'get_product_discounts', 'GenericProduct', 'GenericVariant',
- 'PhysicalProduct', 'ProductVariant', 'ProductImage', 'Stock']
+ 'ProductVariant', 'ProductImage', 'Stock']
diff --git a/saleor/product/models/base.py b/saleor/product/models/base.py
index 30ef7e21ad..2765c9ceb7 100644
--- a/saleor/product/models/base.py
+++ b/saleor/product/models/base.py
@@ -52,8 +52,10 @@ class Product(models.Model, ItemRange):
related_name='products')
price = PriceField(
pgettext_lazy('Product field', 'price'),
- currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=4,
- blank=True, null=True)
+ currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=4)
+ weight = models.DecimalField(
+ pgettext_lazy('Product field', 'weight'), max_digits=6,
+ decimal_places=2)
objects = InheritanceManager()
@@ -61,13 +63,9 @@ class Product(models.Model, ItemRange):
app_label = 'product'
def __iter__(self):
- if self.get_variants():
- if not hasattr(self, '__variants'):
- setattr(self, '__variants', self.get_variants())
- return iter(getattr(self, '__variants'))
- else:
- variants = [self.base_variant] if self.base_variant else []
- return iter(variants)
+ if not hasattr(self, '__variants'):
+ setattr(self, '__variants', self.variants.all())
+ return iter(getattr(self, '__variants'))
def __repr__(self):
class_ = type(self)
@@ -77,13 +75,6 @@ class Product(models.Model, ItemRange):
def __str__(self):
return self.name
- def get_variants(self):
- return self.variants.exclude(pk=self.base_variant.pk)
-
- @property
- def base_variant(self):
- return self.variants.first() if self.variants.exists() else None
-
def get_absolute_url(self):
return reverse('product:details', kwargs={'slug': self.get_slug(),
'product_id': self.id})
@@ -120,9 +111,6 @@ class Product(models.Model, ItemRange):
def is_available(self):
return any(variant.is_available() for variant in self)
- def has_variants(self):
- return bool(self.get_variants())
-
@python_2_unicode_compatible
class ProductVariant(models.Model, Item):
@@ -130,10 +118,13 @@ class ProductVariant(models.Model, Item):
pgettext_lazy('Variant field', 'name'), max_length=100)
sku = models.CharField(
pgettext_lazy('Variant field', 'SKU'), max_length=32, unique=True)
- price = PriceField(
- pgettext_lazy('Variant field', 'price'),
+ price_override = PriceField(
+ pgettext_lazy('Variant field', 'price override'),
currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=4,
blank=True, null=True)
+ weight_override = models.DecimalField(
+ pgettext_lazy('Variant field', 'weight override'),
+ max_digits=6, decimal_places=2, blank=True, null=True)
product = models.ForeignKey(Product, related_name='variants')
objects = InheritanceManager()
@@ -147,11 +138,11 @@ class ProductVariant(models.Model, Item):
name += ' (%s)' % self.name
return name
+ def get_weight(self):
+ return self.weight_override or self.product.weight
+
def get_price_per_item(self, discounts=None, **kwargs):
- if self.price is not None:
- price = self.price
- else:
- price = self.product.price
+ price = self.price_override or self.product.price
if discounts:
discounts = list(get_product_discounts(self, discounts, **kwargs))
if discounts:
diff --git a/saleor/product/models/products.py b/saleor/product/models/products.py
index 279524f253..4bcb3c58aa 100644
--- a/saleor/product/models/products.py
+++ b/saleor/product/models/products.py
@@ -5,27 +5,13 @@ from django.db import models
from .base import Product, ProductVariant
-class PhysicalProduct(models.Model):
- weight = models.DecimalField(max_digits=6, decimal_places=2)
+class GenericProduct(Product):
class Meta:
- abstract = True
app_label = 'product'
- def get_weight(self):
- try:
- return self.weight
- except AttributeError:
- return self.product.weight
-
-class GenericProduct(PhysicalProduct, Product):
-
- class Meta:
- app_label = 'product'
-
-
-class GenericVariant(PhysicalProduct, ProductVariant):
+class GenericVariant(ProductVariant):
class Meta:
app_label = 'product'
diff --git a/utils/create_random_data.py b/utils/create_random_data.py
index c448f3a8f2..ab773e46b3 100644
--- a/utils/create_random_data.py
+++ b/utils/create_random_data.py
@@ -40,35 +40,22 @@ def create_product(**kwargs):
'description': '\n\n'.join(fake.paragraphs(5))
}
defaults.update(kwargs)
- product = GenericProduct.objects.create(**defaults)
- if not product.base_variant:
- GenericVariant(
- name='',
- sku=fake.random_int(1, 100000),
- price=product.price,
- weight=product.weight,
- product=product).save()
- return product
+ return GenericProduct.objects.create(**defaults)
def create_variant(product, **kwargs):
defaults = {
'name': fake.word(),
'sku': fake.random_int(1, 100000),
- 'price': product.price,
'product': product,
- 'weight': product.weight,
}
defaults.update(kwargs)
return GenericVariant.objects.create(**defaults)
def create_stock(product, **kwargs):
- if product.has_variants():
- for variant in product.get_variants():
- _create_stock(variant, **kwargs)
- else:
- _create_stock(product.base_variant, **kwargs)
+ for variant in product.variants.all():
+ _create_stock(variant, **kwargs)
def _create_stock(variant, **kwargs):
@@ -80,6 +67,7 @@ def _create_stock(variant, **kwargs):
defaults.update(kwargs)
return Stock.objects.create(**defaults)
+
def create_product_image(product, placeholder_dir):
img_path = "%s/%s" % (placeholder_dir,
random.choice(os.listdir(placeholder_dir)))
@@ -102,9 +90,11 @@ def create_items(placeholder_dir, how_many=10):
for i in range(how_many):
product = create_product(collection='')
product.categories.add(default_category)
+
+ create_variant(product) # ensure at least one variant
create_product_images(product, random.randrange(1, 5), placeholder_dir)
- for _ in range(random.randrange(0, 5)):
+ for _ in range(random.randrange(1, 5)):
if random.choice([True, False]):
create_variant(product)