Хотя продукт правильно добавляется в серверную часть (что я могу проверить, перейдя в панель администратора), продукт просто не отображается сразу в моей модальной корзине, что важно для того, чтобы веб-сайт выглядел хорошо. Только когда я обновляю страницу, продукт появляется в моем модальном окне. Застрял на этом последние 3 дня, понятия не имею, что делать. Может кто-нибудь помочь мне здесь? Спасибо!
Модель моей корзины:
class Cart(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='cart')
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField(default=1)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.user.username} - {self.product.name}"
Мои представления.py:
class CartView(LoginRequiredMixin, View):
def get(self, request):
cart_items = Cart.objects.filter(user=request.user)
total_price = sum(item.product.price * item.quantity for item in cart_items)
return render(request, 'business/cart.html', {'cart_items': cart_items, 'total_price': total_price})
def post(self, request):
try:
data = json.loads(request.body)
product_id = data.get('product_id')
except json.JSONDecodeError:
logger.error("Invalid JSON data in the request body")
return JsonResponse({'error': 'Invalid JSON data'}, status=400)
logger.debug(f'Received product_id: {product_id}')
if not product_id:
logger.error("No product_id provided in the request")
return JsonResponse({'error': 'No product_id provided'}, status=400)
product = get_object_or_404(Product, id=product_id)
cart_item, created = Cart.objects.get_or_create(user=request.user, product=product)
if not created:
cart_item.quantity += 1
cart_item.save()
cart_items = Cart.objects.filter(user=request.user)
cart_data = []
for item in cart_items:
cart_data.append({
'id': item.id,
'product': {
'id': item.product.id,
'name': item.product.name,
'price': float(item.product.price),
'image': item.product.image.url if item.product.image else None,
},
'quantity': item.quantity,
})
total_price = sum(item.product.price * item.quantity for item in cart_items)
logger.debug("Returning updated cart data as JSON response")
return JsonResponse({'success': True, 'items': cart_data, 'subtotal': total_price})
def get_cart_data(self, request):
logger.debug("Received request to fetch cart data")
cart_items = Cart.objects.filter(user=request.user)
cart_data = []
for item in cart_items:
cart_data.append({
'id': item.id,
'product': {
'id': item.product.id,
'name': item.product.name,
'price': float(item.product.price),
'image': str(item.product.image.url) if item.product.image else None,
},
'quantity': item.quantity,
})
total_price = sum(item.product.price * item.quantity for item in cart_items)
logger.debug(f"Returning cart data: {cart_data}")
return JsonResponse({'items': cart_data, 'subtotal': total_price})
def update_quantity(self, request):
try:
data = json.loads(request.body)
item_id = data.get('item_id')
action = data.get('action')
except json.JSONDecodeError:
return JsonResponse({'error': 'Invalid JSON data'}, status=400)
# Retrieve the cart item
cart_item = get_object_or_404(Cart, id=item_id)
if action == 'increase':
cart_item.quantity += 1
elif action == 'decrease':
if cart_item.quantity > 1:
cart_item.quantity -= 1
cart_item.save()
# Calculate total price and prepare cart data
cart_items = Cart.objects.filter(user=request.user)
cart_data = [
{
'id': item.id,
'product': {
'id': item.product.id,
'name': item.product.name,
'price': float(item.product.price),
'image': item.product.image.url if item.product.image else None,
},
'quantity': item.quantity,
}
for item in cart_items
]
total_price = sum(item.product.price * item.quantity for item in cart_items)
return JsonResponse({'success': True, 'items': cart_data, 'subtotal': total_price})
def dispatch(self, request, *args, **kwargs):
if request.method == 'POST':
if request.path == '/cart/update_quantity/':
return self.update_quantity(request, *args, **kwargs)
else:
# Handle other POST requests here
pass
elif request.method == 'GET':
if request.path == '/cart/data/':
logger.debug(f"Request Path: {request.path}")
return self.get_cart_data(request)
else:
# Handle other GET requests here
pass
# Fall back to the default behavior if the request doesn't match any of the above conditions
return super().dispatch(request, *args, **kwargs)
Мой urls.py:
urlpatterns = [
path('cart/', views.CartView.as_view(), name='cart'),
path('cart/data/', views.CartView.as_view(), name='cart_data'),
path('cart/update_quantity/', views.CartView.as_view(), name='update_quantity'),
]
Модальное окно «Моя корзина» в моей базе.html:
{% for item in cart_items %}
{{ item.product.name }}
Remove
XS/white
${{ item.product.price }}
{% endfor %}
Модальное окно моей корзины в моем main.js:
// Modal Cart
const cartIcon = document.querySelector(".cart-icon");
const modalCart = document.querySelector(".modal-cart-block");
const modalCartMain = document.querySelector(".modal-cart-block .modal-cart-main");
const closeCartIcon = document.querySelector(".modal-cart-main .close-btn");
const continueCartIcon = document.querySelector(".modal-cart-main .continue");
const addCartBtns = document.querySelectorAll(".add-cart-btn");
const openModalCart = () => {
modalCartMain.classList.add("open");
};
const closeModalCart = () => {
modalCartMain.classList.remove("open");
};
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies.trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrftoken = getCookie('csrftoken');
const addToCart = (productId) => {
const product_id = productId;
console.log('Product ID:', product_id);
fetch('/cart/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken,
},
body: JSON.stringify({ product_id }),
})
.then(response => {
if (!response.ok) {
throw new Error('Failed to add product to cart');
}
return response.json();
})
.then(data => {
if (data.success) {
console.log('Product added successfully:', data);
updateCartModalContent(); // Ensure this function is called immediately after adding the product
openModalCart();
}
})
.catch(error => console.error('Error:', error));
};
document.addEventListener("DOMContentLoaded", function() {
const plusIcons = document.querySelectorAll(".ph-plus");
const minusIcons = document.querySelectorAll(".ph-minus");
plusIcons.forEach(icon => {
icon.addEventListener("click", function() {
const itemId = icon.dataset.itemId;
updateQuantity(itemId, 'increase');
});
});
minusIcons.forEach(icon => {
icon.addEventListener("click", function() {
const itemId = icon.dataset.itemId;
updateQuantity(itemId, 'decrease');
});
});
function updateQuantity(itemId, action) {
fetch('/cart/update_quantity/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken,
},
body: JSON.stringify({ item_id: itemId, action: action }),
})
.then(response => {
if (!response.ok) {
throw new Error('Failed to update quantity');
}
return response.json();
})
.then(data => {
if (data.success) {
// Update the cart display based on the response
updateCartModalContent();
}
})
.catch(error => console.error('Error:', error));
}
});
addCartBtns.forEach((btn) => {
btn.addEventListener('click', () => {
const productId = btn.dataset.productId;
console.log('Product ID from button:', productId); // Add this line
addToCart(productId);
});
});
cartIcon.addEventListener("click", openModalCart);
modalCart.addEventListener("click", closeModalCart);
closeCartIcon.addEventListener("click", closeModalCart);
continueCartIcon.addEventListener("click", closeModalCart);
modalCartMain.addEventListener("click", (e) => {
e.stopPropagation();
});
function updateCartModalContent() {
console.log('Updating cart modal content...');
fetchCartData()
.then((cartData) => {
console.log('Cart data fetched:', cartData);
const cartItemsContainer = document.querySelector('.list-product');
cartItemsContainer.innerHTML = '';
if (cartData.items.length === 0) {
cartItemsContainer.innerHTML = '
No product in cart
';
} else {
cartData.items.forEach((item) => {
const cartItem = createCartItemElement(item);
cartItemsContainer.appendChild(cartItem);
});
}
const subtotalElement = document.querySelector('.total-cart');
const subtotal = typeof cartData.subtotal === 'number' ? cartData.subtotal : 0;
subtotalElement.textContent = `$${subtotal.toFixed(2)}`;
})
.catch((error) => {
console.error('Error fetching cart data:', error);
});
}
function fetchCartData() {
// Make an AJAX request to fetch the current cart data
return fetch('/cart/data/')
.then((response) => response.json())
.then((data) => data);
}
function createCartItemElement(item) {
console.log('Creating cart item element for:', item);
const cartItemElement = document.createElement('div');
cartItemElement.classList.add('item', 'py-5', 'flex', 'items-center', 'justify-between', 'gap-3', 'border-b', 'border-line');
cartItemElement.dataset.item = item.id;
const imageUrl = item.product.image || '/static/path/to/default-image.png';
cartItemElement.innerHTML = `
${item.product.name}
Remove
XS/white
$${item.product.price}
`;
return cartItemElement;
}
Примечание:
Это мои инструкции отладки консоли:
Product ID from button: 4
main.js:496 Product ID: 4
main.js:514 Product added successfully: Object
main.js:587 Updating cart modal content...
main.js:590 Cart data fetched: Object
main.js:623 Creating cart item element for: Object
main.js:608 Error fetching cart data: TypeError: Cannot set properties of null (setting 'textContent')
at main.js:605:35
Это мои инструкции отладки терминала:
Received product_id: 4
Returning updated cart data as JSON response
[14/May/2024 07:42:32] "POST /cart/ HTTP/1.1" 200 169
Request Path: /cart/data/
Received request to fetch cart data
Returning cart data: [{'id': 71, 'product': {'id': 4, 'name': 'Marlin Knit', 'price': 199.0, 'image': '/products/RG1.jpeg'}, 'quantity': 1}]
Подробнее здесь: https://stackoverflow.com/questions/784 ... mmediately