Problem I want to add the product to the cart using ajax so that the page is not reloaded or refreshed and a popup is shown that the product is added to the cart.
Script
$(document).on("click",".Id_submit",function(event){
event.preventDefault();
var selector = $(this).closest(".productID")
console.log(selector.find("form").attr('action'))
$.ajax({
type : 'POST',
url: selector.find("form").attr('action'),
success: function()
{
alert("Product added to cart")
}
});
html
<form id='transactionIDValue' class="d-inline" method="post">
{{cart_product_form}}
{% csrf_token %}
<input type="submit" class="btn btn-primary shadow px-5 py-2 Id_submit" value="Add To Cart">
</form>
views.py
@require_POST
def cart_add(request, product_id):
cart = Cart(request)
product = get_object_or_404(transactions, id=product_id)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product, quantity=cd['quantity'])
print(cart)
# request.session['items_total'] = cart.product.count()
return HttpResponse('success')
urls.py
extra_patterns = [
path('add/carts/<int:product_id>/', views.cart_add, name='cart_add'),
]
urlpatterns=[
path ('add/',include(extra_patterns)),
]
Error
This is the errror I'm facing Forbidden (CSRF token missing or incorrect.): /cart/add/add/carts/16/
The issue I'm facing is that using the script it goes the cart url but the product is not added and in the console it shows that the url is forbidden. So, can someone help me with this issue please.