当我尝试以访客身份将产品添加到购物车时,我得到以下错误:
Page not found (404)
No Session matches the given query.
Request Method: POST
Request URL: http://127.0.0.1:8000/store/la-fleur-fily-suvignuion/
Raised by: shop.views.Product
Using the URLconf defined in lafleurlily.urls, Django tried these URL patterns, in this order:
admin/
[name='home']
about/ [name='about_us']
near_me/ [name='find_near_me']
contact-us/ [name='contact_us']
store/ [name='all_products']
store/ category/wines/ [name='wine_category']
store/ category/sparkling/ [name='sparkling_category']
store/ <slug:wine_slug>/ [name='each_wine']
The current path, store/la-fleur-fily-suvignuion/, matched the last one.
You’re seeing this error because you have DEBUG = True in your Django settings
file. Change that to False, and Django will display a standard 404 page.
字符串
订单/views.py:
class CartPage(View):
template = 'orders/cart.html'
def get(self, request):
session_key = request.session.session_key
session = get_object_or_404(Session, session_key=session_key)
cart = get_object_or_404(Cart, session=session)
items = CartItem.objects.filter(cart_items=cart)
def item_total():
summ = 0
for each in items:
print(each.product.price, each.quantity)
summ = summ + each.product.price * each.quantity
return float(summ)
context = {
'cart': cart,
'item': items,
'item_total': item_total()
}
return render(request, self.template, context)
型
商店/views.py:
class Product(View): #SubscribePost,
template = 'shop/product.html'
model = Wine
def get(self, request, wine_slug):
product = get_object_or_404(self.model, slug=wine_slug)
context = {'wine': product}
return render(request, self.template, context=context)
def post(self, request, wine_slug):
action = request.POST.get('action')
if action == 'add_to_cart':
return self.add_to_cart(request, wine_slug)
def add_to_cart(self, request, wine_slug):
session_key = request.session.session_key
if session_key is None:
request.session.create()
session = get_object_or_404(Session, session_key=session_key)
product = Wine.objects.get(slug=wine_slug)
cart, created = Cart.objects.get_or_create(session=session)
cart_item, item_created = CartItem.objects.get_or_create(cart_items=cart, product=product)
if cart_item:
cart_item.quantity += 1
cart_item.save()
return redirect('cart')
型
订单/models.py:
class Cart(models.Model):
session = models.ForeignKey(Session, null=True, blank=True, on_delete=models.CASCADE)
items = models.ManyToManyField('CartItem', null=True, default=None)
date_generation = models.DateField(auto_now=True)
def __str__(self):
return str(self.date_generation)
class CartItem(models.Model):
cart_items = models.ForeignKey(Cart, on_delete=models.CASCADE)
product = models.ForeignKey(Wine, on_delete=models.PROTECT)
quantity = models.IntegerField(default=0)
def __str__(self):`
return str(self.pk)
型
我希望没有帐户的用户也能够添加到购物车。
2条答案
按热度按时间nukf8bse1#
你肯定能做到。同样的事情也发生在我身上。我解决了这个问题,而不是使用这个代码:
字符串
这一个:
型
你现在有会议。在我的情况下,我解决了这个问题。我希望被证明是有帮助的。
lnvxswe22#
它仍然不工作,并给我给予whis错误:
字符串