Reputation: 21
I am trying to implement search in my project so that users can search for anything with ease but I keep getting Page not Found error.The errors seems like it's coming from my urls.py but I don't know where exactly.
Below are my codes
urls.py
from .import views
app_name = 'app'
urlpatterns = [
path('', views.product_list, name='product_list'),
path('<slug:category_slug>/', views.product_list, name='product_list_category'),
path('search/', views.search_list, name='search_list'),
path('<int:id>/<slug:slug>/', views.product_details, name='product_details'),
]
views.py
from .models import Category, Product
from cart.forms import CartAddProductForm
from django.db.models import Q
# Create your views here.
def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
return render(request, 'products/list.html', {'category': category, 'categories': categories, 'products': products})
def product_details(request, id, slug):
product = get_object_or_404(Product, id=id, slug=slug, available=True)
cart_product_form = CartAddProductForm()
return render(request, 'products/detail.html', {'product': product, 'cart_product_form': cart_product_form})
def search_list(request):
search_post = request.GET.get('q')
search_query = Product.objects.filter(Q(name__icontains=search_post) | Q(category__name__icontains=search_post))
return render(request, 'products/search.html', {'search_post': search_post, 'search_query': search_query, 'category': category, 'categories': categories})
Upvotes: 0
Views: 51
Reputation: 32244
The url resolver returns the first pattern that matches the incoming path.
The product_list_category
pattern matches search/
so search_list
is never resolved, put the search_list
pattern before product_list_category
urlpatterns = [
...
path('search/', views.search_list, name='search_list'),
path('<slug:category_slug>/', views.product_list, name='product_list_category'),
...
]
Upvotes: 1