diff --git a/products/urls.py b/products/urls.py index 21ee4de..6a3599b 100644 --- a/products/urls.py +++ b/products/urls.py @@ -7,4 +7,5 @@ path('category//product//', views.product_detail, name='product_detail'), path('category//', views.products, name='category_products'), path('submit_review//', views.submit_review, name='submit_review'), + path('search/', views.search, name='search'), ] \ No newline at end of file diff --git a/products/views.py b/products/views.py index 75a7e7b..09b036d 100644 --- a/products/views.py +++ b/products/views.py @@ -3,8 +3,8 @@ from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.contrib import messages from django.contrib.auth.decorators import login_required - from django.urls import reverse +from django.db.models import Q from .forms import ReviewForm from carts.views import _cart_id @@ -144,4 +144,20 @@ def submit_review(request, product_id): return redirect(referer_url) # Redirect to the product detail page or the referer URL - return redirect(referer_url) \ No newline at end of file + return redirect(referer_url) + +def search(request): + keyword = request.GET.get('keyword', '') # Get keyword or set it as empty string + products = Product.objects.all() # Get all products + product_count = products.count() # Default count of all the products + + if keyword: + products = products.filter(Q(description__icontains=keyword) | Q(product_name__icontains=keyword)).order_by('-created') + product_count = products.count() + + context = { + 'products' : products, + 'product_count': product_count + } + + return render(request, 'products/products.html', context) diff --git a/templates/includes/navbar.html b/templates/includes/navbar.html index 974d7db..30d8a74 100644 --- a/templates/includes/navbar.html +++ b/templates/includes/navbar.html @@ -12,11 +12,16 @@
- + + + +
  • - Top Products + {% if request.GET.keyword %} + Search Results for "{{ request.GET.keyword }}" + {% else %} + Top Products + {% endif %}