My problem: DoesNotExist at /cart/cart_add/
When I try get product_id in request.POST
it`s value = None
Learn django but don`t now JS.
Perhaps:
Mistake in JS file
This code work with django4 (use django5)
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)