首页 > 解决方案 > add_to_cart() 缺少 2 个必需的位置参数:“product_id”和“quantity”

问题描述

我是初学者我不知道该怎么做对不起请帮助我 Traceback

Traceback(最近一次调用最后一次):文件“C:\Users\daghe\Dev\ecommerce - Backup\lib\site-packages\django\core\handlers\exception.py”,第 47 行,内部响应 = get_response(request ) 文件“C:\Users\daghe\Dev\ecommerce - Backup\lib\site-packages\django\core\handlers\base.py”,第 181 行,在 _get_response 响应 = Wrapped_callback(request, *callback_args, **callback_kwargs )

异常类型:/cart/add/ 处的 TypeError 异常值:add_to_cart() 缺少 2 个必需的位置参数:“product_id”和“quantity”

网址.py

from django.urls import path

from .views import (
    cart_home,
    add_to_cart,
    remove_from_cart,
    checkout_home,
    checkout_done_view
)
app_name = 'carts'

urlpatterns = [
    path('', cart_home, name='home'),
    path('checkout/success', checkout_done_view, name='success'),
    path('checkout/', checkout_home, name='checkout'),
    path('add/', add_to_cart, name='add-item'),
    path('remove/<product_id>/', add_to_cart, name='remove-item'),
]

视图.py

    def add_to_cart(request, product_id, quantity):
    product = Product.objects.get(id=product_id)
    cart = Cart(request)
    cart.add(product, product.unit_price, quantity)

def remove_from_cart(request, product_id):
    product = Product.objects.get(id=product_id)
    cart = Cart(request)
    cart.remove(product)

def cart_home(request):
    cart = Cart(request)
    return render(request, 'carts/home.html', {"cart":cart})

形式:

2   <form method='POST' action='{% url "cart:add-item" %}' class="form"> {% csrf_token %}
3       <input type='hidden' name='product_id' value='{{ product.id }}' />
4   
5       {% if in_cart %}
6           <button type='submit' class='btn btn-link btn-sm' style="padding:0px;cursor: pointer;">Remove?</button>
7       {% else %}
8           {% if product in cart.products.all %}
9               In cart <button type='submit' class='btn btn-link'>Remove?</button>
10          {% else %}
11              <button type='submit'  class='btn btn-success'>Add to cart</button>
12          {% endif %}

标签: pythondjango

解决方案


add_to_cart(request, product_id, quantity):   

此方法寻求两个值。product_id 和数量。

在您的 urls.py 中也提供这两个值。

所以 urls.py 将是:

path('add/<product_id>/<product_quantity>/', add_to_cart, name='add-item'),

通知

<form method='POST' action='{% url "cart:add-item" product.id product.quantity %}' class="form"> {% csrf_token %}
  <input type='hidden' name='product_id' value='{{ product.id }}' />

  {% if in_cart %}
       <button type='submit' class='btn btn-link btn-sm' style="padding:0px;cursor: pointer;">Remove?</button>
  {% else %}
       {% if product in cart.products.all %}
           In cart <button type='submit' class='btn btn-link'>Remove? 
</button>
     {% else %}
         <button type='submit'  class='btn btn-success'>Add to 
cart</button>
{% endif %}

推荐阅读