From 101cb2db638f9aab17c235f518ee17cc33602dea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=AD=C3=B0ir=20Valberg=20Gu=C3=B0mundsson?= Date: Wed, 27 Mar 2019 20:25:06 +0100 Subject: [PATCH] Check stock when incrementing orderproduct quantity. --- src/shop/templates/shop_index.html | 8 ++++++-- src/shop/views.py | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/shop/templates/shop_index.html b/src/shop/templates/shop_index.html index c0915e5d..d7b9e072 100644 --- a/src/shop/templates/shop_index.html +++ b/src/shop/templates/shop_index.html @@ -55,9 +55,13 @@ Shop | {{ block.super }} {{ product.name }} - {% if product.stock_amount and product.left_in_stock <= 10 %} + {% if product.stock_amount %}
- Only {{ product.left_in_stock }} left! + {% if product.left_in_stock == 0 %} + Sold out! + {% elif product.left_in_stock <= 10 %} + Only {{ product.left_in_stock }} left! + {% endif %}
{% endif %} diff --git a/src/shop/views.py b/src/shop/views.py index 7eaa9fba..1c97e9c6 100644 --- a/src/shop/views.py +++ b/src/shop/views.py @@ -335,6 +335,20 @@ class OrderDetailView(LoginRequiredMixin, EnsureUserOwnsOrderMixin, EnsureOrderH order_product_id = str(order_product.pk) if order_product_id in request.POST: new_quantity = int(request.POST.get(order_product_id)) + + if order_product.quantity < new_quantity: + # We are incrementing and thus need to check stock + incrementing_by = new_quantity - order_product.quantity + if incrementing_by > order_product.product.left_in_stock: + messages.error( + request, + "Sadly we only have {} '{}' left in stock.".format( + order_product.product.left_in_stock, + order_product.product.name, + ) + ) + return super(OrderDetailView, self).get(request, *args, **kwargs) + order_product.quantity = new_quantity order_product.save() order.customer_comment = request.POST.get('customer_comment') or ''