Implementing Search Feature in Django for an E-commerce Website | Django Tutorial Episode 22

Posted by

Searching Functionality in Django | E-commerce Website using Django | EP. 22

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!

0 0 votes
Article Rating
7 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@steven_ch
6 months ago

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

@shaysframe1472
6 months ago

Awesome video, keep going 🥳🥳

@pablo20237
6 months ago

Thank you again

@pablo20237
6 months ago

Very very excellent

@pablo20237
6 months ago

Thank you

@pablo20237
6 months ago

Excellent, thank you thank you

@ingafter6335
6 months ago

At last … one more video 🙂
🙏