图像附件:当我尝试增加第二项的数量时,第一项的数量增加到2,而不是第二项的数量。
您可以观看我在此处上传的视频,以更好地了解: https://web.facebook.com/groups/1378481325739503/permalink/2373521109568848/
在此处查看视图和模板:https://codeshare.io/GLp0Rg
型号:
class Item(models.Model):
title = models.CharField(max_length=250)
price = models.IntegerField()
discount_price = models.IntegerField(null=True, blank=True)
description = HTMLField()
category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
slug = models.SlugField(unique=True,max_length=250)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("product-detail", kwargs={
'slug': self.slug
})
def get_add_to_cart_url(self):
return reverse("add-to-cart", kwargs={
'slug': self.slug
})
def get_remove_from_cart_url(self):
return reverse("remove-from-cart", kwargs={
'slug': self.slug
})
class VariationManager(models.Manager):
def all(self):
return super(VariationManager, self).filter(active=True)
def sizes(self):
return self.all().filter(category='size')
def colors(self):
return self.all().filter(category='color')
VAR_CATEGORIES = (
('size', 'size'),
('color', 'color'),
('package', 'package'),
)
class Variation(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
category = models.CharField(max_length=120, choices=VAR_CATEGORIES, default='size')
title = models.CharField(max_length=120)
active = models.BooleanField(default=True)
objects = VariationManager()
def __str__(self):
return self.title
def get_add_to_cart_url(self):
return reverse("add-to-cart", kwargs={
'slug': self.slug
})
def get_remove_from_cart_url(self):
return reverse("remove-from-cart", kwargs={
'slug': self.slug
})
class OrderItem(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
ordered = models.BooleanField(default=False)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
variation = models.ManyToManyField(Variation)
def __str__(self):
return f"{self.quantity} of {self.item.title}"
def get_total_item_price(self):
return self.quantity * self.item.price
def get_total_discount_item_price(self):
return self.quantity * self.item.discount_price
def get_amount_saved(self):
return self.get_total_item_price() - self.get_total_discount_item_price()
def get_final_price(self):
if self.item.price:#self.item.discount_price:
return self.get_total_item_price()#self.get_total_discount_item_price()
#return self.get_total_item_price()
VIEWS.PY:
def add_to_cart(request,slug):
item = get_object_or_404(Item,slug=slug)
order_item_qs = OrderItem.objects.filter(
item=item,
user=request.user,
ordered=False
)
item_var = [] #item variation
if request.method == 'POST':
for items in request.POST:
key = items
val = request.POST[key]
try:
v = Variation.objects.get(
item=item,
category__iexact=key,
title__iexact=val
)
item_var.append(v)
except:
pass
if len(item_var) > 0:
for items in item_var:
order_item_qs = order_item_qs.filter(
variation__exact=items,
)
if order_item_qs.exists():
order_item = order_item_qs.first()
order_item.quantity += 1
order_item.save()
else:
order_item = OrderItem.objects.create(
item=item,
user=request.user,
ordered=False
)
order_item.variation.add(*item_var)
order_item.save()
order_qs = Order.objects.filter(user=request.user, ordered=False)
if order_qs.exists():
order = order_qs[0]
#check if the order item is in the order
if not order.items.filter(item__id=order_item.id).exists():
order.items.add(order_item)
messages.info(request, "This item quantity was updated.")
return redirect("order-summary")
else:
ordered_date = timezone.now()
order = Order.objects.create(user=request.user, ordered_date=ordered_date)
order.items.add(order_item)
messages.info(request, "This item was added to cart.")
return redirect("order-summary")
模板(订单摘要):
{% for order_item in object.items.all %}
<div class="quantity buttons_added">
<a href="{% url 'remove-single-item-from-cart' order_item.item.slug %}"><input type="button" value="-" class="minus"></a>
<input type="number" value="{{ order_item.quantity }}" title="Qty" class="input-text qty text" size="4" pattern="" inputmode="">
<a href="{% url 'add-to-cart' order_item.item.slug %}">
<input type="button" value="+" class="plus"></a>
</div>
{% endfor %}
URLS.PY
from django.urls import path
from core.views import (
HomeView,
ItemDetailView,
OrderSummaryView,
CheckoutView,
add_to_cart,
remove_from_cart,
remove_single_item_from_cart
)
app_name = 'core'
urlpatterns = [
path('', HomeView.as_view(), name='homepage'),
path('checkout/', CheckoutView.as_view(), name='checkout'),
path('order-summary/', OrderSummaryView.as_view(), name='order-summary'),
path('product/<slug>/', ItemDetailView.as_view(), name='product'),
path('add-to-cart/<slug>/', add_to_cart, name='add-to-cart'),
path('remove-from-cart/<slug>/', remove_from_cart, name='remove-from-cart'),
path('remove-item-cart/<slug>/', remove_single_item_from_cart, name='remove-single-item-from-cart'),
]
答案 0 :(得分:0)
我认为您的模型存在根本性的问题,这使您难以完成所需的工作。
基本上,每个OrderItem
只能属于一个变体。这样您就可以轻松跟踪每个变体的quantity
。
因此,从您的Item
模型中删除OrderItem
字段,并将variation
字段设置为外键字段。使用这种模式,添加或删除变体要简单得多。只需将变体pk
传递到add_to_cart
,然后添加该过程即可。
那是基本思想;您还需要进行其他较小的更改,但是如果有任何不清楚的地方或存在其他问题,请告诉我。
这是您的OrderItem
和Variation
模型的外观:
class Variation(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
category = models.CharField(max_length=120, choices=VAR_CATEGORIES, default='size')
title = models.CharField(max_length=120)
active = models.BooleanField(default=True)
objects = VariationManager()
class OrderItem(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
ordered = models.BooleanField(default=False)
variation = models.ForeignKey(Variation, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
同样,对于您的网址,我是说get_add_to_cart_url
上的get_remove_from_cart_url
和variation
方法,我认为您应该为版本的kwarg
添加另一个id
< em>或只需传递变体的id
(无)。