Django Adding to cart functionality
I have the model with the collection type and two collections. And now I am creating a button in js for it. But I am having difficulty getting the collection id and collection type into the view.
This is the Order and OrderItem model
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False, null=True, blank=False)
transaction_id = models.CharField(max_length=200, null=True)
def __str__(self):
return str(self.id)
@property
def get_cart_items(self):
orderitems = self.orderitem_set.all()
total = sum([item.quantity for item in orderitems])
return total
def get_cart_total(self):
total = 0
for item in self.orderitem_set.all():
total += item.get_total()
return total
class OrderItem(models.Model):
ORDER_ITEM_TYPE = (
('type1', 'Collection1'),
('type2', 'Collection2'),
)
order = models.ForeignKey(Order, on_delete=models.CASCADE)
collection_type = models.CharField(max_length=255, choices=ORDER_ITEM_TYPE)
collection1 = models.ForeignKey(Collection1, on_delete=models.SET_NULL, null=True, blank=True)
collection2 = models.ForeignKey(Collection2, on_delete=models.SET_NULL, null=True, blank=True)
quantity = models.IntegerField()
def get_total(self):
if self.collection_type == "type1":
return self.collection1.price * self.quantity
elif self.collection_type == "type2":
return self.collection2.price * self.quantity
This is the view that update the cart Items
def updateItem(request):
data = json.loads(request.body)
collection_id = data['collectionId']
collection_type = data['collection_type']
action = data['action']
customer = request.user.customer
if collection_type == 'type1':
collection = Collection1.objects.get(id=collection_id)
elif collection_type == 'type2':
collection = Collection2.objects.get(id=collection_id)
order, created = Order.objects.get_or_create(customer=customer, complete=False)
order_item, created = OrderItem.objects.get_or_create(order=order, collection_type=collection_type, collection1=collection, collection2=collection)
if action == 'add':
order_item.quantity += 1
elif action == 'remove':
order_item.quantity -= 1
order_item.save()
if order_item.quantity <= 0:
order_item.delete()
return JsonResponse('Item was added', safe=False)
This is the JS that update the buttons
var updateBtns = document.getElementsByClassName('update-cart')
for (i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function(){
var collectionId = this.dataset.collection
var collectionType = this.dataset.collectionType
var action = this.dataset.action
console.log('collectionId:', collectionId, 'collectionType:', collectionType, 'Action:', action)
console.log('USER:', user)
if (user == 'AnonymousUser'){
addCookieItem(collectionId, collectionType, action)
}else{
updateUserOrder(collectionId, collectionType, action)
}
})
}
function updateUserOrder(collectionId, collectionType, action){
console.log('User is authenticated, sending data...')
var url = '/update_item/'
fetch(url, {
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({'collectionId':collectionId, 'collection_type':collectionType,'action':action})
})
.then((response) => {
return response.json();
})
.then((data) => {
location.reload()
});
}
And this is the button that has the product id to be added nd data action
<button data-product="{{collection.id}}" data-action="add" class="btn btn-outline-dark add-btn update-cart">Add to Cart</button>