So I’ll preface this question by stating I think the error could be in a few places though the most likely, especially according to the windows command prompt is SyntaxError: Invalid syntax on this line
response = JsonResponse(data={'Product Name: ': str(product.name)}, status=201)
full code in context of the file down below. Though there maybe another culprit causing the the code to go awry. I suspect my javascript and jquery is so weak that I can’t notice I’m not grabbing the identifier of the DOM element like I think I’m doing in jquery
here’s the urls file
from django.urls import path
from . import views
urlpatterns = [
path('', views.cart_summary, name="cart_summary"),
path('add', views.cart_add, name="cart_add"),
path('delete/', views.cart_delete, name="cart_delete"),
path('update/', views.cart_update, name="cart_update"),
]
here’s the view in question
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'))
# lookup product in DB
product = get_object_or_404(Product, id=product_id)
print(product.name)
# Save to session
cart.add(product=product)
print("Successfully returned from cart object add function... added new product to cart")
# Return Response
response = JsonResponse(data={'Product Name: ': str(product.name)}, status=201)
return response
Here’s the cart object and add function including the init for the cart object
class Cart():
def __init__(self, request):
self.session = request.session
# Get the current session key if it exists
cart = self.session.get('session_key')
# If the user is new, no session key! Create one!
if 'session_key' not in request.session:
cart = self.session['session_key'] = {}
# Make sure cart is available on all pages of site
self.cart = cart
def add(self, product):
product_id = str(product.id)
if product_id in self.cart:
pass
else:
print("In cart object add function product id:" + product_id)
print("Same place product price: " + str(product.price))
self.cart[product_id] = {'price', str(product.price)}
print("Trying to set session modification token to true")
self.session.modified = True
Lastly here’s my template
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="container">
<br/><br/>
<div class="card mb-8" style="max-width: 720px;">
<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">
<center>
<h5 class="card-title">{{ product.name }}</h5>
<p class="card-text">{{ product.description }}</p>
{% if product.is_sale %}
<!-- Sale -->
<div class="d-flex justify-content-center small text-warning mb-2">
<div class="bi-star-fill"></div>
<span class="text-dark"> Sale </span>
<div class="bi-star-fill"></div>
</div>
<!-- Product price-->
<strike>${{product.price}}</strike>
${{product.sale_price}}
<br/> ID: {{product.id}}
{% else %}
${{product.price}}
{% endif %}
<br/><br/>
<a href="{% url 'home' %}" class="btn btn-secondary">
Home
</a>
<button type=button value="{{ product.id}}" class="btn btn-secondary" id="add-cart">Add to Cart</button>
</center>
</div>
</div>
</div>
</div>
<br/><br/>
<br/><br/>
<br/><br/>
<br/><br/>
</div>
<script>
// Check if Button pressed
$(document).on('click', '#add-cart', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url 'cart_add' %}',
data: {
product_id: $('#add-cart').val(),
csrfmiddlewaretoken: '{{ csrf_token }}',
action: 'post'
},
success: function(json){
console.log(json)
},
error: function(xhr, errmsg, err) {
}
});
})
</script>
{% endblock %}
there’s a script in base.html to include jquery, here’s a snippet of that code
<script
src="https://code.jquery.com/jquery-3.7.1.min.js"
integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
crossorigin="anonymous"></script>
When I inspect the ajax after clicking on the button here’s what I see
$.ajax({
type: 'POST',
url: '/cart/add',
data: {
product_id: $('#add-cart').val(),
csrfmiddlewaretoken: 'uSwH0Uyb5rrOXmDHWnd0DjpRmHfWUqsyD0aqU3YqdlV5EnFA9NvvdDRyBcHMq7SZ',
action: 'post'
},
to my amatuer eyes product_id should read an integer of what the product ID is, so I don’t know if all this is an error where jquery isn’t interperting like I expect.