gpt4 book ai didi

python - 将产品添加到购物车无法正常工作

转载 作者:行者123 更新时间:2023-12-04 12:19:34 27 4
gpt4 key购买 nike

我遇到了代码问题,一个更具体的错误,那就是当我第一次将一个项目添加到购物车时(比如绿色和中等版本),它被很好地添加了。然后当我添加另一个项目(假设蓝色和小)时,它也可以工作。但是,当我从 order_summary.html 增加项目数量时,它增加了另一个项目的数量,而不是我点击的项目(如果我点击了红色和中号,蓝色和大号的数量会增加)并说:请指定所需的变化。为什么会这样?还值得注意的是,当我从我的单个产品页面添加具有相同变体的相同项目时,它工作正常。我认为这个错误的发生是因为我的观点的编写方式。我试图自己解决它,但我迷路了。任何人都可以帮我吗?提前致谢!

我的models.py:

class Item(models.Model):
title = models.CharField(max_length=120)
price = models.FloatField()

class Variation(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
name = models.CharField(max_length=50) # size, color

class ItemVariation(models.Model):
variation = models.ForeignKey(Variation, on_delete=models.CASCADE)
value = models.CharField(max_length=50) # small, medium large etc

class OrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
item_variations = models.ManyToManyField(ItemVariation)
quantity = models.IntegerField(default=1)
ordered = models.BooleanField(default=False)

class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
ref_code = models.CharField(max_length=20)
ordered = models.BooleanField(default=False)
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add= True)
ordered_date = models.DateTimeField()

我的意见.py:
@login_required
def add_to_cart(request, slug):
item = get_object_or_404(Item, slug=slug)
variations = request.POST.getlist('variations', [])
print(variations)
print(request.POST)
minimum_variation_count = Variation.objects.filter(item=item).count()
print(minimum_variation_count)
print(len(variations))
if len(variations) < minimum_variation_count:
messages.info(request, "Please specify the required variations.")


order_item_qs = OrderItem.objects.filter(
item=item,
user= request.user,
ordered=False,
)

for v in variations:
print(v)
order_item_qs = order_item_qs.filter(
item_variations__value=v
)

if order_item_qs.exists():
order_item = order_item_qs.first()
order_item.quantity += 1
# messages.success(request, "Product quantity was updated.")
order_item.save()
else:
order_item = OrderItem.objects.create(
item=item,
user= request.user,
ordered=False,
)

# order_item.item_variations.add(*variations)
item_variations_to_add = ItemVariation.objects.filter(
variation__item=item,
value__in=variations
).values_list('id', flat=True)
order_item.item_variations.add(*item_variations_to_add)
order_item.save()

order_qs = Order.objects.filter(user=request.user, ordered=False)
if order_qs.exists():
order = order_qs[0]
if not order.items.filter(item__id=order_item.id).exists():
order.items.add(order_item)
# print(request.POST.getlist('variations', None))
messages.success(request, "Product added to cart.")
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)
# print(request.POST.getlist('variations', None))
messages.success(request, "Product added to cart.")
return redirect("order-summary")
return redirect("order-summary")


@login_required
def remove_single_item_from_cart(request, slug):
item = get_object_or_404(Item, slug=slug)
variations = request.POST.getlist('variations', [])
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 order.items.filter(item__slug=item.slug).exists():
order_item = OrderItem.objects.filter(
item=item,
user=request.user,
ordered=False
)[0]
if order_item.quantity > 1:
order_item.quantity -= 1
order_item.save()
messages.info(request, "Product quantity was updated.")
else:
order.items.remove(order_item)
order_item.delete()
messages.info(request, "Product was removed from cart.")
return redirect("order-summary")
else:
messages.info(request, "Product was not in your cart")
return redirect("product", slug=slug)
else:
messages.info(request, "You do not have an active order")
return redirect("product", slug=slug)
return redirect("order-summary")

我的 order_summary.html(我可以在其中增加数量):

