我使用python 3.7和Django 2.2.3
我正在为我的网站创建一个交流购物车系统,但是我看不到我的购物车项目。我在URL的模式中使用product.id,但似乎不起作用。 这是我的网站购物车,我想要在单击“添加到购物车”按钮后,将其添加到购物车并显示我的购物车页面。 我通过在URL模式中使用product.id和views.py中的update_cart()视图来尝试此操作。
我使用"{% url 'update_cart' product.id %}"
在产品页面中单击“添加到购物车”。
我使用"{% for item in cart.products_list.all %}"
在购物车页面中显示购物车项目。
views.py
def cart_view(request):
cart=Cart.objects.all()[0]
return render(request,'products/cart.html',{'cart':cart})
def update_cart(request,product_id):
cart=Cart.objects.all()[0]
try:
product=Products.objects.get(id=product_id)
except Products.DoesNotExist:
pass
if not product in cart.products_list.all():
cart.products_list.add(product)
else:
cart.products_list.remove(product)
return HttpResponseRedirect("cart")
urls.py
from django.urls import path,include
from . import views
urlpatterns = [
path('create/',views.create,name='create'),
path('<int:product_id>/',views.detail,name='detail'),
path('cart',views.cart_view,name='cart'),
path('cart/update/<int:product_id>/',views.update_cart,name='update_cart')
models.py:
class Cart(models.Model):
products_list=models.ManyToManyField(Products,null=True,blank=True)
total=models.IntegerField(default=0)
date=models.DateTimeField(auto_now_add=False,auto_now=True)
isPaid=models.BooleanField(default=False)
def count_cart_items(self):
return int(self.cart_items)
class Products(models.Model):
category_id=models.ForeignKey(Products_Cat,on_delete=models.CASCADE)
creator=models.ForeignKey(User, on_delete=models.CASCADE)
title=models.CharField(max_length=250)
price=models.IntegerField(default=0)
description=models.TextField()
slug=models.SlugField()
image=models.ImageField(upload_to='images/')
isOff=models.BooleanField(default=False)
我希望看到我的购物车能够正常工作,并向我显示购物车,但是我没有看到任何错误的结果。任何人都可以帮忙吗?
答案 0 :(得分:0)
您需要具有唯一的网址,这两个网址是相同的:
path('<int:product_id>/',views.detail,name='detail'),
path('<int:product_id>/',views.update_cart,name='update_cart')
所以您需要更改它,
并且最好创建多个urlpattern进行分类
例如:
urlpatterns = [
path('cart/', views.cart_view, name='list_cart'),
path('cart/create/', views.create, name='create_cart'),
path('cart/detail/<int:product_id>/', views.detail, name='detail_cart'),
path('cart/update/<int:product_id>/', views.update_cart, name='update_cart'),
]