I’m new to django and I am trying to implement a cart functionality using Django sessions. The issue comes in where any order added to cart is stored in the database and whenever I start the site all the orders will be displayed in the cart table. Another issue is when I try to remove items from the cart I get the error HTTP error 405.
Here are some of the related code snippets.
#Views.py
class Cart(View):
def get(self, request, *args, **kwargs):
cart_item_ids = request.session.get(‘cart’, )
cart_items = CartModel.objects.filter().prefetch_related('items')
total_price = 0
for cart_item in cart_items:
total_price += cart_item.price
context = {
'cart_items': cart_items,
'total_price': total_price,
}
print("gCart Item IDs: ", cart_item_ids)
print("gCart Items: ", cart_items)
return render(request, 'customer/cart.html', context)
@staticmethod
def add_to_cart(request):
if request.method == 'POST':
# Get the selected items from the form
selected_items = request.POST.getlist('items[]')
# validate selected item IDs
valid_ids = MenuItem.objects.values_list('id', flat=True)
selected_items = [int(item_id) for item_id in selected_items if int(item_id) in valid_ids]
# proceed only if at least one valid item ID is selected
if selected_items:
# create a new CartModel instance
cart = CartModel(price=0, is_paid=False)
cart.save()
items = MenuItem.objects.filter(id__in=selected_items)
cart.items.set(items)
# Calculate the total price of the cart
total_price = items.aggregate(Sum('price'))['price__sum'] or 0
cart.price = total_price
cart.save()
# Initialize the cart in the session if it doesn't exist
if 'cart' not in request.session:
request.session['cart'] = []
# Add the selected items to the cart
for item_id in selected_items:
request.session['cart'].append(item_id)
print("aSelected Items:", selected_items)
print("aSession data:", request.session.get('cart'))
print("aCart Item IDs: ", list(cart.items.values_list('id', flat=True)))
print("aCart Items: ", list(cart.items.all()))
return redirect('cart')
def remove_from_cart(request):
if request.method == 'POST':
try:
if 'remove_item' in request.POST:
# Remove an individual item from the cart
item_id = int(request.POST['remove_item'])
print(f"Removing item with ID: {item_id}")
# Retrieve the cart items from the session
cart = request.session.get('cart', [])
# Remove the item with the given item_id from the cart
if str(item_id) in cart:
cart.remove(str(item_id))
# Delete the record from the database using CartModel
CartModel.objects.filter(id=item_id).delete()
# Update the cart in the session
request.session['cart'] = cart
print("Item removed successfully")
else:
print("Item not found in the cart")
elif 'selected_items' in request.POST:
# Remove selected items from the cart
selected_items = request.POST.getlist('selected_items')
print(f"Removing selected items: {selected_items}")
# Retrieve the cart items from the session
cart = request.session.get('cart', [])
for item_id in selected_items:
if str(item_id) in cart:
cart.remove(str(item_id))
# Delete the record from the database using CartModel
CartModel.objects.filter(id=item_id).delete()
# Update the cart in the session
request.session['cart'] = cart
print("Selected items removed successfully")
else:
print("Invalid form submission")
except ValueError:
print("Invalid Item ID")
else:
print("Invalid HTTP method")
return redirect('cart')
#Models.py
class CartModel(models.Model):
items = models.ManyToManyField(MenuItem, related_name=‘carts’, blank=True)
price = models.DecimalField(max_digits=7, decimal_places=2)
is_paid = models.BooleanField(default=False)
#for cart items
class CartItemModel(models.Model):
cart = models.ForeignKey(CartModel, on_delete=models.CASCADE)
items = models.ForeignKey(‘MenuItem’, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
Cart.html
{% extends ‘customer/base.html’ %}
{% block content %}
Your Cart
<form method="post" >
{% csrf_token %}
<table class="table table-striped">
<thead>
<tr>
<th>Contents</th>
<th>Price</th>
<th>Action</th>
<th>Select</th>
</tr>
</thead>
<tbody>
{% for cart_item in cart_items %}
<tr>
<td>
{% for item in cart_item.items.all %}
{{ item.name }}<br>
{% endfor %}
</td>
<td>
{{ cart_item.price }}
</td>
<td>
<button type="submit" name="remove_item" value="{{ cart_item.pk }}" class="btn btn-danger">Remove</button>
</td>
<td>
<input type="checkbox" name="selected_items[]" value="{{ cart_item.pk }}">
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="text-right">
<button type="submit" class="btn btn-danger">Remove Selected</button>
</div>
</form>
<h3>Total Price: {{ total_price|floatformat:2 }}</h3>
<a href="{% url 'order' %}" class="btn btn-dark mt-3">Place new order</a>
<a href="{% url 'checkout' %}" class="btn btn-dark">Checkout</a>
</div>
</div>
{% endblock content %}