NoReverseMatch at / Reverse for 'cart' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['cart/(?P<id>[0-9]+)/\\Z']

Getting NoReverse error again.

models.py

from django.db import models

# Create your models here.
from django.contrib.auth.models import User
from ds_mp.models import Product




class Cart(models.Model):
	name = models.CharField(max_length=255)
	user = models.ForeignKey(User, on_delete=models.CASCADE)
	product = models.ManyToManyField(Product)
	qty = models.IntegerField(default=0)


	def get_absolute_url(self):
		return reverse('cart:cart', args=[self.id])

	def __str__(self):
		return str(self.id)






views.py

def cart(request, id):
	cart = get_object_or_404(Cart, id=id)
	return render(request, 'cart/cart.html',{
			'cart':cart,

		})

def add_to_cart(request):
	return render(request, 'cart/add_to_cart.html',{
		
		})

urls.py

from django.urls import path
from . import views

app_name = 'cart'

urlpatterns = [
	path('<int:id>/', views.cart, name='cart'),
	path('add_to_cart/', views.add_to_cart, name='add_to_cart'),

]

cart.html

		<li><a href="{% url 'cart:cart' cart.id %}">cart</a></li>

Tracestack:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 4.1.3
Python Version: 3.10.7
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sitemaps',
 'ltt.apps.LttConfig',
 'social_share_testing.apps.SocialShareTestingConfig',
 'membership.apps.MembershipConfig',
 'fatyatya.apps.FatyatyaConfig',
 'django_experiments_app.apps.DjangoExperimentsAppConfig',
 'tidynotes.apps.TidynotesConfig',
 'weatherapp.apps.WeatherappConfig',
 'books.apps.BooksConfig',
 'testing_app.apps.TestingAppConfig',
 'blog.apps.BlogConfig',
 'product_catalog.apps.ProductCatalogConfig',
 'ds_mp.apps.DsMpConfig',
 'newsy_app.apps.NewsyAppConfig',
 'vendors.apps.VendorsConfig',
 'cart.apps.CartConfig',
 'tutorials.apps.TutorialsConfig',
 'codepedia.apps.CodepediaConfig',
 'anonymous.apps.AnonymousConfig',
 'ecommerce.apps.EcommerceConfig',
 'django_comments_xtd',
 'django_comments',
 'django_markdown2',
 'rest_framework',
 'django_social_share',
 'easy_thumbnails',
 'filer',
 'treebeard',
 'ckeditor',
 'mptt',
 'import_export',
 'bootstrap_modal_forms',
 'django_filters',
 'dynamic_breadcrumbs',
 'accounts.apps.AccountsConfig',
 'django.contrib.sites',
 'allauth',
 'allauth.account',
 'allauth.socialaccount',
 'allauth.socialaccount.providers.google',
 'allauth.socialaccount.providers.facebook',
 'allauth.socialaccount.providers.twitter',
 'allauth.socialaccount.providers.apple']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Template error:
In template /Users/ariethan/Documents/django_apps/django_experiments_OLD_02/django_experiments/django_experiments_app/templates/django_experiments_app/front_page.html, error at line 33
   Reverse for 'cart' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['cart/(?P<id>[0-9]+)/\\Z']
   23 : 				<li><a href="{% url 'social_share_testing:front_page' %}">social share testing</a></li>
   24 : 				
   25 : 				<li><a href="{% url 'ecommerce:front_page' %}">e-commerce</a></li>
   26 : 
   27 : 				<li><a href="{% url 'django_experiments_app:keywords' %}">keywords</a></li>
   28 : 
   29 : 				<li><a href="{% url 'tidynotes:front_page' %}">Tidy notes</a></li>
   30 : 
   31 : 
   32 : 
   33 : 				<li><a href=" {% url 'cart:cart' cart.id %} ">cart</a></li>
   34 : 
   35 : 
   36 : 		</ul>
   37 : 
   38 : 
   39 : 		<hr>
   40 : 
   41 : 
   42 : 		<h3>Cropperjs - Testing:</h3>
   43 : 		<style>


