Implement Basic Search Into A Django Application

$ pip install django
$ django-admin startproject ecommerce
$ python manage.py migrate
$ python manage.py runserver
$ python manage.py startapp products
INSTALLED_APPS = [
...
'products', # newly created app
]
class Category(models.Model):
title = models.CharField(max_length=15, unique=True, null=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, null=True)

class Meta:
verbose_name_plural = "Categories"

def __str__(self):
return self.title


class Product(models.Model):
name = models.CharField(max_length=200)
price = models.FloatField()
category = models.ForeignKey('Category', blank=True, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.name
$ python manage.py makemigrations products
$ python manage.py migrate
from django.contrib import admin# Register your models here.
from .models import Product, Category

class ProductAdmin(admin.ModelAdmin):
list_display = ("name", "price", "category")

class CategoryAdmin(admin.ModelAdmin):
list_display = ("title", "timestamp",)

admin.site.register(Product, ProductAdmin)
admin.site.register(Category, CategoryAdmin)
$ python manage.py createsuperuser
from django.contrib import admin
from django.urls import path
from django.urls import path, include # newly added

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('products.urls')), # newly added
]
$ touch products/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('query/', views.query, name='query_results'),
path('', views.home, name='home'),
]
from django.shortcuts import render
# Create your views here.
def query(request):
return render(request, 'search_results.html')
def home(request):
return render(request, 'home.html')
$ mkdir templates
$ touch templates/home.html
$ touch templates/search_results.html
TEMPLATES = [
{
...
'DIRS': ['templates'], # newly added
...
}
]
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
<body>
<h1>Home Page</h1>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search</title>
</head>
<body>
<h1>Search Page</h1>
</body>
</html>
from django.shortcuts import render
from .models import * #newly added
# Create your views here.
def query(request):
return render(request, 'search_results.html')
def home(request):
products = Product.objects.all() #newly added
return render(request, 'home.html', {'products':products }) #newly added {'products':products }
<h1>Home Page</h1> 
<form style="text-align: center; margin: 20px;" action="{% url 'query_results' %}" method="get">
<input name="query" type="text" placeholder="Search Products"> <button type="submit">Search</button>
</form>
{% for product in products %}
<div style="text-align: center;">
{{product.name}} - {{product.price}} - {{product.category}}
<hr>
</div>
{%endfor%}
from django.db.models import Q # new
from django.shortcuts import render
from .models import *
# Create your views here.
def query(request):
query = request.GET.get('query') # new
results = Product.objects.filter( # new
Q(name__icontains=query) | Q(price__icontains=query) # new
| Q(category__title__icontains=query) # new
)
return render(request, 'search_results.html', # new
{ 'results':results, })
def home(request):
products = Product.objects.all()
return render(request, 'home.html',
{ 'products':products })
<body style="text-align: center;">
<h1>Search Page</h1>
<hr>
{% for result in results %}
<div style="text-align: center;">
{{result.name}} - {{result.price}} - {{result.category}}
<hr>
</div>
{% empty %}
<h2 >No results found</h2>
<div >
<a href="{% url 'home' %}"> < Back Home</a>
</div>
{% endfor %}
</body>
from django.shortcuts import render,redirect # redirect
from django.db.models import Q
from .models import *
# Create your views here.
def query(request):
query = request.GET.get('query')
if query is None: # new
return redirect('home') # new
else:
results = Product.objects.filter(
Q(name__icontains=query) | Q(price__icontains=query)| Q(category__title__icontains=query))
return render(request, 'search_results.html',{ 'results':results, })
def home(request):
products = Product.objects.all()
return render(request, 'home.html',
{ 'products':products })

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ridwan Yusuf

Ridwan Yusuf

RidwanRay.com - I love writing code to solve 🛠️ real-life problems.