Search code examples
pythondjango

Django:Reverse for 'Search' not found. 'Search' is not a valid view function or pattern name


I am. trying to. build a search function for my django project base on the enter link description here

and the error message popped out "Reverse for 'Search' not found. 'Search' is not a valid view function or pattern name."

i have done the searching most of the advise asking me to check if the spelling is error

like my "search" in url or my search.html in my render

however, i have tried all the solution it still can't work

here is some of my code

urls.py:

from django.contrib import admin
from django.urls import path

from pages.views import home_view, contact_view, about_view
from products.views import product_detail_view, product_create_view, vendor_data,search_product

urlpatterns = [
    path('', home_view, name='home'),
    path('contact/', contact_view),
    path('about/', about_view),
    path('create/', product_create_view),
    path('product/', product_detail_view),
    path('search/', search_product),
    path('vendor/', vendor_data),
    path('admin/', admin.site.urls),

]

views.py

from django.shortcuts import render

from .models import Product

from .forms import ProductForm, RawProductForm,VendorForm


def search_product(request):
    if  request.method == "POST":
        query_name = request.POST.get('title', None)
        if query_name:
            results = Product.objects.filter(name__contains=query_name)
            return render(request, 'products/search.html', {"results":results})

    return render(request, 'products/search.html')

search.html

<!DOCTYPE html>
<html>
<head>
    <title>Django Search</title>
</head>
<body>



<form action="{% url 'search' %}" method="POST">
    {% csrf_token %} 
    <input type="text" name="name">
    <input type="submit" name="submit" value="Search">
</form>



{% for result in results %}

    <p>{{result.name}}</p>

{% endfor %}

</body>
</html>

and following is my folder in case if needed

enter image description here


Solution

  • Change this file.. urls.py

    from django.contrib import admin
    from django.urls import path
    
    from pages.views import home_view, contact_view, about_view
    from products.views import product_detail_view, product_create_view, vendor_data,search_product
    
    urlpatterns = [
        path('', home_view, name='home'),
        path('contact/', contact_view),
        path('about/', about_view),
        path('create/', product_create_view),
        path('product/', product_detail_view),
        path('search/', search_product, name = 'search'), # changed here
        path('vendor/', vendor_data),
        path('admin/', admin.site.urls),
    
    ]