1

I have following products in the database: enter image description here

Html code for the above image:

{% for crops_ordered_names,crops_ordered_images,crops_ordered_cost,crops_ava in total %}
    <tbody>
    <tr>
        <td data-th="Product">
            <div class="row">
                <div class="col-sm-2 hidden-xs"><img alt="..." class="img-responsive" src="http://placehold.it/100x100"/>
                </div>
                <div class="col-sm-10">
                    <h4 class="nomargin">{{crops_ordered_names}}</h4>
                    <p>Available amount: {{crops_ava}}</p>
                </div>
            </div>
        </td>
        <td data-th="Price" data-type="price">{{crops_ordered_cost}}</td>
        <td data-th="Quantity">
            <input class="form-control text-center" data-type="quan" max="{{crops_ava}}" min="1" type="number">
        </td>
        <td class="text-center" data-th="Subtotal" data-type="subtotal"></td>
        <td class="actions" data-th="">
            <a href="{% url 'shopping_cart:delete_item' crops_ordered_names%}">
                <button class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>
            </a>
        </td>
    </tr>
    </tbody>

How can I send the value quantity of each item to the django views to store quantity of each item to the respective product when I submit the form after entering all the quantities. I need to get value of quantity from the HTML code:

<input type="number" class="form-control text-center" data-type="quan"  min="1" max="{{crops_ava}}" >
Vishal Singh
  • 6,014
  • 2
  • 17
  • 33
SAI SANTOSH CHIRAG
  • 2,046
  • 1
  • 10
  • 26
  • I guess `Django-Extra-Views` would solve your problem, check this thread https://stackoverflow.com/questions/37634959/django-how-do-i-create-a-view-to-update-multiple-records-on-an-intermediate-mod – Tariq Yousef Jul 13 '20 at 19:52

2 Answers2

2

I was working on something similar. And I've used ajax to update the quantity. I'm not very good at explaining things, but I tried.

Get the quantity of the unique item using id="quantity{{item.id}}

<div style="flex:1">
    <p id="quantity{{ item.id }}" class="align-content-center quantity">{{ item.quantity }}</p>
    <div class="quantity_btns">
        <img height="15" width="15" class="chg-quantity update_cart" data-product="{{ item.id }}" data-action="add" src="{% static  'images/arrow-up.png' %}">
        <img height="15" width="15" class="chg-quantity update_cart" data-product="{{ item.id }}" data-action="remove" src="{% static  'images/arrow-down.png' %}">
    </div>
</div>

And below is the ajax code.

let update_cart = document.getElementsByClassName('update_cart');

for (var i = 0; i < update_cart.length; i++) {
    update_cart[i].addEventListener('click', function() {
        var data_action = $(this).data('action');

        var product_id = $(this).data('product');
        let quantity = document.getElementById('quantity' + product_id);

        $.ajax({
            url:'/test_add_cart_button',
            data:{
                'data_action':data_action,
                'product_id':product_id,
            },
            success: function(data){

                quantity.innerHTML = data.item_quantity;
            }
        });
    });
}

Little summary of above code. We get all the elements with class "update_cart". Loop through all the elements. Get the attribute value of data-action which contains add/remove action. Then get the attribute data-product(which contains the {{ item.id }}). Get the quantity of the product the using getElementById('quantity' + product_id). Where the product_id will be retrieved from the data-product. Then in the ajax, we send the value we captured in a key to send it to our view.

def test_add_cart_button(request):
clicked = request.GET.get('data_action')
product_id = request.GET.get('product_id')
item = CartItem.objects.get(id=product_id, user=request.user)

if clicked == 'add':
    item.quantity += 1
    item.save()

elif clicked == 'remove':
    item.quantity -= 1

    if item.quantity <= 0:
        remove_from_cart(request, item.id)
return JsonResponse({'item_quantity':item.quantity,}, safe=False)

With data_action and product_id keys. We can use them in our view by request.GET.get('data_action') and request.GET.get('product').

