我尝试通过添加一些代码来启用购物车上的删除选项以删除购物车项目,结果出现以下错误

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

我添加了代码以启用购物车上的删除选项。出现以下错误。 与“remove_cart_item”相反,未找到参数“(2,)”。尝试了 1 个模式:['cart/remove_cart_item/(?P[0-9]+)/(?P[0-9]+)/$']

cart.html

{% extends 'base.html' %}
{% load static %}

{% block content %}

<!-- ============================ COMPONENT 1 ================================= -->
{% if not cart_items%}
<h2 class="text-center">Your shopping cart is empty</h2>
<br>
<div class="text-center">
<a href="{% url 'store' %}" class="btn btn-primary">Continue Shopping</a>
</div>
{% else %}
<div class="row">
    <aside class="col-lg-9">
<div class="card">
<table class="table table-borderless table-shopping-cart">
<thead class="text-muted">
<tr class="small text-uppercase">
  <th scope="col">Product</th>
  <th scope="col" width="120">Quantity</th>
  <th scope="col" width="120">Price</th>
  <th scope="col" class="text-right" width="200"> </th>
</tr>
</thead>
<tbody>

<tr>
    {% for cart_item in cart_items %}
    <td>
        <figure class="itemside align-items-center">
            <div class="aside"><img src="{{ cart_item.product.images.url }}" class="img-sm"></div>
            <figcaption class="info">
                <a href="{{ cart_item.product.get_url }}" class="title text-dark">{{cart_item.product.product_name}}</a>
                <p class="text-muted small">
                    {% if cart_item.variations.all %}
                        {% for item in cart_item.variations.all %}
                            {{item.variation_category |capfirst }} : {{item.variation_value | capfirst}} <br>
                        {% endfor %}
                    {% endif %} 
                </p>    
            </figcaption>
        </figure>
    </td>
    <td> 
        <!-- col.// -->
                    <div class="col"> 
                        <div class="input-group input-spinner">
                            <div class="input-group-prepend">
                            <a href="{% url 'remove_cart' cart_item.product.id cart_item.id %}" class="btn btn-light" type="button" id="button-plus"> <i class="fa fa-minus"></i> </a>
                            </div>
                            <input type="text" class="form-control"  value="{{cart_item.quantity}}">
                            <div class="input-group-append">
                            <form action="{% url 'add_cart' cart_item.product.id %}" method="POST">
                                {% csrf_token %}
                                {% for item in cart_item.variations.all %}
                                    <input type="hidden" name="{{item.variation_category | lower}}" value="{{item.variation_value | capfirst}}">
                                {% endfor %}
                                <button class="btn btn-light" type="submit" id="button-minus"> <i class="fa fa-plus"></i> </button>
                            </form>
                            </div>      
                        </div> <!-- input-group.// -->
                    </div> <!-- col.// -->
    </td>
    <td> 
        <div class="price-wrap"> 
            <var class="price">${{cart_item.sub_total}}</var> 
            <small class="text-muted"> ${{cart_item.product.price}} each</small> 
        </div> <!-- price-wrap .// -->
    </td>
    <td class="text-right"> 
    <a href="{% url 'remove_cart_item' cart_item.product.id cart_item.id %}" class="btn btn-danger"> Remove</a>
    </td>
</tr>
{% endfor %}
</tbody>
</table>
</div> <!-- card.// -->

    </aside> <!-- col.// -->
    <aside class="col-lg-3">

        <div class="card">
        <div class="card-body">
            <dl class="dlist-align">
              <dt>Total price:</dt>
              <dd class="text-right">{{total}}</dd>
            </dl>
            <dl class="dlist-align">
              <dt>Tax:</dt>
              <dd class="text-right"> {{tax}}</dd>
            </dl>
            <dl class="dlist-align">
              <dt>Grand Total:</dt>
              <dd class="text-right text-dark b"><strong>${{grand_total}}</strong></dd>
            </dl>
            <hr>
            <p class="text-center mb-3">
                <img src="{% static './images/misc/payments.png' %}" height="26">
            </p>
            <a href="./place-order.html" class="btn btn-primary btn-block"> Checkout </a>
            <a href="{% url 'store' %}" class="btn btn-light btn-block">Continue Shopping</a>
        </div> <!-- card-body.// -->
        </div> <!-- card.// -->

</aside> <!-- col.// -->


</div> <!-- row.// -->
{% endif %}
<!-- ============================ COMPONENT 1 END .// ================================= -->

</div> <!-- container .//  -->
</section>
<!-- ========================= SECTION CONTENT END// ========================= -->

{% endblock %}

购物车应用程序的 urls.py 文件

urlpatterns = [
    path('', views.cart, name='cart'),
    path('add_cart/<int:product_id>/', views.add_cart, name='add_cart'),
    path('remove_cart/<int:product_id>/<int:cart_item_id>/', views.remove_cart, name='remove_cart'),
    path('remove_cart_item/<int:product_id>/<int:cart_item_id>/', views.remove_cart_item, name='remove_cart_item'),

]

购物车应用程序的views.py文件


# Create your views here.
def _cart_id(request):
    cart = request.session.session_key
    if not cart:
        cart = request.session.create()
    return cart

