[Python] Django 5 views function doesn't accept the POST request that I wrote with javascript...

Discussão em 'Python' iniciado por Stack, Fevereiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    My problem: DoesNotExist at /cart/cart_add

    product = Products.objects.get(id=product_id)


    because product_id equals None

    When I try to get product_id in request.POST it's value equals None

    I know Django but I don't now Javascript.

    Perhaps there is a mistake in the Javascript file? This code that works with Django 4 (I use Django 5):

    jquery-ajax.js

    $(document).ready(function () {
    var successMessage = $("#jq-notification");
    $(document).on("click", ".add-to-cart", function (e) {
    e.preventDefault();
    var goodsInCartCount = $("#goods-in-cart-count");
    var cartCount = parseInt(goodsInCartCount.text() || 0);
    var product_id = $(this).data("product-id");
    var add_to_cart_url = $(this).attr("href");
    $.ajax({
    type: "POST",
    url: add_to_cart_url,
    data: {
    product_id: product_id,
    csrfmiddlewaretoken: $("[name=csrfmiddlewaretoken]").val(),
    },
    success: function (data) {
    successMessage.html(data.message);
    successMessage.fadeIn(400);
    setTimeout(function () {
    successMessage.fadeOut(400);
    }, 7000);
    cartCount++;
    goodsInCartCount.text(cartCount);
    var cartItemsContainer = $("#cart-items-container");
    cartItemsContainer.html(data.cart_items_html);
    },
    error: function (data) {
    console.log("text");
    },
    });
    });


    catalog.html

    <a href="{% url "cart:cart_add" %}" class="btn add-to-cart" data-product-id="{{ product.id }}">
    {% csrf_token %}
    <img class="mx-1" src="{% static "deps/icons/cart-plus.svg" %}" alt="Catalog Icon" width="32" height="32">


    views.py

    def cart_add(request):

    product_id = request.POST.get("product_id")
    product = Products.objects.get(id=product_id)
    user_cart = get_user_carts(request)
    cart_items_html = render_to_string(
    "carts/includes/included_cart.html", {'carts': user_cart}, request=request
    )
    response_data = {
    'masage': 'Тext',
    'cart_items_html': cart_items_html,
    }
    return JsonResponse(response_data)

    Continue reading...

Compartilhe esta Página