Dharman
  • 30,962
  • 25
  • 85
  • 135
0

its quite similar my projects. I think this code help you

models.py

class OrderItem(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    ordered = models.BooleanField(default=False)
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)

    def __str__(self):
        return f"{self.item.product_title} No. of quantity : {self.quantity}"

    def get_total_item_price(self):
        return self.quantity * self.item.product_price

    def get_total_discount_item_price(self):
        return self.quantity * self.item.product_discount_price

    def get_amount_saved(self):
        return self.get_total_item_price() - self.get_total_discount_item_price()

    def get_final_price(self):
        if self.item.product_discount_price:
            return self.get_total_discount_item_price()
        return self.get_total_item_price()

views.py

class Cartview(LoginRequiredMixin, View):
    def get(self, *args, **kwargs):
        try:
            order = Order.objects.get(user=self.request.user, ordered=False)
            context = {
                'object': order
            }
            return render(self.request, 'cart.html', context)
        except ObjectDoesNotExist:
            messages.warning(self.request, "You do not have an active order")
            return redirect("/")

Jinja template with for looping

  <tbody>
                                {% for order_item in object.items.all %}
                                <tr class="text-center">
                                    <td class="product-remove"><span style=color:burlywood; class="badge badge-light">{{forloop.counter}}</span></td>
                                    <td class="image-prod">
                                        <div class="img" style="background-image:url({{order_item.item.product_image.url}});"></div>
                                    </td>

                                    <td class="product-name">
                                        <h3>{{order_item.item.product_title}}</h3>
                                        <p>{{order_item.item.product_description}}</p>
                                    </td>

                                    <td class="price">
                                        {% if order_item.item.product_offer %}
                                        <span class="ml-2 price-sale">&#x20b9; {{order_item.item.product_discount_price}}</span> {% else %}
                                        <span class="price-sale">&#x20b9; {{order_item.item.product_price}}</span> {% endif %}
                                    </td>

                                    <td class="quantity">
                                        <div class="input-group mb-3">
                                            <a href="{% url 'public:remove-single-item-from-cart' order_item.item.product_slug %}" class="minus">-</a>
                                            <input type="text" name="quantity" class="quantity form-control input-number" value="{{ order_item.quantity }}">
                                            <a href="{% url 'public:add-to-cart' order_item.item.product_slug %}" class="plus">+</a>
                                        </div>
                                    </td>

                                    <td class=" total ">
                                        {% if order_item.item.product_offer %} &#x20b9; {{ order_item.get_total_discount_item_price }}
                                        <span class="badge badge-info">Saving &#x20b9; {{ order_item.get_amount_saved }}</span> {% else %} &#x20b9;{{ order_item.get_total_item_price }} {% endif %}
                                    </td>
                                    <td class="product-remove"><a href="{% url 'public:remove-from-cart' order_item.item.product_slug %}"><span class="ion-ios-close"></span></a></td>
                                    {% empty %}
                                    <tr>
                                        <td colspan='6'>Your cart is empty</td>
                                    </tr>
                                </tr>
                                {% endfor %}
                                <!-- END TR-->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="row justify-content-start ">
                <div class="col col-lg-5 col-md-6 mt-5 cart-wrap ftco-animate ">
                    {% if object.get_total %}
                    <div class="cart-total mb-3 ">
                        <h3>Cart Totals</h3>
                        <p class="d-flex ">
                            <span>Subtotal</span>
                            <span>{{object.get_total}}</span>
                        </p>
                        <p class="d-flex ">
                            <span>Delivery</span>
                            <span>0.00</span>
                        </p>
                        <p class="d-flex ">
                            <span>Discount</span>
                            <span>0.00</span>
                        </p>
                        <hr>
                        <p class="d-flex total-price ">
                            <span>Total</span>
                            <span> &#x20b9; {{object.get_total}}</span>
                        </p>
                    </div>
                    {% endif %}

follow this Django build-in functions documents

Ravi
  • 28
  • 1
  • 9