django 404错误当尝试添加项目到购物车上的详细信息页面

kadbb459  于 2023-01-06  发布在  Go
关注(0)|答案(3)|浏览(121)

编辑我发现了这个问题,所以当我在基本网站上单击“添加”时,绝对URL只是base/updateItem,但当我转到详细信息页面时,URL是/detail/3/updateItem

我正在创建一个在线商店。在基本URL(127.0.0.1:8000)上,我可以直接将“推荐”产品添加到购物车。但是当我进入包含该产品详细信息(图片、描述等)的页面并尝试从 there 添加到购物车时,我在127.0.0.1:8000/detail/1/updateItem处收到404错误。

cart.js(我怀疑错误就在这里):

var updateBtn = document.getElementsByClassName("update-cart")

for (i = 0; i < updateBtn.length; i++){
    updateBtn[i].addEventListener('click', function(){
        var productId = this.dataset.product
        var action    = this.dataset.action
        console.log(productId,action)
        console.log(user)
        if (user === "AnonymousUser"){
            console.log("user not logged in")
        }else{
           updateUserOrder(productId, action)
        }
    })
}
function updateUserOrder(productId, action){
    console.log("user created an order")

    var url = 'updateItem'

    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()
    })
}

网址.py

path('updateItem', views.updateItem, name='updateItem'),
path('cart', views.cartDetail, name='cart'),

查看次数.py

def cartDetail(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()
    else:
        order = {'get_cart_total':0,} 
        items = []
    print(items)
    context ={
        'items':items,
        'orders':order,
    }

    return render(request,'cart.html',context)

def updateItem(request):
    data = json.loads(request.body)
    productId = data['productId']
    action = data['action']
    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 or action=='delete':
        orderItem.delete()

    return JsonResponse("item was added", safe=False)

型号.py

class Order(models.Model):
    customer        = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
    date_oredred    = models.DateField(auto_now_add=True)
    complete        = models.BooleanField(default=False, null=True, blank=True)
    transaction_id  = models.CharField(max_length=200, null=True)

    def __str__(self):
        return str(self.id)

    @property
    def get_cart_total(self):
        items = self.orderitem_set.all()
        total = sum([x.get_total for x in items])
        return total

    

class OrderItem(models.Model):
    product     = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True)
    order       = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
    quantity    = models.IntegerField(default=0, null=True, blank=True)
    date_added  = models.DateTimeField(auto_now_add=True)

    @property
    def get_total(self):
        if self.product.pricePromo is None:
            total = self.product.priceNormal * self.quantity
        else:
            total = self.product.pricePromo * self.quantity
        
        return total

如果我缺少任何代码,请告诉我。

gg0vcinb

gg0vcinb1#

urls.py中,将/添加到updateItem的末尾
urls.py

path('updateItem/', views.updateItem, name='updateItem'),

并在函数updateUserOrder中将变量url更改为/updateItem/

function updateUserOrder(productId, action){
    
    var url = '/updateItem/'
ql3eal8s

ql3eal8s2#

在cart.js中,我已将url更改为绝对路径,它可以正常工作

lmvvr0a8

lmvvr0a83#

绝对路径的含义如下&这是404错误的解决方案.. var url = '/updateItem/'

相关问题