Create Search App With Django Python

Here in this project you are going to learn how to create a custom search app with django.Where we are going to make a Post model and add the post to the database.

To the home page there is a search bar where we can search for the post ,if Post  exist then result will be return to the search page. when user click on result then there is a dynamic linking to every Post result.

Follow the following steps and at the end you will have your own Search app .

1 . Install Required modules

First of all you need to install django & mysql-connector

pip install django 
pip install mysql-connector

2. Create new project

After installation create new project

django-admin startproject SearchApp 

3. Create app

Now go inside your project create new app

  python manage.py startapp search

4. Add templates

Now go inside your app which is search and  create folder for templates ,add search.html,posts.html and resultPage.html files to templates.

search.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<style>
.serach{
    margin-top:200px;
    margin-left:450px;
}
.btn{
    margin-left: 200px;
    width: 100px;
}
body{
    background-color: darkgray;
}
</style>
<body>
     <div class="serach">
        <h1 style="font-size:100px; padding-left:90px;color:#34A853">Search</h1>

    <form action="" method="GET">
        <!-- {% csrf_token %} -->
        <div class="form-group" style="width: 500px; ">
            
          <input type="text" class="form-control"  aria-describedby="emailHelp" placeholder="Search" name="search">
          <small id="emailHelp" class="form-text text-muted">Search for post.</small>
        </div>
        <button type="submit" class="btn btn-primary" >Search</button>
    </form>    
    </div>
       
</body>
</html>

resultPage.html

{% if result%}
    {% for i in result%}
    <a href="/posts/{{i.id}}">{{i.title}}</a> <br>
    {%endfor%} 
    
 {%else%}
   <h3>no post fount</h3>   
 {% endif %}  

posts.html

<h1>This is post one</h1>
{% for i in obj %}
<a href="posts">{{i.title}}</a>
{%endfor%}

5. modify setting.py file

Now you need to add path of your templates to the settings ,and also add your app  inside settings ,

Here you can see i have added my database ,am using mysql DB .

"""
Django settings for SearchApp project.

Generated by 'django-admin startproject' using Django 2.0.2.

For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'b898k40!j+w-85iex)!ao3c5pxzh-#t-@9_zgbbognfcm$)89l'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Search',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'SearchApp.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'SearchApp.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'Search',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'

6. Create Model

Create User Model

 from django.db import models
        class Post(models.Model):
            id = models.AutoField(primary_key=True)
            title = models.CharField(max_length=150)
            desc = models.CharField(max_length=500)
            uploadBy= models.CharField(max_length=30)
        

7. Register Model

Once the model is created you have to register your model ,go to admin.py file <br>and Import your model from .models

from django.contrib import admin

from .models import Post
        
admin.site.register(Post)

8. Migrate model to database

Now yur are ready to make migrations ,by running the following commands your model will going to create table inside your database.

python manage.py makemigrations 

python manege.py migrate 

9. Create views

Now this is a important step . Creating a view for your templates.

       from django.shortcuts import render
        from .models import Post
        
        def search(request):
            post = Post.objects.all()
            query = request.GET.get('search')
        
            if query:
                find_post = post.filter(title__icontains=query)
                return render(request,'resultPage.html',{'result':find_post})
            return render(request,'search.html')
        def dynamicUrl(request,post_id):
            object = Post.objects.get(id=post_id)
            return render(request,'posts.html',{'object':object})

10. Modify urls.py file

 from django.contrib import admin
        from search import views
        from django.urls import path
        
        urlpatterns = [
            path('admin/', admin.site.urls),
            path('',views.search,name="search"),
            path('posts/&lt;int:post_id&gt;/',views.dynamicUrl)
        
        ]
        

11. Run Project

Now all done .To run your project go to your project dir and run following command.

python manage.py runserver

Final Output

Leave a Reply