Searching Functionality in Django | E-commerce Website using Django | EP. 22
Welcome to Episode 22 of our Django E-commerce website tutorial series! In this episode, we will be implementing a searching functionality in our Django website to make it easier for users to find products they are looking for.
Setting up the Search Functionality
First, we need to create a search form in our templates where users can input their search queries. We can use a simple HTML form with a text input field and a submit button.
“`html
“`
Next, we need to create a view function that will handle the search results. We can use Django’s Q objects to perform a full-text search across multiple fields in our product model.
“`python
from django.db.models import Q
from .models import Product
def search_results(request):
query = request.GET.get(‘query’)
results = Product.objects.filter(
Q(name__icontains=query) |
Q(description__icontains=query)
)
context = {
‘results’: results,
‘query’: query
}
return render(request, ‘search_results.html’, context)
“`
Finally, we need to create a template to display the search results. We can iterate over the results and display them in a grid format with images and product names.
“`html
{% for product in results %}
{{ product.name }}
{{ product.description }}
{% empty %}
No products found.
{% endfor %}
“`
Conclusion
With the search functionality implemented, users can now easily find products on our E-commerce website by simply typing in their search queries. This enhances the user experience and makes it more convenient for users to navigate the site.
Stay tuned for the next episode where we will be adding more features to our Django E-commerce website!
another approach, we can use Q :
products = Product.objects.filter(
Q(title__icontains=query) |
Q(description__icontains=query) |
Q(tag__name__icontains=query) |
Q(category__title__icontains=query)
).order_by("-date_created").distinct()
in this way, we can make the search more wider
Awesome video, keep going 🥳🥳
Thank you again
Very very excellent
Thank you
Excellent, thank you thank you
At last … one more video 🙂
🙏