I am working on ecommerce website. I wanted to implement wishlist function on my website. And, it is working if its the first time for user that is adding to the list. In the second time giving an error. What's the problem? Can someone please help me? views.py
def addWishlistView(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
print('Action:', action)
print('Product:', productId)
user = request.user
product = Product.objects.get(id=productId)
if (Wishlist.objects.filter(user=user) and Wishlist.objects.filter(product=product)).exists():
print("Item is exists")
else:
Wishlist.objects.create(user=user,product=product)
return JsonResponse('Item was added', safe=False)
models.py
class Wishlist(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, verbose_name="Название товара")
user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True)
script js
for (i = 0; i < wishlist.length; i++) {
wishlist[i].addEventListener('click', function(){
var productId = this.dataset.product
var action = this.dataset.action
if (user == 'AnonymousUser'){
Console.log("Not logged in");
}else{
addToWishlist(productId, action)
}
})
}
function addToWishlist(productId, action){
console.log('User is authenticated, sending data...')
var url = '/add_wishlist/'
fetch(url, {
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({'productId':productId, 'action':action})
})
.then((data) => {
location.reload()
})
}