Сеанс Django создает новый сеансовый ключ при каждом обновлении страницы, что приводит к дублированию корзин.Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Сеанс Django создает новый сеансовый ключ при каждом обновлении страницы, что приводит к дублированию корзин.

Сообщение Anonymous »

Я работаю над приложением Django, которое использует сеансы пользователей для управления корзинами покупок. Однако каждый раз, когда я обновляю страницу, генерируется новый сеансовый ключ, что приводит к созданию новой корзины. Это приводит к появлению нескольких корзин для одного и того же пользователя/сеанса, чего не должно быть. Я пытаюсь понять, почему Django создает новый сеанс при каждом обновлении страницы.
При перезагрузке /products в серверной части django создается несколько сеансов

Код: Выделить всё

[16/Sep/2024 17:11:31] "GET /api/products/ HTTP/1.1" 200 212
Session key: iedrvaus89536ly57pb242tnalwtx7vo
[16/Sep/2024 17:11:31] "GET /api/carts/retrieve_cart/ HTTP/1.1" 200 107
[16/Sep/2024 17:11:31] "GET /api/products/ HTTP/1.1" 200 212
Session key: eipxdrmkf343fjtkchk7ads14ef1vccr
[16/Sep/2024 17:11:31] "GET /api/carts/retrieve_cart/ HTTP/1.1" 200 107
Если я нажму «Добавить в корзину», будут созданы две корзины:

Код: Выделить всё

    {
"id": 77,
"items": [
{
"id": 66,
"product": 1,
"product_sku": "MNT-MST-MDL-HRV",
"product_name": "Monthly Harvest Box",
"product_price": 50.0,
"quantity": 1
}
],
"created_at": "2024-09-16T20:10:24.950541Z",
"updated_at": "2024-09-16T20:10:24.950541Z"
},
{
"id": 78,
"items": [],
"created_at": "2024-09-16T20:10:25.006548Z",
"updated_at": "2024-09-16T20:10:25.006548Z"
}
Вот ProductsPage.js

Код: Выделить всё

import React, { useState, useEffect } from "react";
import './ProductsPage.css';
import Cart from './Cart';
import PictureGrid from "./PictureGrid";

const ProductsPage = () => {
const [products, setProducts] = useState([]);
const [cartItems, setCartItems] = useState([]);
const [cart, setCart] = useState(null);  // Cart starts as null
const [total, setTotal] = useState(0);
const [loadingCart, setLoadingCart] = useState(true);  // For managing loading state

// Fetch products from the Django API
useEffect(() => {
fetch('http://localhost:8000/api/products/')
.then(response => response.json())
.then(data => setProducts(data))
.catch(error => console.error('Error fetching products:', error));
}, []);

// Retrieve or create the cart for the current session
useEffect(() => {
if (!cart) {
loadCart();  // Load the cart for the current session
}
}, [cart]);

// Load cart items for the current session
const loadCart = () => {
setLoadingCart(true);  // Set loading state to true while loading cart
fetch(`http://localhost:8000/api/carts/retrieve_cart/`)
.then(response => response.json())
.then(cartData => {
setCart(cartData.id);  // Set the cart ID
setCartItems(cartData.items);  // Set cart items
calculateTotal(cartData.items);  // Calculate the total
setLoadingCart(false);  // Set loading state to false after loading cart
})
.catch(error => {
console.error('Error fetching cart data:', error);
setLoadingCart(false);  // Set loading state to false even if there's an error
});
};

// Calculate total price of the cart
const calculateTotal = (items) => {
const totalPrice = items.reduce((sum, item) => {
const itemPrice = parseFloat(item.product_price);
return sum + (itemPrice * item.quantity);
}, 0);
setTotal(totalPrice);
};

// Function to handle adding a product to the cart
const addToCart = (productSku) => {
if (!cart) {
console.error('Cart not defined yet.  Try again later.');
return;
}

console.log('Adding product with SKU:', productSku);

fetch(`http://localhost:8000/api/carts/${cart}/add_item`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ sku: productSku, quantity: 1 }),
})
.then(response => response.json())
.then(data => {
console.log('Product added to cart:', data);

// Reload the cart after adding the item
loadCart();
})
.catch(error => console.error('Error adding product to cart:', error));
};

// Function to handle removing a product from the cart
const removeFromCart = (productSku) => {
if (!cart) {
console.error('Cart not defined yet. Try again later.');
return;  // Prevent the function from running if cart is not yet defined
}

console.log('Removing product with SKU:', productSku);

fetch(`http://localhost:8000/api/carts/${cart}/remove_item/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ sku: productSku }),
})
.then(response => {
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
}
return response.json();
})
.then(data => {
console.log('Item removed from cart:', data);
const updatedCartItems = cartItems.filter(item => item.product_sku !== productSku);
setCartItems(updatedCartItems);  // Update the cart items after removal
calculateTotal(updatedCartItems);  // Recalculate the total
})
.catch(error => console.error('Error removing item from cart:', error));
};

return (

Our Subscriptions

{products.map(product => (

[img]{[/img]
{product.name}
Price: ${product.price}
 addToCart(product.sku)} disabled={loadingCart}>
{loadingCart ? 'Loading...' : 'Add to Cart'}

SKU: {product.sku}

))}


{/* Include the Cart component */}


);
};

export default ProductsPage;
Все работало, пока я не перевел тележки на работу через сеанс. Что я делаю не так?

Подробнее здесь: https://stackoverflow.com/questions/789 ... -duplicate
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Создайте сеансовый ключ продавца в Opayo для быстрой оплаты
    Гость » » в форуме Php
    0 Ответы
    67 Просмотры
    Последнее сообщение Гость
  • Android Paging 3 приводит к дублированию строк
    Anonymous » » в форуме Android
    0 Ответы
    25 Просмотры
    Последнее сообщение Anonymous
  • Почему использование EF Core приводит к дублированию значений идентификаторов?
    Anonymous » » в форуме C#
    0 Ответы
    10 Просмотры
    Последнее сообщение Anonymous
  • Почему использование EF Core приводит к дублированию значений идентификаторов?
    Anonymous » » в форуме C#
    0 Ответы
    6 Просмотры
    Последнее сообщение Anonymous
  • Изменение значения раскрывающегося списка приводит к дублированию страниц на страницах бритвы.
    Anonymous » » в форуме C#
    0 Ответы
    11 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Python»