Skip to content

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

Handle variants in product views

Marcin Gębala96695d87e766
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.py
index 88e0b3ee02..133eb96d3b 100644
--- a/saleor/dashboard/product/forms.py
+++ b/saleor/dashboard/product/forms.py
@@ -1,5 +1,56 @@
+from django import forms
from django.forms.models import inlineformset_factory
-from ...product.models import ProductImage, Product
+from ...product.models import (ProductImage, Product, Category, ShirtVariant,
+ BagVariant, Shirt, Bag)
-ProductImageFormSet = inlineformset_factory(Product, ProductImage, extra=2)
+class ProductCategory(forms.Form):
+ category = forms.ChoiceField()
+
+ def __init__(self, *args, **kwargs):
+ super(ProductCategory, self).__init__(*args, **kwargs)
+ categories = Category.objects.all()
+ self.fields['category'].choices = [(c.slug, c.name) for c in categories]
+
+
+class ProductForm(forms.ModelForm):
+ class Meta:
+ model = Product
+ exclude = ['category']
+ fields = ['name', 'description', 'collection']
+
+ def __init__(self, *args, **kwargs):
+ super(ProductForm, self).__init__(*args, **kwargs)
+
+
+class ShirtForm(ProductForm):
+ class Meta:
+ model = Shirt
+
+
+class BagForm(ProductForm):
+ class Meta:
+ model = Bag
+
+
+ProductImageFormSet = inlineformset_factory(Product, ProductImage, extra=0)
+ShirtVariantFormset = inlineformset_factory(Shirt, ShirtVariant, extra=0)
+BagVariantFormset = inlineformset_factory(Bag, BagVariant, extra=0)
+
+
+def get_product_form_class(product):
+ if isinstance(product, Shirt):
+ return ShirtForm
+ elif isinstance(product, Bag):
+ return BagForm
+ else:
+ return ProductForm
+
+
+def get_variant_formset_class(product):
+ if isinstance(product, Shirt):
+ return ShirtVariantFormset
+ elif isinstance(product, Bag):
+ return BagVariantFormset
+ else:
+ raise ValueError('Unknown product')
diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.py
index 2834930a1b..270b2e0833 100644
--- a/saleor/dashboard/product/views.py
+++ b/saleor/dashboard/product/views.py
@@ -2,18 +2,20 @@ from django.core.urlresolvers import reverse
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.views.generic import ListView, UpdateView
+from django.views.generic.edit import FormMixin
from django.utils.translation import ugettext_lazy as _
-from ..stock.forms import StockRecordFormSet
from ..views import StaffMemberOnlyMixin
from ...product.models import Product
-from .forms import ProductImageFormSet
+from .forms import (ProductImageFormSet, ProductForm, ProductCategory,
+ get_product_form_class, get_variant_formset_class)
-class ProductListView(StaffMemberOnlyMixin, ListView):
+class ProductListView(StaffMemberOnlyMixin, ListView, FormMixin):
model = Product
paginate_by = 30
template_name = 'dashboard/product/list.html'
context_object_name = 'products'
+ form_class = ProductCategory
def get_queryset(self):
qs = super(ProductListView, self).get_queryset()
@@ -22,33 +24,51 @@ class ProductListView(StaffMemberOnlyMixin, ListView):
qs = qs.select_subclasses()
return qs
+ def get_context_data(self, **kwargs):
+ ctx = super(ProductListView, self).get_context_data(**kwargs)
+ ctx['form'] = self.form_class()
+ return ctx
+
+ def post(self, request, **kwargs):
+ form = self.form_class(request.POST)
+ if form.is_valid:
+ return HttpResponseRedirect(reverse('dashboard:product-add'))
+ return self.get(request, **kwargs)
+
class ProductView(StaffMemberOnlyMixin, UpdateView):
model = Product
template_name = 'dashboard/product/product_form.html'
image_formset = ProductImageFormSet
- stock_formset = StockRecordFormSet
+ variant_formset = None
+ form_class = ProductForm
+ context_object_name = 'product'
def __init__(self, *args, **kwargs):
super(ProductView, self).__init__(*args, **kwargs)
- self.formsets = {'image_formset': self.image_formset,
- 'stock_formset': self.stock_formset}
+ self.formsets = {'image_formset': self.image_formset}
+
+ def get_queryset(self):
+ qs = super(UpdateView, self).get_queryset()
+ qs = qs.select_subclasses()
+ return qs
def get_object(self, queryset=None):
- """
- This parts allows generic.UpdateView to handle creating products as
- well. The only distinction between an UpdateView and a CreateView
- is that self.object is None. We emulate this behavior.
- Additionally, self.product_class is set.
- """
self.creating = 'pk' not in self.kwargs
-
if self.creating:
- return None # success
+ return None
else:
product = super(ProductView, self).get_object(queryset)
+ if not self.variant_formset:
+ variant_formset_cls = get_variant_formset_class(product)
+ self.formsets['variant_formset'] = variant_formset_cls
+ self.variant_formset = variant_formset_cls
return product
+ def get_form_class(self):
+ product = self.get_object()
+ return get_product_form_class(product)
+
def get_context_data(self, **kwargs):
ctx = super(ProductView, self).get_context_data(**kwargs)
@@ -63,10 +83,6 @@ class ProductView(StaffMemberOnlyMixin, UpdateView):
return ctx
def process_all_forms(self, form):
- """
- Short-circuits the regular logic to have one place to have our
- logic to check all forms
- """
if self.creating and form.is_valid():
self.object = form.save()
@@ -75,39 +91,27 @@ class ProductView(StaffMemberOnlyMixin, UpdateView):
formsets[ctx_name] = formset_class(self.request.POST,
self.request.FILES,
instance=self.object)
+ for formset in formsets.values():
+ formset.is_valid()
- is_valid = form.is_valid() and all([formset.is_valid()
- for formset in formsets.values()])
+ is_valid = form.is_valid() \
+ and all([formset.is_valid() for formset in formsets.values()])
if is_valid:
return self.forms_valid(form, formsets)
else:
return self.forms_invalid(form, formsets)
- # form_valid and form_invalid are called depending on the validation result
- # of just the product form and redisplay the form respectively return a
- # redirect to the success URL. In both cases we need to check our formsets
- # as well, so both methods do the same. process_all_forms then calls
- # forms_valid or forms_invalid respectively, which do the redisplay or
- # redirect.
form_valid = form_invalid = process_all_forms
def forms_valid(self, form, formsets):
- """
- Save all changes and display a success url.
- """
if not self.creating:
- # a just created product was already saved in process_all_forms()
self.object = form.save()
-
- # Save formsets
for formset in formsets.values():
formset.save()
-
return HttpResponseRedirect(self.get_success_url())
def forms_invalid(self, form, formsets):
- # delete the temporary product again
if self.creating and self.object and self.object.pk is not None:
self.object.delete()
self.object = None
@@ -121,4 +125,3 @@ class ProductView(StaffMemberOnlyMixin, UpdateView):
def get_success_url(self):
return reverse('dashboard:product-update',
kwargs={'pk': self.object.pk})
-
diff --git a/saleor/dashboard/templates/dashboard/product/list.html b/saleor/dashboard/templates/dashboard/product/list.html
index 80d9925af9..b9c2e6015c 100644
--- a/saleor/dashboard/templates/dashboard/product/list.html
+++ b/saleor/dashboard/templates/dashboard/product/list.html
@@ -11,14 +11,16 @@
<div class="col-lg-12">
<h1 class="page-header">{% trans "Products" %}</h1>
- <a class="btn btn-primary" href="{% url "dashboard:product-add" %}">Add new product</a>
-
+ <form method="post" action=".">
+ {% csrf_token %}
+ {{ form }}
+ <button class="btn btn-primary" type="submit">Add new product</button>
+ </form>
<table class="table">
<thead>
<th>{% trans "Image" %}</th>
<th>{% trans "Name" %}</th>
- <th>{% trans "Brand" %}</th>
- <th>{% trans "Stock" %}</th>
+ <th>{% trans "Collection" %}</th>
<th>{% trans "Price" %}</th>
</thead>
<tbody>
@@ -32,8 +34,7 @@
{% endif %}
</td>
<td><a href="{% url 'dashboard:product-update' pk=product.pk %}">{{ product.name }}</a></td>
- <td><a href="#" title="Filter by this brand">{{ product.brand.name }}</a></td>
- <td>{{ product.get_stock }}</td>
+ <td>{{ product.collection }}</td>
<td>{% gross product.price %}</td>
</tr>
{% endfor %}
diff --git a/saleor/dashboard/templates/dashboard/product/product_form.html b/saleor/dashboard/templates/dashboard/product/product_form.html
index 989e7caac1..2474f081ea 100644
--- a/saleor/dashboard/templates/dashboard/product/product_form.html
+++ b/saleor/dashboard/templates/dashboard/product/product_form.html
@@ -17,32 +17,62 @@
<span class="glyphicon glyphicon-ok-sign"></span>
<span class="message-content">{% trans "Data saved" %}</span>
</div>
- <form method="post" action="." id="product-form" enctype="multipart/form-data">
+ <form class="form form-horizontal" method="post" action="." id="product-form" enctype="multipart/form-data">
+ {{ variant_formset.management_form }}
+ {{ image_formset.management_form }}
<div class="panel panel-default">
<div class="panel-heading">
- <span class="panel-title">{% trans "Product data" %}</span>
+ <span class="panel-title">{% trans "Details" %}</span>
</div>
<div class="panel-body">
{% csrf_token %}
- {{ form|as_vertical_form }}
+ {{ form|as_horizontal_form }}
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
- <span class="panel-title">Inventory</span>
+ <span class="panel-title">{% trans "Variants" %}</span>
+ <span class="pull-right"><a data-toggle="collapse" href="#add-variant"><i class="glyphicon glyphicon-plus"></i> Add variant</a></span>
</div>
<div class="panel-body">
- {{ stock_formset.as_p }}
+ <table class="table">
+ <thead>
+ <tr>
+ {% for field in variant_formset.0 %}
+ <th>{{ field.label }}</th>
+ {% endfor %}
+ </tr>
+ </thead>
+ <tbody>
+ {% for form in variant_formset.initial_forms %}
+ <tr>
+ {% for field in form %}
+ <td>{{ field }}</td>
+ {% endfor %}
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
- <span class="panel-title">Images</span>
+ <span class="panel-title">{% trans "Images" %}</span>
+ <span class="pull-right"><a data-toggle="collapse" href="#add-image"><i class="glyphicon glyphicon-plus"></i> Add image</a></span>
</div>
<div class="panel-body">
- {{ image_formset.as_p }}
+ <table class="table">
+ <tbody>
+ {% for form in image_formset %}
+ <tr>
+ {{ form }}
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+
</div>
</div>