Reverse for 'cart_add' not found. 'cart_add' is not a valid view function or pattern name

Question:

I wanted to use django-shopping-cart 0.1 , but I got this error:
urls.py

from django.urls import path
from . import views
app_name='shop'
  urlpatterns = [
    path('',views.accueil, name='home'),
    path('cart/add/<int:id>/', views.cart_add, name='cart_add'),
    path('cart/item_clear/<int:id>/', views.item_clear, name='item_clear'),
    path('cart/item_increment/<int:id>/',
     views.item_increment, name='item_increment'),
    path('cart/item_decrement/<int:id>/',
     views.item_decrement, name='item_decrement'),
    path('cart/cart_clear/', views.cart_clear, name='cart_clear'),
    path('cart/cart-detail/',views.cart_detail,name='cart_detail'),

]

views.py

from django.shortcuts import render, redirect
from testshop.models import Product
from cart.cart import Cart

def cart_add(request, id):
  cart = Cart(request)
  product = Product.objects.get(id=id)
  cart.add(product=product)
  return redirect("home")


def item_clear(request, id):
  cart = Cart(request)
  product = Product.objects.get(id=id)
  cart.remove(product)
  return redirect("cart_detail")


def item_increment(request, id):
  cart = Cart(request)
  product = Product.objects.get(id=id)
  cart.add(product=product)
  return redirect("cart_detail")


def item_decrement(request, id):
  cart = Cart(request)
  product = Product.objects.get(id=id)
  cart.decrement(product=product)
  return redirect("cart_detail")


def cart_clear(request):
 cart = Cart(request)
 cart.clear()
 return redirect("cart_detail")


def cart_detail(request):
  return render(request, 'cart/cart_detail.html')

home.html

{% for product in products %}
    <p>{{produit.name}}<br>
       {{produit.price}}
       <a href="{% url 'cart_add' product.id %}">Add</a>
    </p>
    
{% endfor %}

the link Add does not work,
I have this error (Reverse for ‘cart_add’ not found. ‘cart_add’ is not a valid view function or pattern name.)

Thank you for your help !

Asked By: Khalifa

||

Answers:

If you have set app_name you have to include it in {% url %}:

<a href="{% url 'shop:cart_add' product.id %}">Add</a>

I assume that you have also placed ‘django-shopping-cart’ in INSTALLED_APPS.

Django DOCS

Answered By: NixonSparrow
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.