Update the status of a buy a product button when we have more than one of that product in page with JavaScript in a Django app

I am Tring to update a buy button base of the quantity of the colors on that product in my django app with javaScript my code is working if i have one from that item in my page but some where in code when i have some swiper to show favorite products must sell products or must see products i have same item in diffrent places and when i try to chnage the color of the products it change the first one of the kind of this prodcut in page i have this view to check the product color quantity :

def quantity_of_product_with_color(request):
    color_id = request.GET.get('color')
    try:
        product_color = ProductColor.objects.get(id=color_id)
        data = {
            'in_stock': product_color.quantity > 0,
            'quantity': product_color.quantity
        }
    except ProductColor.DoesNotExist:
        data = {
            'in_stock': False,
            'quantity': 0
        }

    return JsonResponse(data)

and for exampel i have this html code :

{% for item in discounted_products %}
    <div class="swiper-slide">
        <div class="product-box">
            <div class="product-timer">
                <div class="timer-label">
                    <span>{{ item.discount }}% تخفیف</span>
                </div>
                <div class="timer">
                    <div class='countdown'
                         data-date="{{ item.offer_end.date|date_convertor }}"
                         data-time="{{ item.offer_end.time|time_convertor }}">
                    </div>
                </div>
            </div>
            <div class="product-image">
                <img src="{{ item.images.all.0.image.url }}" loading="lazy"
                     alt="{{ item.images.all.0.image_alt }}"
                     class="img-fluid p-2">
            </div>
            <div class="product-title">
                <div class="title">
                    <p class="text-overflow-1">{{ item.name }}</p>
                    <span class="text-muted text-overflow-1"></span>
                </div>

                <div class="rating">
                    <div class="number"><span
                            class="text-muted font-12">({{ item.get_score_count }}) {{ item.get_total_score }}</span>
                    </div>
                    <div class="icon"><i class="bi bi-star-fill"></i></div>
                </div>
            </div>
            <div class="product-meta-color-items">
                {% for color in item.colors.all %}
                    <input type="radio" class="btn-check color-radios"
                           name="color-options-{{ item.id }}"
                           id="color_{{ item.id }}_{{ color.id }}"
                           value="{{ color.id }}"
                           data-product-id="{{ item.id }}"
                           data-color-id="{{ color.id }}"
                           autocomplete="off"
                            {% if forloop.counter == 1 %} checked {% endif %}>
                    <label class="btn"
                           for="color_{{ item.id }}_{{ color.id }}">
                        <span style="background-color: {{ color.color }};"></span>
                        {{ color.get_color_display }}
                    </label>
                {% endfor %}
            </div>
            <div class="product-action">
                <div class="price">
                    <p class="new-price">3,175,000 تومان</p>
                    <p class="old-price">6,500,000 تومان</p>
                </div>
                <div class="link">
                    <a href="" class="btn border-0 rounded-3 main-color-one-bg buy-btn">
                        <i class="bi bi-basket text-white"></i>
                        <span class="text-white">خرید محصول</span>
                    </a>
                </div>
            </div>
        </div>
    </div>

