Проблемы AJAX-интеграции с Django
Когда я сохраняю товары из ajax в db, он всегда перенаправляет меня на страницу с ошибкой и говорит 500 server error
views.py
from cart.cart import Cart
from django.http import JsonResponse
from django.shortcuts import render
from .models import Order, OrderItem, ShippingAddress
# Create your views here.
def checkout(request):
if request.user.is_authenticated:
try:
shipping_address = ShippingAddress.objects.get(user=request.user.id)
context = {'shipping': shipping_address}
return render(request, 'payment/checkout.html', context=context)
except:
return render(request, 'payment/checkout.html')
else:
return render(request, 'payment/checkout.html')
def complete_order(request):
if request.POST.get('action') == 'post':
name = request.POST.get('name')
email = request.POST.get('email')
address1 = request.POST.get('address1')
address2 = request.POST.get('address2')
city = request.POST.get('city')
state = request.POST.get('state')
zipcode = request.POST.get('zipcode')
print(name)
shipping_address = (address1 + "\n" + address2 + "\n" +
city + "\n" + state + "\n" + zipcode
)
cart = Cart(request)
total_cost = cart.get_total()
if request.user.is_authenticated:
order = Order.objects.create(full_name=name, email=email, shipping_address=shipping_address,
amount_paid=total_cost, user=request.user)
order_id = order.pk
for item in cart:
OrderItem.objects.create(order_id=order_id, product=item['product'], quantity=item['qty'],
price=item['price'], user=request.user)
else:
order = Order.objects.create(full_name=name, email=email, shipping_address=shipping_address,
amount_paid=total_cost)
order_id = order.pk
for item in cart:
OrderItem.objects.create(order_id=order_id, product=item['product'], quantity=item['qty'],
price=item['price'])
order_success = True
response = JsonResponse({'success':order_success})
return response
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('checkout', views.checkout, name='checkout'),
path('complete-order', views.complete_order, name='complete-order'),
path('payment-success', views.payment_success, name='payment-success'),
path('payment-failed', views.payment_failed, name='payment-failed'),
]
checkout.html
models.py
from django.contrib.auth.models import User
from django.db import models
from store.models import Product
class ShippingAddress(models.Model):
full_name = models.CharField(max_length=150)
email = models.EmailField(max_length=254)
address1 = models.CharField(max_length=150)
address2 = models.CharField(max_length=150)
city = models.CharField(max_length=50)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
state = models.CharField(max_length=255, null=True, blank=True)
zipcode = models.CharField(max_length=255, null=True, blank=True)
class Meta:
verbose_name_plural = "Shipping Address"
def __str__(self):
return 'Shipping Address - ' + str(self.id)
class Order(models.Model):
full_name = models.CharField(max_length=150)
email = models.EmailField(max_length=254)
shippingAddress = models.TextField(max_length=10000)
amount_paid = models.DecimalField(max_digits=8, decimal_places=2)
date_ordered = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
def __str__(self):
return 'Order - #' + str(self.id)
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
quantity = models.PositiveBigIntegerField(default=1)
price = models.DecimalField(max_digits=8, decimal_places=2)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
def __str__(self):
return 'Order Item - #' + str(self.id)
Если пользователь аутентифицирован и нажимает на кнопку "Завершить заказ", то он должен сохранить все товары в базу данных с именем пользователя и перенаправить на страницу успеха. Но каждый раз он перенаправляет на страницу неудачи и говорит Error 500 complete-oreder
В вашем представлении complete_order
вы создаете объекты Order
и OrderItem
. То, как вы используете order_id=order_id
при создании экземпляров OrderItem
, неверно. Поскольку поле OrderItem является ForeignKey
в Order
, вы должны передавать экземпляр Order
непосредственно, а не только его ID
. Вы должны исправить это следующим образом:
for item in cart:
OrderItem.objects.create(order=order, product=item['product'], quantity=item['qty'], price=item['price'], user=request.user)