【发布时间】:2020-01-04 14:22:11
【问题描述】:
我使用 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)
我想看到我的购物车正常工作并向我展示购物车,但我没有看到没有错误的结果。有人可以帮忙吗?
【问题讨论】:
-
谁能帮忙?
-
您的 URL 模式函数是什么样的?