{% endfor %}
<div class="parent">
    <div class="container-fluid">
        <div class="swiper product-slider-swiper">
            <div class="swiper-wrapper">
                {% for product, id in products.items %}
                    <div class="swiper-slide">
                        <div class="product-box">
                            <div class="product-timer">
                                {% if product.discount %}
                                    <div class="timer-label">

                                        <span>  {{ product.discount }}% تخفیف </span>

                                    </div>
                                {% else %}
                                    <div class="">

                                        <span>&nbsp </span>

                                    </div>
                                {% endif %}
                                {% with user_like=product.user_likes.all %}
                                    <div class="product-header-btn">
                                        <a href="#" class="like-btn button" data-id="{{ product.id }}"
                                           data-action="{% if request.user in product.user_likes.all %}un{% endif %}like"
                                           data-bs-title="افزودن به علاقه مندی ها">
                                            {% if request.user not in product.user_likes.all %}
                                                <i class="bi bi-heart"></i>
                                            {% else %}
                                                <i class="bi bi-heart-fill text-danger"></i>
                                            {% endif %}
                                        </a>

                                    </div>
                                {% endwith %}
                            </div>
                            <div class="product-image">
                                {% for image in product.images.all %}
                                    {% if forloop.counter <= 2 %}
                                        <img src="{{ image.image.url }}" loading="lazy" alt="{{ image.image_alt }}"
                                             class="img-fluid{% if forloop.counter == 1 %} one-image {% else %} two-image {% endif %}">
                                    {% endif %}
                                {% endfor %}
                            </div>
                            <div class="product-title">
                                <div class="title">
                                    <p class="text-overflow-1">{{ product.name }}</p>
                                    <span class="text-muted text-overflow-1"></span>
                                </div>
                                <div class="rating">
                                    <div class="number"><span
                                            class="text-muted font-12">({{ product.score|length }}+) {{ product.get_total_score }}</span>
                                    </div>
                                    <div class="icon"><i class="bi bi-star-fill"></i></div>
                                </div>
                            </div>

                            <div class="product-meta-color-items">
                                {% for color in product.colors.all %}
                                    <input type="radio" class="btn-check color-radios"
                                           name="color-options-{{ product.id }}"
                                           id="color_{{ product.id }}_{{ color.id }}"
                                           value="{{ color.id }}"
                                           data-product-id="{{ id }}"
                                           data-color-id="{{ color.id }}"
                                           autocomplete="off"
                                            {% if forloop.counter == 1 %} checked {% endif %}>
                                    <label class="btn" for="color_{{ product.id }}_{{ color.id }}">
                                        <span style="background-color: {{ color.color }};"></span>
                                        {{ color.get_color_display }}
                                    </label>
                                {% endfor %}
                            </div>
                            <div class="product-action">
                                {% if product.discount != 0 %}
                                    <div class="price">
                                        <p class="new-price">{{ product.get_discounted_price|intcomma }} تومان</p>
                                        <p class="old-price">{{ product.price|intcomma }} تومان</p>
                                    </div>
                                {% else %}
                                    <div class="price text-center">
                                        <p class="new-price">{{ product.price|intcomma }} تومان</p>
                                        <p class="old-price">&nbsp;</p>
                                    </div>
                                {% endif %}
                                <div class="link">
                                    {% if product.available %}
                                        <a href="" class="btn border-0 rounded-3 main-color-one-bg buy-btn">
                                            <i class="bi bi-basket text-white"></i>
                                            <span class="text-white">خرید محصول</span>
                                        </a>
                                    {% else %}
                                        <a href="" class="btn border-0 rounded-3 btn-danger disabled">
                                            <i class="bi bi-basket text-white"></i>
                                            <span class="text-white">اتمام موجودی</span>
                                        </a>
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                    </div>
                {% endfor %}
            </div>
            <div class="swiper-button-next"></div>
            <div class="swiper-button-prev"></div>
        </div>
    </div>
</div>

so i write this JS code my knowldge about js is very low :

document.addEventListener('DOMContentLoaded', function () {
    // Attach event listener to body once to avoid duplication
    document.body.addEventListener('change', function (event) {
        if (event.target.classList.contains('color-radios')) {
            const productId = event.target.getAttribute('data-product-id');
            alert(productId);
            const colorId = event.target.value;

            const url = `${shopUrl}?color=${colorId}`;


            fetch(url)
                .then(response => response.json())
                .then(data => {

                    const productContainer = document.querySelector(`.buy-btn[data-product-id="${productId}"]`);


                    if (productContainer) {
                        if (data.in_stock) {
                            productContainer.classList.remove('btn-danger', 'disabled');
                            productContainer.classList.add('main-color-one-bg');
                            productContainer.innerHTML = `<i class="bi bi-basket text-white"></i> <span class="text-white">خرید محصول</span>`;
                        } else {
                            productContainer.classList.add('btn-danger', 'disabled');
                            productContainer.classList.remove('main-color-one-bg');
                            productContainer.innerHTML = `<i class="bi bi-basket text-white"></i> <span class="text-white">اتمام موجودی</span>`;
                        }
                    }
                })
                .catch(error => console.error('Error:', error));
        }
    });
});

as i said before when i have one from same product in a page it works fine but when i have more than one its not i know there will be problem with id or data-product-id but i cant solve this problem

Вернуться на верх