Python - Django Simple Search Filter

In this tutorial we will create a Simple Search Filter in Django. Django was created to achieve key objective and to ease the development of complicated, database-driven websites. It is a high-level Python Web framework with efficient programming capability . So let's now do the coding...

Getting Started

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/. After Python IDLE's is installed, open the command prompt then type "pip install Django", and hit enter. tut1

Creating the App

After django is set we will now create the web app. While your in the command prompt cd to the directory you want to save the app, then type "django-admin startproject server" and hit enter. A new folder will be created on the directory named 'server'. tut2

Running The Server

After creating the project, cd to the newly created directory, then type "manage.py runserver" and hit enter to start the server running. The "manage.py" is a command of django-admin that utilize the administrative tasks of python web framework. Here is the image of python web server: tut3Note: Type '127.0.0.1:8000' in the url browser to view the server. When there is code changes in the server just (ctrl + C) to command prompt to stop the server from running, then start again to avoid errors.

Creating The Website

This time will now create the web app to display the web models. First locate the directory of the app via command prompt cd, then type "manage.py startapp blog" and hit enter. A new directory will be created named "blog". tut4

Setting up The URL

This time will now create a url address to connect the app to the server. First go to server directory, then open urls.py via Python IDLE's or any text editor. Then import "include" module beside the url module and import additional module to make a redirect url to your site "from . import views". After that copy/paste the code below inside the urlpatterns.
  1. url(r'^$', views.index_redirect, name='index_redirect'),
  2. url(r'^blog/', include('blog.urls')),
It will be look like this:
  1. from django.conf.urls import include, url
  2. from django.contrib import admin
  3. from . import views
  4.  
  5. urlpatterns = [
  6. url(r'^$', views.index_redirect, name='index_redirect'),
  7. url(r'^blog/', include('blog.urls')),
  8. url(r'^admin/', admin.site.urls),
  9. ]
Then after that create a view that will catch the redirect url. To do that create a file "views.py" inside the blog directory then copy/paste the code below.
  1. from django.shortcuts import redirect
  2.  
  3. def index_redirect(request):
  4. return redirect('/blog/')

Creating The Path For The Pages

Now that we are all set we will now create a path for the web pages. All you have to do first is to go to blog directory, then copy/paste the code below and save it inside "blog" directory named it as 'urls.py' The file name must be urls.py or else there will be an error in the code.
  1. from django.conf.urls import url
  2. from . import views
  3.  
  4. urlpatterns = [
  5. url(r'^$', views.index, name='index'),
  6. url(r'^create$', views.create, name='create'),
  7. url(r'^search$', views.search, name='search'),
  8. ]

Creating A Static Folder

This time we will create a directory that store an external file. First go to the blog directory then create a directory called "static", after that create a sub directory called "blog". You'll notice that it is the same as your main app directory name to assure the absolute link. This is where you import the css, js, etc directory. For the bootstrap framework you get it from here http://getbootstrap.com/

Creating The Views

The views contains the interface of the website. This is where you assign the html code for rendering it to django framework and contains a methods that call a specific functions. To do that open the views.py, the copy/paste the code below.
  1. from django.shortcuts import render, redirect
  2. from .models import Member
  3. from django.db.models import Q
  4.  
  5. # Create your views here.
  6.  
  7. def index(request):
  8. members = Member.objects.all().order_by('lastname')
  9. return render(request, 'blog/index.html', {'members': members})
  10.  
  11. def create(request):
  12. member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname'])
  13. member.save()
  14. return redirect('/')
  15.  
  16. def search(request):
  17.  
  18. members = Member.objects.filter(Q(firstname=request.GET.get('search')) | Q(lastname=request.GET.get('search')))
  19. return render(request, 'blog/index.html', {'members': members})

Creating The Models

Now that we're done with the views we will then create a models. Models is module that will store the database information to django. To do that locate and go to blog directory, then open the "models.py" after that copy/paste the code.
  1. from django.db import models
  2.  
  3. # Create your models here.
  4. class Member(models.Model):
  5. firstname = models.CharField(max_length=50)
  6. lastname = models.CharField(max_length=50)
  7.  
  8. def __str__(self):
  9. return self.firstname + " " + self.lastname

Registering The App To The Server

Now that we created the interface we will now then register the app to the server. To do that go to the server directory, then open "settings.py" via Python IDLE's or any text editor. Then copy/paste this script inside the INSTALLED_APP variables 'blog'. It will be like this:
  1. INSTALLED_APPS = [
  2. 'blog',
  3. 'django.contrib.admin',
  4. 'django.contrib.auth',
  5. 'django.contrib.contenttypes',
  6. 'django.contrib.sessions',
  7. 'django.contrib.messages',
  8. 'django.contrib.staticfiles',
  9. ]

Creating The Mark up Language

Now we will create the html interface for the django framework. First go to blog directory, then create a directory called "templates" and create a sub directory on it called blog. base.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. {% load static %}
  4. <link rel="stylesheet" type="text/css" href="{% static 'blog/css/bootstrap.css' %}"/>
  5. <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  6. </head>
  7. <nav class="navbar navbar-default">
  8. <div class="container-fluid">
  9. <a class="navbar-brand" href="https://sourecodester.com">Sourcecodester</a>
  10. </div>
  11. </nav>
  12. <div class="col-md-3"></div>
  13. <div class="col-md-6 well">
  14. <h3 class="text-primary">Python - Django Simple Search Filter</h3>
  15. <hr style="border-top:1px dotted #000;"/>
  16. {% block body %}
  17. {% endblock %}
  18. </div>
  19. </body>
  20. </html>
Save it as "base.html" inside the blog directory "sub directory of templates". index.html
  1. {% extends 'blog/base.html' %}
  2. {% block body %}
  3. <form method="POST" action="create">
  4. {% csrf_token %}
  5. <div class="form-inline">
  6. <label>Firstname</label>
  7. <input type="text" name="firstname" size="12" class="form-control" required="required"/>
  8. <label>Lastname</label>
  9. <input type="text" name="lastname" size="12" class="form-control" required="required"/>
  10. <button class="btn btn-primary">Submit</button>
  11. </div>
  12. </form>
  13. <br /><br /><br />
  14. <form method="GET" action="search">
  15. <div class="form-inline">
  16. <input type="text" placeholder="Search" name="search" class="form-control" required="required" />
  17. <button class="btn btn-primary btn-sm"><span class="glyphicon glyphicon-search"></span> Search</button>
  18. </div>
  19. </form>
  20. <br />
  21. <table class="table table-bordered">
  22. <thead class="alert-danger">
  23. <tr>
  24. <th>Firstaname</th>
  25. <th>Lastname</th>
  26. </tr>
  27. </thead>
  28. {% for member in members%}
  29. <tr>
  30. <td>{{ member.firstname }}</td>
  31. <td>{{ member.lastname }}</td>
  32. </tr>
  33. {% endfor %}
  34. </tbody>
  35. </table>
  36. {% endblock %}
Save it as "index.html" inside the blog directory "sub directory of templates".

Migrating The App To The Server

Now that we're done in setting up all the necessary needed, we will now then make a migration and migrate the app to the server. To do that open the command prompt then cd to the "server" directory, then type "manage.py makemigrations" and hit enter. After that type again "manage.py migrate" then hit enter. tut5 There you have it we successfully created a Simple Search Filter in Django. I hope that this simple tutorial help you for what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!!

Tags

Add new comment