I am learning Python and Django and trying to create a Pilates Studio Website (as an e-commerce website, I’m following some tutorials) and I have a problem with ADD TO CART.
I don’t know why it doesn’t work. When I click the button which supposes to add a product to a cart and I inspect the website I see that there is this error:
POST http://127.0.0.1:8000/cart/add/ 500 (Internal Server Error)
`
o = o("abort");
try {
r.send(i.hasContent && i.data || null)
} catch (e) {
if (o)
throw e
}`
Please, can you help me with it? I am totally stuck!!!
I tried to add this product to a cart. I have tried to check if there are any problems with models etc. but everything looks good. I honestly have no idea what else can I do especially because I have just started learning Django and I don’t know so much about it yet.
views.py:
`def cart_summary(request):
return render(request, 'cart_summary.html', {})
def cart_add(request):
# Get the cart
cart = Cart(request)
# test for POST
if request.POST.get('action') == 'post':
# Get stuff
product_id = int(request.POST.get('product_id'))
# product_qty = int(request.POST.get('product_qty'))
# lookup product in DB
product = get_object_or_404(Product, id=product_id)
# Save to session
cart.add(product=product)
# Get Cart Quantity
cart_quantity = cart.__len__()
# Return resonse
# response = JsonResponse({'Product Name: ': product.name})
response = JsonResponse({'qty': cart_quantity})
print(response)
# messages.success(request, ("Product Added To Cart..."))
return response
else:
return HttpResponse("Invalid request method or action.", status=400)
def cart_delete(request):
pass
def cart_update(request):
pass
……………………………………….
product.html:
{% extends 'base.html' %}
{% block content %}
<div class="container my-5">
<br/>
<div class="card mb-3">
<div class="row g-0">
<div class="col-md-4">
<img src="{{ product.image.url }}" class="img-fluid rounded-start" alt="...">
</div>
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title">{{ product.name }}</h5>
<p class="card-text">{{ product.info }}</p>
<p class="card-text"><small class="text-body-secondary">Class Length: 60 minutes.</small></p>
<button type="button" value="{{ product.id }}" class="btn btn-secondary" id="add-cart">Book a class</button>
<button type="button" value="{{ product.id }}" class="btn btn-secondary">One Month Membership</button>
</div>
</div>
</div>
</div>
<br/>
</div>
<script>
$(document).on('click', '#add-cart', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url 'cart_add' %}',
data: {
product_id: $('#add-cart').val(),
product_qty: $('#qty-cart option:selected').text(),
csrfmiddlewaretoken: '{{ csrf_token }}',
action: 'post'
},
success: function(json){
console.log(json)
},
error: function(xhr, errmsg, err){
}
});
})
</script>
{% endblock %}
kitty333 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1