这是我的代码。当我不在path('remove/<int:product_id>/', views.cart_detail, name='cart_remove'),
中写urls.py
时,它可以正常工作,但是当我编写上述代码时,出现以下错误:
找不到带有参数'('',)'的'cart_add'的反向。尝试了1个模式:['购物车//(?P [0-9] +)\ / $']
文件:
urls.py
from django.urls import path
from . import views
app_name = 'cart'
urlpatterns = [
path('<int:id>/', views.cart_add, name='cart_add'),
path('remove/<int:product_id>/', views.cart_detail, name='cart_remove'),
path('detail/', views.cart_detail, name='cart_detail'),
]
views.py
def cart_add(request, id):
if request.method == 'POST':
cart_form = CartAddProductForm(request.POST)
if cart_form.is_valid():
if not cart_form.cleaned_data['update']:
product_id = str(id)
session = request.session
cart = session.get(settings.CART_SESSION_ID)
if not cart:
cart = request.session[settings.CART_SESSION_ID]={}
if product_id in cart:
cart[product_id]['quantity'] = cart_form.cleaned_data['quantity']
else:
cart[product_id] = {'quantity': cart_form.cleaned_data['quantity']}
session[settings.CART_SESSION_ID] = cart
session.modified = True
else:
pass
return redirect('shop:product_list')
def cart_detail(request, product_id=None):
cart_item = request.session.get(settings.CART_SESSION_ID)
total_price = 0
if not product_id:
add = [k for k in cart_item.keys()]
for key in add:
product_id = int(key)
product = get_object_or_404(Product, id=product_id)
total_price_per_item = cart_item[key]['quantity'] * product.price
cart_item[key]['product'] = product
cart_item[key]['total_price_per_item'] = total_price_per_item
cart_item[key]['update_quantity_form'] = CartAddProductForm(
initial={'quantity': cart_item[key]['quantity'],
'update': True})
total_price += total_price_per_item
else:
if product_id in cart_item:
del cart_item[product_id]
return render(request, 'cart/detail.html', {'cart': cart_item, 'total_price': total_price})
detail.html
<td>
<form action="{% url 'cart:cart_add' product.id %}" method="post">
{{ item.update_quantity_form.quantity }}
{{ item.update_quantity_form.update }}
<input type="submit" value="Update">
{% csrf_token %}
</form>
</td>
<td><a href="{% url 'cart:cart_remove' product.id %}">Remove</a></td>
<td class="num">${{ product.price }}</td>
<td class="num">${{ item.total_price_per_item }}</td>