AJAX 与 Django 集成出现问题

问题描述 投票:0回答:1

当我将产品从 ajax 保存到数据库时,它总是将我重定向到失败页面并显示 500 服务器错误

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

url.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'),

]

结帐.html


{% include "store/base.html" %}


{% load static %}


{% block content %}

<style>
    
    body 
    {
        
        background-color: gray;
    
    }


</style>


    <body>

        <br>

        <div class="container bg-white shadow-md p-5" style="width:500px; border-radius:20px;">

            <form id="form" onsubmit="event.preventDefault();">

                <div>

                    <h3> <i class="fa fa-chevron-circle-right" aria-hidden="true"></i> &nbsp; Complete your order </h3>

                    <p> Please enter in the relevant information below. </p>
 


                    <hr>

                    <br>

                    <div class="form-field">
                    
                        <input class="form-control validate" id="name" type="text" placeholder="Full name*" autocomplete="off" value="{{shipping.full_name}}" required>

                    </div>


                    <br>


                    <div class="form-field">

                        <input class="form-control validate" id="email" type="email" placeholder="Email address*" autocomplete="off" value="{{shipping.email}}" required>

                    </div>

                    
                    <br>

                    
                    <div class="form-field">

                        <input class="form-control validate" id="address1" type="text" placeholder="Address 1*" autocomplete="off" value="{{shipping.address1}}" required>

                    </div>


                    <br>


                    <div class="form-field">

                        <input class="form-control validate" id="address2" type="text" placeholder="Address 2*" autocomplete="off" value="{{shipping.address2}}" required>

                    </div>


                    <br>


                    <div class="form-field">

                        <input class="form-control validate" id="city" type="text" placeholder="City*" autocomplete="off" value="{{shipping.city}}" required>

                    </div>


                    <br>


                    <div class="form-field">

                        <input class="form-control" id="state" type="text" placeholder="State (Optional)" autocomplete="off" value="{{shipping.state}}">

                    </div>


                    <br>


                    <div class="form-field">

                        <input class="form-control" id="zipcode" type="text" placeholder="Zip code (Optional)" autocomplete="off" value="{{shipping.zipcode}}">

                    </div>
            
                </div>

                <br>



            <button id="complete-order" class="btn btn-primary navbar-btn text-white"> &nbsp; Complete order </button>
            

                <br>

            </form>


        </div>

        

        <br>


    </body>

    <script>

        $(document).on('submit', function(e) {
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: '{% url "complete-order" %}',
                data: {
                    name: $('#name').val(),
                    email: $('#email').val(),
                    address1: $('#address1').val(),
                    address2: $('#address2').val(),
                    city: $('#city').val(),
                    state: $('#state').val(),
                    zipcode: $('#zipcode').val(),
                    csrfmiddlewaretoken: "{{csrf_token}}",
                    action: 'post'
                },
                success: function(json) {
                    window.location.replace("{% url 'payment-success' %}");
                },
                error: function(xhr, errmsg, err) {
                    window.location.replace("{% url 'payment-failed' %}");
                }
            });
        });
        </script>
        
{% endblock %}

模型.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)

如果用户通过身份验证并单击“完成订单”,它应该使用用户名将所有产品保存到数据库并重定向到成功页面。但每次它都会重定向到失败页面并显示错误 500 完成订单

django ajax
1个回答
0
投票

在您的

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)
© www.soinside.com 2019 - 2024. All rights reserved.