简体   繁体   中英

NoReverseMatch: Reverse for 'update_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/(?P<slug>[\\w-]+)/$']

I got this error using django 2.0.7. Here are my codes:

urls.py: 
urlpatterns = [

url(r'^home/$', HomeView.as_view(), name='ACRMS-Home'),

url(r'^cart/(?P<slug>[\w-]+)/$', carts_views.update_cart, name='update_cart'),

url(r'^cart/$', carts_views.view, name="cart"),

]


views.py in carts:

def view(request):
    cart = Cart.objects.all()[0]
    context = {"cart": cart}
    template = "cart/view.html"
    return render(request, template, context)

def update_cart(request, slug):
    cart = Cart.objects.all()[0]
    try:
        product = Product.objects.get(slug=slug)
    except Product.DoesNotExist:
        pass
    except:
        pass
    if not product in cart.products.all():
        cart.products.add(product)
    else:
        cart.products.remove(product)
    return HttpResponseRedirect(reverse("cart"))

template:

<div>
<h1>{{ product.name }} <a href='{% url "update_cart" product.slug %}' class ='pull-right'>Add to Cart</a></h1>
</div>

I am trying to add an item to the cart, but keep getting that error. I cannot tell why it is not able to find a reverse pattern, since I am very new to django. Please help. Thank you!

You need to pass a product variable to your template

def view(request):
    cart = Cart.objects.all()[0]
    products= Product.objects.all()
    context = {
         "cart": cart,
         "products: products
    }
    template = "cart/view.html"
    return render(request, template, context)
{% for product in products %}
<div>
    <h1>{{ product.name }} <a href='{% url "update_cart" product.slug %}' class ='pull-right'>Add to Cart</a></h1>
</div>
{% endfor %{

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM