python - 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 %}
解决方案
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 %}
推荐阅读
- rust - 什么是包、板条箱和模块?
- reactjs - 反应 useEffect 循环
- r - 将 Rcpp 文件添加到现有的 r 包?
- pandas - 如何在没有 qcut 的情况下将数字熊猫系列分成 n 个大小大致相同的组?
- javascript - 多个正则表达式 const - 为每个匹配的单词添加样式
- sql - 将每一行与最新的前一行与条件相关联的有效方法。(PostgreSQL)
- c# - 如何检查一个项目在c#中的列表中存在多少次?
- c# - C# 使用 forEach 修改被迭代的列表
- python - UnicodeEncodeError:“latin-1”编解码器无法在位置 8 编码字符“\u01e2”:序数不在范围内(256)。怎么解决?
- android - 我的应用不要求访问权限