Skip to content

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

Make checking quantity on adding to cart work with new models

Marcin Gębala36f85476d079
diff --git a/saleor/cart/forms.py b/saleor/cart/forms.py
index 962919094b..2fcc3394e9 100644
--- a/saleor/cart/forms.py
+++ b/saleor/cart/forms.py
@@ -54,7 +54,7 @@ class AddToCartForm(forms.Form):
self.cart.check_quantity(
product_variant, new_quantity, None)
except InsufficientStock as e:
- remaining = e.item.stock - used_quantity
+ remaining = e.item.get_stock_quantity() - used_quantity
if remaining:
msg = self.error_messages['insufficient-stock']
else:
@@ -91,7 +91,7 @@ class ReplaceCartLineForm(AddToCartForm):
self.cart.check_quantity(self.product, quantity, None)
except InsufficientStock as e:
msg = self.error_messages['insufficient-stock']
- raise forms.ValidationError(msg % {'remaining': e.item.stock})
+ raise forms.ValidationError(msg % {'remaining': e.item.get_stock_quantity()})
return quantity
def clean(self):
diff --git a/saleor/product/models/base.py b/saleor/product/models/base.py
index b6dfb87d44..eb1943f8c5 100644
--- a/saleor/product/models/base.py
+++ b/saleor/product/models/base.py
@@ -16,7 +16,7 @@ from jsonfield import JSONField
from model_utils.managers import InheritanceManager
from mptt.managers import TreeManager
from mptt.models import MPTTModel
-from satchless.item import ItemRange, Item
+from satchless.item import ItemRange, Item, InsufficientStock
from unidecode import unidecode
from versatileimagefield.fields import VersatileImageField
@@ -162,6 +162,14 @@ class ProductVariant(models.Model, Item):
def get_weight(self):
return self.weight_override or self.product.weight
+ def check_quantity(self, quantity):
+ available_quantity = sum([stock.quantity for stock in self.stock.all()])
+ if quantity > available_quantity:
+ raise InsufficientStock(self)
+
+ def get_stock_quantity(self):
+ return sum([stock.quantity for stock in self.stock.all()])
+
def get_price_per_item(self, discounts=None, **kwargs):
price = self.price_override or self.product.price
if discounts: