Home > Blockchain >  Reverse for 'Tools' with no arguments not found. 1 pattern(s) tried: ['home/(?P<ca
Reverse for 'Tools' with no arguments not found. 1 pattern(s) tried: ['home/(?P<ca

Time:06-13

Based on an answer to my previous question here

This is my html code:

<a href="{% url 'Tools' %}"><p>Tools</p></a>

When I used category like this def home( request,category) in my views, I got a positional argument error so I used this :

def home( request,**kwargs ):
    p=product.objects.filter(category__name= category)
    return render(request,'home.html',{'p':p})

This is URLs:

urlpatterns = [
    
    path('',views.home),
    path('home/<str:category>', views.home,name='Tools'),
    
]

But after going to this URL http://127.0.0.1:8000/home/Tools I got this error :

NoReverseMatch at /home/Tools
Reverse for 'Tools' with no arguments not found. 1 pattern(s) tried: ['home/(?P<category>[^/] )\\Z']

Why do I get this error?

Or how can I solve this error home() missing 1 required positional argument: 'category'

if I want to use this : def home( request,category)?

CodePudding user response:

The error you see means that Tools URL expects one parameter. So the following:

<a href="{% url 'Tools' 'some_category' %}"><p>Tools</p></a>

is acceptable. It you want to have Tools view without a category, you need another URL that doesn't require it (or regex in existing to allow empty category, but it is more error prone in general):

# urls.py

urlpatterns = [
    path('', views.home),
    path('home', views.home, name='Tools'),
    path('home/<str:category>', views.home, name='Tools'),    
]
# views.py

def home(request, category=None):  # Note default value
    p = product.objects.all()  # Why is your model class name lowercase?..
    if category is not None:
        p = p.filter(category__name=category)

    return render(request, 'home.html', {'p':p})

Also you can use

path('home', views.home, {'category': None}, name='Tools')

in urls.py instead of default argument value.

  • Related