[Python] Django: How to dynamically update stock quantity when selecting a product variation?

Discussão em 'Python' iniciado por Stack, Março 23, 2025.

  1. Stack

    Stack Membro Participativo

    I am working on an e-commerce project where a product has multiple variations (like different colors, sizes, etc.), and each variation has its own stock. When a user selects a variation, I want to update the displayed stock dynamically, but it is not working correctly.

    Here’s my ProductStock model:

    class ProductStock(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="stocks")
    variation = models.ForeignKey(Variation, on_delete=models.CASCADE, blank=True, null=True)
    uploaded_stock_quantity = models.PositiveIntegerField(default=0)
    stock_quantity = models.PositiveIntegerField(default=0)
    reserved_stock = models.PositiveIntegerField(default=0) # For pending orders

    def available_stock(self):
    return self.stock_quantity - self.reserved_stock


    In my HTML template, I display variations as radio buttons:

    {% for v in variations %}
    <div class="variation__radio">
    <input type="radio" id="variation_{{ v.id }}" name="variation"
    onclick="updateStock(this);" value="{{ v.id }}">
    <label for="variation_{{ v.id }}">{{ v.name }}</label>
    </div>
    {% endfor %}

    <div class="stock-info">
    <span id="uploaded-stock">-</span> in stock, <span id="remaining-stock">-</span> left
    </div>


    And my JavaScript function to update stock dynamically:

    function updateStock(element) {
    var variationId = element.value;
    var stockData = JSON.parse('{{ size_stock_data|safe }}'); // Pass stock data

    if (stockData[variationId]) {
    document.getElementById("uploaded-stock").textContent = stockData[variationId].uploaded_stock_quantity;
    document.getElementById("remaining-stock").textContent = stockData[variationId].stock_quantity;
    } else {
    document.getElementById("uploaded-stock").textContent = "-";
    document.getElementById("remaining-stock").textContent = "-";
    }
    }

    Issue

    • The stock does not update when selecting a variation.
    • Sometimes, it shows incorrect values or does not change at all.

    Continue reading...

Compartilhe esta Página