Traceback (most recent call last):
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/ariethan/Documents/django_apps/django_experiments_OLD_02/django_experiments/django_experiments_app/views.py", line 15, in front_page
    return render(request,'django_experiments_app/front_page.html',{
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/shortcuts.py", line 24, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/backends/django.py", line 62, in render
    return self.template.render(context)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/base.py", line 175, in render
    return self._render(context)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/loader_tags.py", line 157, in render
    return compiled_parent._render(context)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/loader_tags.py", line 63, in render
    result = block.nodelist.render(context)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/template/defaulttags.py", line 472, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/urls/base.py", line 88, in reverse
    return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.10/site-packages/django/urls/resolvers.py", line 828, in _reverse_with_prefix
    raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /
Exception Value: Reverse for 'cart' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['cart/(?P<id>[0-9]+)/\\Z']

whats happening?
sometimes it works, at times it doesn’t.

any idea what causes this?

please help

The error in your front_page.html
I think you miss pass (cart) i.e you have no query to make (<li><a href=" {% url 'cart:cart' cart.id %} ">cart</a></li>)
Make sure you pass (cart variable to the front_page.html)

What is this view? (The view containing this line at line 15 of that specified file)

This is the view called front_page which is located in the main app of the project called django_experiments_app, I’m trying to link from this front_page to the cart view which is located in another, separate app called cart.

That’s the view we need to see here. It’s that view (and the template that it is trying to render) that is causing the error.

here is the view

def front_page(request):

	return render(request,'django_experiments_app/front_page.html',{

		})

urls.py

from django.urls import path
from . import views
from .views import SearchResults
app_name = 'django_experiments_app'

urlpatterns = [
    path('', views.front_page, name='front_page'),

I’m not exactly sure what is wrong here

We need to see the template, too.


{% extends 'django_experiments_app/base.html' %}
	{% block content %}

<div class="container ">
  <div class="row row-cols-2">

		<ul class="">

				<li><a href="{% url 'fatyatya:front_page' %}">Fatyatya</a></li>
				<li><a href="{% url 'books:front_page' %}">Books</a></li>
				<li><a href="{% url 'blog:posts' %}">Blog</a></li>
				<li><a href="{% url 'product_catalog:front_page' %}">Products catalog</a></li>
				<li><a href="{% url 'testing_app:front_page' %}">Testing app</a></li>
				<li><a href="{% url 'ds_mp:front_page' %}">dropship marketplace</a></li>
				<li><a href="{% url 'newsy_app:front_page' %}">newsy app</a></li>

				<li><a href="{% url 'tutorials:front_page' %}">tutorials</a></li>
				
				<li><a href="{% url 'codepedia:front_page' %}">codepedia</a></li>
				<li><a href="{% url 'anonymous:front_page' %}">anonymous</a></li>
				<li><a href="{% url 'ltt:front_page' %}">ltt</a></li>
				
				<li><a href="{% url 'social_share_testing:front_page' %}">social share testing</a></li>
				
				<li><a href="{% url 'ecommerce:front_page' %}">e-commerce</a></li>

				<li><a href="{% url 'django_experiments_app:keywords' %}">keywords</a></li>

				<li><a href="{% url 'tidynotes:front_page' %}">Tidy notes</a></li>



				<li><a href="{% url 'cart:cart' cart.id %}">cart</a></li>


		</ul>


		<hr>


		<h3>Cropperjs - Testing:</h3>
		<style>

		<br><br><br><br><br><br>

		<div>



  	<img id="image" src="">


  	<img id="output" src="">



</div>

</div>
</div>


	{% endblock %}
{% include 'django_experiments_app/footer.html' %}

So, knowing that this error is being caused by this view trying to render this line in this template, what do you think might be causing the error?

None of the other code or templates that you have posted have anything to do with this, focus only on this code.

I fixed it like this

	{% if user.is_authenticated %}
				<li><a href="{% url 'cart:cart' id=user.id %}">cart</a></li>

				{% endif %}

not sure if this is the right way.

I figured since the cart is assigned to a user the user needs to be authenticated first, right? Please tell e this is correct

I can’t answer that. I don’t know if that’s the right answer for you. (I don’t know what the cart:cart view is supposed to display or what you need to provide as the parameter there.)

the cart is the shopping cart. Silly me, I didn’t realize that only the logged in user should be able to see his/her cart, in this case the if user.auth… statement helped. Notice how the Cart model has the user field which is related to the User model? This user had to be authenticated first in order to access the cart view like so:

{% if user.is_authenticated %}
				<li><a href="{% url 'cart:cart' id=user.id %}">cart</a></li>

				{% endif %}