Simple Search App using Django API and Vanilla Javascript

||
Posted 3 years, 10 months ago
||
Views 1271
||
3 min read
1 reaction

 

In this section, we are going to build the simple search engine kind of app for our Django models,

Prerequiste,

  • Django > 2.2.1 (Backend)
  • Django rest framework(REST API)
  • Materialize CSS(Front End design)

Just assume, we have the product app in Django and below product model already in place,

from django.db import models


class Product(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField(max_length=2000)
    image = models.URLField()

    def __str__(self):
        return self.title

As you have noticed, its just simple model, which holds, Product title, image & description. Just for this demo purpose, we will just having the URL field to hold the image URL ,

In order to serialize the data from backend, we need to install the Django rest framework. Assume, we have serializers.py & views.py like below,

#serializers.py
from rest_framework.serializers import(
    ModelSerializer
)

from products.models import Product


class ProductListSerializer(ModelSerializer):

    class Meta:
        model = Product
        fields = [
            'id',
            'title',
            'description',
            'image'


        ]

Views.py

from rest_framework.generics import (
    ListAPIView,
)
from .serializers import ProductListSerializer
from products.models import Product


class ProductListAPIView(ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductListSerializer

    

Now, we have exposed our API to list the data. Below are the script to handle the front end part,

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search App</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/css/materialize.css">
</head>
<style>
    input[type="text"]::placeholder {

        text-align: center;
    }
</style>

<body>
    <div class="container">
        <h1 class="center-align">
            Simple Search
        </h1>
        <input type="text" id="searchid" placeholder="search here...">
        <!-- <div class="card-panel blue-text text-darken-2 contentmsg"> -->
        <div id="output"></div>
    </div>



    </div>

    <script>


        fetch("http://localhost:8000/api/", {
            method: "GET",

        }).then(response => {
            if (response.status !== 200) {

                throw new Error(response.status)
            }
            else {
                return response.json()
            }
        }).then(data => {
            output = data
            test()
            // data.forEach((elem) => {
            //     console.log(elem)
            // })
        })
        function test() {
            console.log(output)
        }

        let outputEl = document.getElementById('output')
        let inputEl = document.getElementById('searchid')
        inputEl.addEventListener('keyup', function (event) {
            if (event.keyCode === 13) {
                event.preventDefault();
                let searchValue = document.getElementById('searchid').value.toUpperCase();
                let finalTodoStr = ''
                for (let j = 0; j < output.length; j++) {
                    const titleValue = output[j]['title'].toUpperCase()
                    const descriptionTitle = output[j]['description'].toUpperCase()
                    const regexTitle = `${searchValue}`;
                    const regexDescription = `${searchValue}`;
                    const outputTitleValue = titleValue.match(regexTitle)
                    const outputDescValue = descriptionTitle.match(regexDescription)
                    if (outputTitleValue || outputDescValue) {
                        let currentItem = ` <div class="card-panel">
                        <span class="text-darken-2">${output[j]['title'] || output[j]['description']} <br>
                        ${output[j]['description']}</span>
                       
                        <br><a target='_blank' href="${output[j]['image']}">${output[j]['image']}<a>
                    </div>`
                        finalTodoStr += currentItem;

                    }
                }

              
                // console.log('Testing' + finalTodoStr.length)
                if (finalTodoStr.length === 0) {
                    let currentItem = ` <div class="card-panel">
                        <span class="red lighten-5">No Match Found !!!</span>
                    </div>`
                    finalTodoStr += currentItem;
                }


                outputEl.innerHTML = finalTodoStr


            }
        });

        function searchdata() {

            let searchValue = document.getElementById('searchid').value.toUpperCase();
            let finalTodoStr = ''
            for (let i = 0; i < data.length; i++) {

                if (data[i].toUpperCase() === searchValue) {
                    let currentItem = ` <div class="card-panel">
                        <span class="blue-text text-darken-2">Hi</span>
                    </div>`
                    finalTodoStr += currentItem;
                }

            }
            outputEl.innerHTML = finalTodoStr
           


        }

    </script>
</body>

</html>

Final output looks like this,

We have many approach to achieve this, but this is more clean & nice.

We will uploading the tutorial for this blog in a couple of days. Please make sure to register here in order to receive the notification when we upload new videos.

Happy coding !!!


1 reaction

Discussion

caliowino97
Posted 3 years, 10 months ago

Love it


bhanupriyakuchana123
Posted 3 years, 6 months ago

ok



Joined on April 19, 2020

Latest Videos