creaing a search form - lhmisho/django-eCommerce GitHub Wiki
search/views.py
from django.shortcuts import render
from django.views.generic import ListView
from products.models import Product
# Create your views here.
class SearchProductView(ListView):
# first way to manage list view
#queryset = Product.objects.all()
template_name = 'search/view.html'
# passing request.GET.q as a query to the template
def get_context_data(self, *args, **kwargs):
request = self.request
context = super(SearchProductView, self).get_context_data(*args, **kwargs)
query = request.GET.get('q')
context['query'] = query
return context
def get_queryset(self, *args, **kwargs):
request = self.request
query = request.GET.get('q',None)
print(query)
if query is not None:
return Product.objects.filter(title__icontains=query)
return Product.objects.featured()
search/templates/snippets/view.html
{% extends 'base.html' %}
{% block head %}
{% endblock head %}
<!-- we can also make query smarter without using get_context_data on views.py by useing with ... as .. -->
{% block content %}
<div class="row my-3">
{% if query %}
<div class="col-12">
Result for <b>{{ query }}</b>
</div>
{% else %}
<div class="col-12 col-md-6 mx-auto">
{% include 'search/snippets/search-form.html' %}
</div>
{%endif%}
</div><hr>
<div class="row">
<!-- {{ object_list }} -->
{% for obj in object_list %}
<div class="col shadow-lg p-3 mb-5 bg-white rounded" style="margin:10px;">
<!-- get_absolute_url is created at products.models get_absolute_url() -->
{%include 'products/snippets/card.html' with instance=obj%}
</div>
{% endfor %}
</div>
<!-- {'paginator': None, 'page_obj': None, 'is_paginated': False, 'object_list': <QuerySet [<Product: car>]>, 'product_list': <QuerySet [<Product: car>]>, 'view': <products.views.ProductListView object at 0x7f686df2edd8>}
{{ paginator }}
{{ is_paginated }}
{{ object_list }} -->
</div>
{% endblock %}
search/urls.py
from django.urls import path,re_path
from .views import (SearchProductView)
app_name = 'search'
urlpatterns = [
path('', SearchProductView.as_view(),name='query'),
]
{% include 'search/snippets/search-form.html' %}