def add_cart(request, product_id): 
    product = Product.objects.get(id=product_id)  #get the product
    product_variation = []
    if request.method=='POST':
        for item in request.POST:
            key=item
            value=request.POST[key]
            
            try:
                variation=Variation.objects.get(product=product, variation_category__iexact=key, variation_value__iexact=value)
                product_variation.append(variation)
            except:
                pass

    try:
        cart = Cart.objects.get(cart_id = _cart_id(request))  #get the cart using the cart_id present in the session
    except Cart.DoesNotExist:
        cart = Cart.objects.create(
            cart_id = _cart_id(request)
        )
    cart.save()

    is_cart_item_exists = CartItem.objects.filter(product=product, cart=cart).exists()
    if is_cart_item_exists:
        cart_item = CartItem.objects.filter(product=product, cart=cart)
        # existing_variations ->database
        # current_variations -> product_variation
        # item_id -> database
        ex_var_list = []
        id = []
        for item in cart_item:
            existing_variation = item.variations.all()
            ex_var_list.append(list(existing_variation))
            id.append(item.id)

        print(ex_var_list)

        if product_variation in ex_var_list:
            # increase the cart item quantity
            index = ex_var_list.index(product_variation)
            item_id = id[index]
            item = CartItem.objects.get(product=product, id=item_id)
            item.quantity += 1
            item.save()
        else:
            # create a new cart item
            item = CartItem.objects.create(product=product, quantity=1, cart=cart)
            if len(product_variation) > 0:
                item.variations.clear()
                item.variations.add(*product_variation)     
            item.save()
    else:
        cart_item = CartItem.objects.create(
            product = product,
            quantity = 1,
            cart = cart,
        )
        if len(product_variation) > 0:
            cart_item.variations.clear()
            cart_item.variations.add(*product_variation)
        cart_item.save()

    return redirect('cart')

def remove_cart(request, product_id, cart_item_id):
    cart = Cart.objects.get(cart_id = _cart_id(request))
    product = get_object_or_404(Product, id=product_id)
    try:
        cart_item = CartItem.objects.get(product = product, cart = cart, id=cart_item_id)
        if cart_item.quantity > 1:
            cart_item.quantity -= 1
            cart_item.save()
        else:
            cart_item.delete()
    except:
        pass
    return redirect('cart')

def remove_cart_item(request, product_id, cart_item_id):
    cart = Cart.objects.get(cart_id = _cart_id(request))
    product = get_object_or_404(Product, id=product_id)
    cart_item = CartItem.objects.get(product = product, cart = cart, id=cart_item_id)
    cart_item.delete()
    return redirect('cart')
    
def cart(request, total=0, quantity=0, cart_items= None):
    try:
        tax = 0
        grand_total = 0
        cart = Cart.objects.get(cart_id = _cart_id(request))
        cart_items = CartItem.objects.filter(cart=cart, is_active=True)
        for cart_item in cart_items:
            total += (cart_item.product.price * cart_item.quantity)
            quantity += cart_item.quantity
        tax = (total * 2) / 100
        grand_total = total + tax
        
    except ObjectDoesNotExist:
        pass # just ignore
    context = {
        'total': total,
        'quantity': quantity,
        'cart_items': cart_items,
        'tax': tax,
        'grand_total': grand_total,
        }

    return render(request, 'store/cart.html', context)

def __str__(self):
    return self.cart_item

跟踪堆栈

Internal Server Error: /cart/
Traceback (most recent call last):
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\carts\views.py", line 124, in cart       
    return render(request, 'store/cart.html', context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\backends\django.py", line 61, in render
    return self.template.render(context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 170, in render
    return self._render(context)
           ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 162, in _render
    return self.nodelist.render(context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
           ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\loader_tags.py", line 150, in render
    return compiled_parent._render(context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 162, in _render
    return self.nodelist.render(context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
           ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
           ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\defaulttags.py", line 312, in render
    return nodelist.render(context)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
           ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\defaulttags.py", line 211, in render
    nodelist.append(node.render_annotated(context))
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
           ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\defaulttags.py", line 446, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\urls\base.py", line 87, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'remove_cart_item' with arguments '(2,)' not found. 1 pattern(s) tried: ['cart/remove_cart_item/(?P<product_id>[0-9]+)/(?P<cart_item_id>[0-9]+)/$']
python django django-rest-framework django-views django-templates
1个回答
0
投票

在 urls.py 中,remove_cart_item 路径被定义为需要两个参数:product_id 和 cart_item_id

path('remove_cart_item/<int:product_id>/<int:cart_item_id>/', views.remove_cart_item, name='remove_cart_item')

错误表明函数需要两个参数,但得到了 0,所以你应该像这样传递参数来解决错误:

<a href="{% url 'remove_cart_item' product_id=cart_item.product.id cart_item_id=cart_item.id %}" class="btn btn-danger"> Remove</a>

此语法显式匹配 urls.py 文件中定义的参数,确保它们正确传递。

如果错误无法解决,请通过打印查看productid和cart id的值

print(cart_item.id)
© www.soinside.com 2019 - 2024. All rights reserved.