При входе в систему в качестве пользователя корзина не очищается после завершения транзакции через paypal в моем проекте Django. Она работает, когда пользователь не вошел в систему
Недавно я закончил серию уроков на YouTube от Денниса Айви по созданию сайта коммерции на основе Django . Мой сайт работает, за исключением одной серьезной ошибки. Когда пользователь вошел в систему и проходит через процесс оформления заказа, корзина не очищается после завершения оформления заказа через paypal. Когда пользователь не зарегистрирован ("AnonymousUser"), все работает правильно. Я изо всех сил пытаюсь найти источник этой ошибки. Есть какие-нибудь предложения? Я включаю части кода, которые, по моему мнению, могут иметь значение.
cart.js
var updateBtns = document.getElementsByClassName('update-cart')
for (i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function(){
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId:', productId, 'Action:', action)
console.log('USER:', user)
if (user == 'AnonymousUser'){
addCookieItem(productId, action)
}else{
updateUserOrder(productId, action)
}
})
}
function updateUserOrder(productId, 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({'productId':productId, 'action':action})
})
.then((response) => {
return response.json();
})
.then((data) => {
location.reload()
});
}
function addCookieItem(productId, action){
console.log('User is not authenticated')
if (action == 'add'){
if (cart[productId] == undefined){
cart[productId] = {'quantity':1}
}else{
cart[productId]['quantity'] += 1
}
}
if (action == 'remove'){
cart[productId]['quantity'] -= 1
if (cart[productId]['quantity'] <= 0){
console.log('Item should be deleted')
delete cart[productId];
}
}
console.log('CART:', cart)
document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/"
location.reload()
}
function updateUserOrder(productId, action){
console.log('User is logged in, sending data...')
var url = '/update_item/'
fetch(url, {
method: 'POST',
headers:{
'Content-Type':'application/json',
"X-CSRFToken": csrftoken,
},
body:JSON.stringify({'productId': productId, 'action':action})
})
.then((response) => {
if (!response.ok) {
// error processing
throw 'Error';
}
return response.json()
})
.then((data) => {
console.log('data:', data)
location.reload()
});
}
checkout.html
views.py
from django.shortcuts import render
from django.http import JsonResponse
import datetime
import json
from .models import *
from .utils import cookieCart, cartData, guestOrder
# Create your views here.
def store(request):
data = cartData(request)
cartItems = data['cartItems']
order = data['order']
items = data['items']
products = Product.objects.all()
context = {'products':products, 'cartItems': cartItems}
return render(request, 'store/store.html', context)
def cart(request):
data = cartData(request)
cartItems = data['cartItems']
order = data['order']
items = data['items']
context = {'items':items, 'order':order, 'cartItems': cartItems, 'shipping':False}
return render(request, 'store/cart.html', context)
def checkout(request):
data = cartData(request)
cartItems = data['cartItems']
order = data['order']
items = data['items']
context = {'items':items, 'order':order, 'cartItems': cartItems, 'shipping':False}
return render(request, 'store/checkout.html', context)
def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
print('Action:', action)
print('productId:', productId)
customer = request.user.customer
product = Product.objects.get(id=productId)
order, created = Order.objects.get_or_create(customer=customer, complete=False)
orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)
if action == 'add':
orderItem.quantity = (orderItem.quantity + 1)
elif action == 'remove':
orderItem.quantity = (orderItem.quantity - 1)
orderItem.save()
if orderItem.quantity <= 0:
orderItem.delete()
return JsonResponse('Item was added', safe=False)
def processOrder(request):
transaction_id = datetime.datetime.now().timestamp()
data = json.loads(request.body)
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
else:
customer, order = guestOrder(request, data)
total = float(data['form']['total'])
order.transaction_id = transaction_id
if total == order.get_cart_total:
order.complete = True
order.save()
if order.shipping == True:
ShippingAddress.objects.create(
customer=customer,
order=order,
address=data['shipping']['address'],
city=data['shipping']['city'],
state=data['shipping']['state'],
zipcode=data['shipping']['zipcode'],
)
return JsonResponse('Payment complete!', safe=False)
utils.py
import json
from . models import *
def cookieCart(request):
try:
cart = json.loads(request.COOKIES['cart'])
except:
cart = {}
print('Cart:', cart)
items = []
order = {'get_cart_total':0, 'get_cart_items':0}
cartItems = order['get_cart_items']
for i in cart:
try:
cartItems += cart[i]["quantity"]
product = Product.objects.get(id=i)
total = (product.price * cart[i]['quantity'])
order['get_cart_total'] += total
order['get_cart_items'] += cart[i]['quantity']
item = {
'product':{
'id':product.id,
'name':product.name,
'price':product.price,
'imageURL':product.imageURL,
},
'quantity':cart[i]['quantity'],
'get_total':total
}
items.append(item)
if product.digital == False:
order['shipping'] = True
except:
pass
return {'cartItems':cartItems, 'order':order, 'items':items}
def cartData(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
cookieData = cookieCart(request)
cartItems = cookieData['cartItems']
order = cookieData['order']
items = cookieData['items']
return {'cartItems':cartItems, 'order':order, 'items':items}
def guestOrder(request, data):
print("User is not logged in...")
print('Cookies:', request.COOKIES)
name = data['form']['name']
email = data['form']['email']
cookieData = cookieCart(request)
items = cookieData['items']
customer, created = Customer.objects.get_or_create(
email=email,
)
customer.name = name
customer.save()
order = Order.objects.create(
customer=customer,
complete=False
)
for item in items:
product = Product.objects.get(id=item['product']['id'])
orderItem = OrderItem.objects.create(
product = product,
order=order,
quantity=item['quantity']
)
return customer, order
Полагаю, я исправил это. Поле цены в модели продукта было десятичным полем (DecimalField), поэтому итог с лицевой стороны не совпадал с итогом с обратной стороны. Я сделал следующее и, кажется, все работает.
def processOrder(request):
transaction_id = datetime.datetime.now().timestamp()
data = json.loads(request.body)
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
else:
customer, order = guestOrder(request, data)
total = float(data['form']['total'])
order.transaction_id = transaction_id
# ВОТ КАК Я ЭТО ИСПРАВИЛ##
orderFL = float(order.get_cart_total) #the solution
if total == orderFL:
order.complete = True
order.save()
if order.shipping == True:
ShippingAddress.objects.create(
customer=customer,
order=order,
address=data['shipping']['address'],
city=data['shipping']['city'],
state=data['shipping']['state'],
zipcode=data['shipping']['zipcode'],
)
return JsonResponse('Payment complete!', safe=False)