使用Django 2,我正在尝试将购物车应用添加到我的django项目中。我收到此错误消息:找不到带有参数'(',)'的'add_cart'。尝试了1种模式:['购物车/添加/(?P [0-9] +)/ $']
根据我的理解和研究,我认为我的问题是我没有在模板标签中输入正确的URL链接到我的视图。但是我刚接触Django仅4个星期,有点迷茫。
我尝试更改“ {%url'cart_remove'cart_item.product.id%}”和“ {%url'cart_add'cart_item.product.id%}”标签。
我尝试调整应用程序和项目级别的urls.py。
我试图更改base.html,cart.html
我尝试过更改视图,并多次读取每个文件,以发现错误或错字。
我已经改变了大约5个小时,但似乎没有任何效果。正如我说的,我认为我的模板标签有问题。我认为我很困惑,正在尝试链接错误的内容。
cart.html
{% for cart_item in cart_items %}
<tr>
<td>{{cart_item.product.name}}</td>
<td>{{cart_item.product.brand}}</td>
<td>{{cart_item.product.description}}</td>
<td>€{{cart_item.product.price}}</td>
<td>{{cart_item.sub_total}}</td>
<td>{{cart_item.quantity}}</td>
<td><a href="{% url 'cart_remove' cart_item.product.id%}">
<span class="glyphicon glyphicon-minus-sign"></span></a></td>
<td><a href="{% url 'add_cart' cart_item.product.id %}">
<span class="glyphicon glyphicon-plus-sign"></span></a></td>
</tr>
{% endfor %}
cart / views.py中的add_cart函数
def add_cart(request, product_id):
product = Product.objects.get(id=product_id)
try:
cart = Cart.objects.get(cart_id=_cart_id(request))
except Cart.DoesNotExist:
cart = Cart.objects.create(
cart_id = _cart_id(request)
)
cart.save()
try:
cart_item = CartItem.objects.get(product=product, cart=cart)
if cart_item.quantity < cart_item.product.stock:
cart_item.quantity += 1
cart_item.save()
else:
messages.add_message(request, messages.INFO,
'Sorry, no more of this item available')
except CartItem.DoesNotExist:
cart_item = CartItem.objects.create(
product = product,
quantity = 1,
cart = cart
)
cart_item.save()
return redirect('cart_detail')
cart / urls.py
from django.urls import path
from . import views
urlpatterns = [
path('add/<int:product_id>/', views.add_cart, name='add_cart'),
path('', views.cart_detail, name='cart_detail'),
path('remove/<int:product_id>/', views.cart_remove, name='cart_remove'),
path('full_remove/', views.full_remove, name='full_remove'),
]
模板路径
'DIRS': [os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'shop', 'templates/'),
os.path.join(BASE_DIR, 'cart', 'templates/'),],
项目级别urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('landing.urls')),
path('shop/', include('shop.urls')),
path('cart/', include('cart.urls')),
]
我的预期结果是,当我单击本地导航栏中的shop链接时,登录页面将显示登录页面,而shop.html页面将加载。目前,我收到错误消息:找不到带有参数'(',)'的'add_cart'。尝试了1种模式:['购物车/添加/(?P [0-9] +)/ $']