Home > Software engineering >  Reverse for 'AddCart' not found. 'AddCart' is not a valid view function or patte
Reverse for 'AddCart' not found. 'AddCart' is not a valid view function or patte

Time:08-14

I am Working on my project and I don't know how this error I got

Can anybody see what I'm missing?

This is my root project urls.py

from django.contrib import admin
from django.urls import path, include
from .import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),
    path('onlinePizza/', include('onlinePizza.urls')),
    path('cart/', include(('cart.urls'), namespace='cart')),
    path('accounts/', include(('accounts.urls'), namespace='accounts')),
]   static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This is my cart app urls.py

from django.urls import path
from .import views
from cart.views import AddCart

app_name = 'cart'

urlpatterns = [
    path('add_cart/', views.AddCart, name='Cart'),
]

This is my cart app views.py

from django.shortcuts import render, redirect
from cart.models import *

def AddCart(request):
    product = request.POST.get('product')
    remove = request.POST.get('remove')
    cart = request.session.get('cart')
    
    if not cart:
        request.session['cart'] = {}

    if cart:
        quantity=cart.get(product)
        if quantity:
            if remove:
                if quantity<=1:
                    cart.pop(product)
                else:
                    cart[product]=quantity-1
            else:   
                cart[product]=quantity 1
        else:
            cart[product]=1         
    else:
        cart={}
        cart[product]=1

    request.session['cart']=cart
    
    return redirect ('Menu')

This is my onlinePizza/pc_menu.html template

<form action="{% url 'cart:AddCart' %}" method="POST">{% csrf_token %}
     <input hidden type="text" name="product" value="{{i.id}}">
     <button  style="padding: 5px 32px">Add <i ></i></button>
</form>

I try to solve this problem, but I show this error everywhere in my project.

CodePudding user response:

You need that name:

urlpatterns = [
    path('add_cart/', views.AddCart, name='Cart'),
]

and that link generator:

{% url 'cart:AddCart' %}

refering to the exactly same value. So it has to be either 'Cart' and 'cart:Cart' or 'AddCart' and 'cart:AddCart'.

  • Related