<th scope="row" class="border-0">
<div class="p-2">
<img src="{{ order_item.item.image_url }}" alt="" width="70" class="img-fluid rounded shadow-sm">
<div class="ml-3 d-inline-block align-middle">
<h5 class="mb-1"> <a href="{{ order_item.item.get_absolute_url }}" class="text-dark
-inline-block align-middle">{{ order_item.item.title }}</a>
{% for var in order_item.item_variations.all %}
<!-- <h6>{{ order_item.item_variations.all }}</h6> -->
<!-- <ul> -->
<!-- <li><h6>{{ var.variation.name }}: {{ var.value }}</h6></li> -->
<!-- </ul> -->
<h6>{{ var.variation.name }}: {{ var.value }}</h6>
{% endfor %}
</div>
</div>
</th>
{% if order_item.item.discount_price %}
<td class="border-0 align-middle"><strong>${{ order_item.get_total_discount_item_price }} <span class="badge badge-warning">Saving ${{ order_item.get_amount_saved }}</span></strong></td>
{% else %}
<td class="border-0 align-middle"><strong>${{ order_item.get_total_item_price }}</strong></td>
{% endif %}
<td class="border-0 align-middle"><strong>
<div class="pull-center">
<a href="{% url 'remove-single-item-from-cart' order_item.item.slug %}" class="btn mr-2"><i class="fa fa-minus"></i></a>
{{ order_item.quantity }}<a href="{% url 'add-to-cart' order_item.item.slug %}" class="btn ml-2"><i class="fa fa-plus"></i></a>
</div>
</div>
</strong></td>
<td class="border-0 align-middle"><a href="{% url 'remove-from-cart' order_item.item.slug %}" class="text-dark"><i class="fa fa-trash"></i></a></td>
</tr>


我的 single_product.html(我可以从这里增加我的产品数量,并且它工作正常):
<form class="form" method="POST" action="{{ object.get_add_to_cart_url }}">
{% csrf_token %}
{% for var in object.variation_set.all %}
<h5>Choose {{ var.name }}</h5>
<select class="form-control mb-4 col-md-4" name="variations">
{% for item in var.itemvariation_set.all %}
<option value="{{ item.value }}">{{ item.value|capfirst }}</option>
{% endfor %}
</select>
{% endfor %}


<div class="action">
<button class="btn btn-success">Add to Cart</button>
<button class="like btn btn-danger" type="button"><span class="fa fa-heart"></span></button>
</div>
</form>

我的 admin.py:
from django.contrib import admin
from .models import Item, Variation, ItemVariation


class ItemVariationAdmin(admin.ModelAdmin):
list_display = ['variation',
'value']

list_filter = ['variation', 'variation__item']
search_fields = ['value']


class ItemVariationInLineAdmin(admin.TabularInline):
model = ItemVariation
extra = 1


class VariationAdmin(admin.ModelAdmin):
list_display = ['item',
'name']
list_filter = ['item']
search_fields = ['name']
inlines = [ItemVariationInLineAdmin]

admin.site.register(Item)
admin.site.register(ItemVariation, ItemVariationAdmin)
admin.site.register(Variation, VariationAdmin)

我的 urls.py:
path('add_to_cart/<slug>/', orders_views.add_to_cart, name='add-to-cart'),
path('remove_from_cart/<slug>/', orders_views.remove_from_cart, name='remove-from-cart'),

最佳答案

  • 我希望 variations为空,因为您不是通过 POST 请求发送,也不是从您的 html 表单发送任何变体输入。这就是您获得 "Please specify the required variations." 的原因信息。 ( len(variations) == 0 )
  • 因为 variations为空,for v in variations没有做任何过滤工作。所以当你到达 order_item_qs.first() ,您不一定会得到您期望的 OrderItem,并且可能是 +=1在错误的 OrderItem 上。

  • 修理:
  • 最简单的方法是添加 increase_quantity url 端点,您可以在其中将 OrderItem id 传递到 View 中。这样您就可以确切地知道要增加数量的 OrderItem,并且不需要进行任何过滤来找到它。
  • 否则,您需要弄清楚如何将变体发送到 View 。如果使用 POST,那么您希望使用某种输入。如果 GET,那么您可以附加 url 或类似的内容。 (我强烈建议作为 POST 请求发送。)
  • 关于python - 将产品添加到购物车无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61673413/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com