从 Django 中的篮子功能中删除项目

问题描述 投票:0回答:0

我最近在我的 Django 电子商务网站上修改了我的购物篮,以获取产品的多种变体。除了 views.py 中的 remove item 方法外,我已经完成了所有工作。它会删除具有相同产品 ID 的所有项目。我无法弄清楚如何获得识别购物篮中商品变体的方法。这是我在 views.py 中的函数:

def remove_from_basket(request, item_id):
    """Remove the item from the shopping basket"""

    try:
        product = get_object_or_404(Product, pk=item_id)
        item = None
        if 'product_item' in request.POST:
            flavour = request.POST['product_flavour']
            strength = request.POST['product_strength']
            product_item = request.POST['product_item']
            item = f'{item_id}_{flavour}_{strength}'
        print(item)
        basket = request.session.get('basket', {})

        if item:
            del basket[item_id]['items_by_variation'][item]
            if not basket[item_id]['items_by_variation']:
                basket.pop(item_id)
            messages.success(request, (f'Removed 'f'{product.name} flavour {flavour.upper()} from your basket'))
            print('test 1')
        else:
            basket.pop(item_id)
            messages.success(request, f'Removed {product.name} from your basket')
            print('test 2')

        request.session['basket'] = basket
        return HttpResponse(status=200)

    except Exception as e:
        messages.error(request, f'Error removing item: {e}')
        return HttpResponse(status=500)

这之前在 Django html 模板中使用了一些 Javscript。我已重命名锚标记中的数据属性并更新了 JS。这是模板代码的完整部分:

{% for item in basket_items %}
<tr>
  <td class="p-3 w-25">
    {% if product.image %}
    <a href="{{ product.image.url }}" target="_blank">
      <img class="img-fluid rounded" src="{{ item.product.image.url }}">
    </a>
    {% else %}
    <a href="">
      <img class="img-fluid rounded" src="{{ MEDIA_URL }}noimage.png">
    </a>
    {% endif %}

  </td>
  <td class="py-3">
    <p class="my-0"><strong>{{ item.product.name }}</strong></p>
    <p class="my-0"><strong>Flavour:
                                </strong>{% if item.product.has_flavours %}{{ item.flavour|upper }}{% else %}N/A{% endif %}
    </p>
    <p class="my-0"><strong>Strength:
                            </strong>{% if item.product.has_strength %}{{ item.strength|upper }}{% else %}N/A{% endif %}
    </p>
    <p class="my-0 small text-muted">SKU: {{ item.product.sku|upper }}</p>
  </td>
  <td class="py-3">
    <p class="my-0">£{{ item.product.price }}</p>
  </td>
  <td class="py-3 w-25">
    <form class="form update-form" method="POST" action="{% url 'adjust_basket' item.item_id %}" ">
                                {% csrf_token %}
                                <div class="form-group ">
                                    <div class="input-group ">
                                        <div class="input-group-prepend ">
                                            <button class="decrement-qty btn btn-sm btn-black rounded-0 "
                                                data-item_id="{{ item.item_id }} " id="decrement-qty_{{ item.item_id }} ">
                                                <span>
                                                    <i class="fas fa-minus fa-sm "></i>
                                                </span>
                                            </button>
                                        </div>
                                        <input class="form-control form-control-sm qty_input " type="number "
                                            name="quantity " value="{{ item.quantity }} " min="1 " max="99 "
                                            data-item_id="{{ item.item_id }} " id="id_qty_{{ item.item_id }} ">
                                        <div class="input-group-append ">
                                            <button class="increment-qty btn btn-sm btn-black rounded-0 "
                                                data-item_id="{{ item.item_id }} " id="increment-qty_{{ item.item_id }} ">
                                                <span>
                                                    <i class="fas fa-plus fa-sm "></i>
                                                </span>
                                            </button>
                                        </div>
                                        {% if item.product.has_flavours and item.product.has_strength %}
                                        <input type="hidden " name="product_item " value="{{ item.item }} ">
                                        <input type="hidden " name="product_flavour " value="{{ item.flavour }} ">
                                        <input type="hidden " name="product_strength " value="{{ item.strength }} ">
                                        {% endif %}
                                    </div>
                                </div>
                            </form>
                            <a class="update-link text-info "><small>Update</small></a>
                            <a class="remove-item text-danger float-right " id="remove_{{ item.item_id }} "
                                data-product_item="{{ item.item }} "><small>Remove</small></a>
                        </td>
                        <td class="py-3 ">
                            <p class="my-0 ">£{{ item.product.price | calc_subtotal:item.quantity }}</p>
                        </td>
                    </tr>
                    {% endfor %}

这里只是有问题的锚标签:

<a class="remove-item text-danger float-right " id="remove_{{ item.item_id }} " data-product_item="{{ item.item }} "><small>Remove</small></a>

最后这里是应该让它工作的脚本:

<script type="text/javascript">
    // Update quantity on click
    $('.update-link').click(function (e) {
        var form = $(this).prev('.update-form');
        form.submit();
    })

    // Remove item and reload on click
    $('.remove-item').click(function (e) {
        var csrfToken = "{{ csrf_token }}";
        var itemId = $(this).attr('id').split('remove_')[1];
        var item = $(this).data('product_item');
        var url = `/basket/remove/${itemId}`;
        var data = {
            'csrfmiddlewaretoken': csrfToken,
            'product_item': item
        };

        $.post(url, data)
            .done(function () {
                location.reload();
            });
    })
</script>

我想我遗漏了一些非常简单的东西,我认为这与我的 if 语句有关,因为当我将项目打印到控制台时它返回 None 并因此跳到通过 id 而不是 items_by_variations 字典删除项目。

javascript django django-views django-templates
© www.soinside.com 2019 - 2024. All rights reserved.