ANOVIN

Building a Search Engine with Python and Django

Building a Search Engine with Python and DjangoIn this tutorial, we will learn how to build a search engine using Python and Django framework. The search engine will enable users to search for data in our database and get relevant results.PrerequisitesTo follow along, you need to have a basic understanding of Python programming language, Django framework, and HTML. If you are not familiar with these concepts, you can check out our beginner-friendly tutorials on Python programming and Django framework on our blog.Step 1 - Setting up the EnvironmentFirst, we need to create a Django project and set up our environment. To do this, open your terminal and run the following commands:```mkdir search_enginecd search_enginepython3 -m venv envsource env/bin/activatepip install djangodjango-admin startproject searchappcd searchapppython manage.py migrate```Step 2 - Creating the ModelsNext, we need to create a model that will represent the data we want to search. In this tutorial, we will create a simple model for storing books. Open the models.py file in the searchapp folder and add the following code:```pythonfrom django.db import modelsclass Book(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=255) description = models.TextField() def __str__(self): return self.title```This code defines a model called Book that has three fields: title, author, and description. We also define a `__str__` method to display the title of the book in the Django admin interface.Next, run the following command in your terminal to create the database table for our model:```python manage.py makemigrationspython manage.py migrate```Step 3 - Adding Data to the DatabaseNow that we have created our model, we need to add some data to our database. Open the Django shell by running the following command:```python manage.py shell```In the shell, run the following Python code to add some books to our database:```pythonfrom searchapp.models import Bookbook1 = Book(title='The Great Gatsby', author='F. Scott Fitzgerald', description='A novel about the American dream.')book1.save()book2 = Book(title='To Kill a Mockingbird', author='Harper Lee', description='A novel about racial injustice in the South.')book2.save()book3 = Book(title='1984', author='George Orwell', description='A dystopian novel about government control.')book3.save()```These commands add three books to our database.Step 4 - Creating the Search ViewNow we need to create a view that will handle the search requests from the users. Create a new file search.py in the searchapp folder and add the following code:```pythonfrom django.shortcuts import renderfrom searchapp.models import Bookdef search(request): query = request.GET.get('q') books = Book.objects.filter(title__icontains=query) return render(request, 'search.html', {'books': books, 'query': query})```This code defines a view called search that gets the user's search query from the URL parameters using the GET method. We then filter the books based on the query using the `icontains` lookup. Finally, we render a template called search.html and pass the filtered books and the search query as context variables.Step 5 - Creating the Search FormNext, we need to create a search form that the user will use to input their search query. Create a new file search.html in the templates folder inside the searchapp folder and add the following code:```html Search Results - {{ query }}

{% if books %}

Search Results for "{{ query }}"

{% else %}

No results for "{{ query }}".

{% endif %}```This code defines a basic HTML form that has an input field for the search query and a submit button. We also display the search results if any and a message if there are no results.Step 6 - Configuring the URLsFinally, we need to configure the URLs for our search app. Open the urls.py file in the searchapp folder and add the following code:```pythonfrom django.urls import pathfrom searchapp.views import searchurlpatterns = [ path('', search, name='search'),]```This code defines a URL pattern that maps the root URL of our app to the search view we created earlier.Step 7 - Testing the Search EngineThat's it! We have built a search engine using Python and Django. To test it out, run the Django development server by running the following command in your terminal:```python manage.py runserver```Open your web browser and go to `http://localhost:8000/` to see the search form. Enter a search query and click the search button. You should see the results displayed on the next page.ConclusionIn this tutorial, we learned how to build a search engine using Python and Django. We created a model to represent our data, added data to our database, created a search view, created a search form, and configured the URLs for our app. This is just a simple example, but the principles we learned can be applied to any search engine project.

Useful Links: