Search Data in Django From Firebase - GeeksforGeeks

08 Oct, 2021
Firebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. It provides cloud storage. It uses NoSQL for the storage of data.
Here, We are going to learn How we can search for data in Firebase. To do so follow the below steps:
Step 1: If you are new to firebase then please refer to this.
Step 2: Go to urls.py file and create a path to move to the webpage to search for data.
Python
from django.contrib import adminfrom django.urls import pathfrom . import views urlpatterns = [       #when we are moving to search then move to this url    path('search/', views.search),       #showing search detail on this url    path('searchusers/', views.searchusers),]
Step 3 : Then move to views.py file and write the following function to render to html page. 
Python
from django.shortcuts import renderfrom django.views.decorators.http import require_http_methodsfrom django.views.decorators.csrf import csrf_exemptfrom django.contrib.auth.decorators import login_requiredimport pyrebase config={        "databaseURL": "*********************",    "projectId": "*******************",   }firebase=pyrebase.initialize_app(config)authe = firebase.auth()database=firebase.database() # move to this search.html page to search for contentdef search(request):    return render(request, "search.html")   # after typing what to search this function will be calleddef searchusers(request):    value = request.POST.get('search')         # if no value is given then render to search.h6tml    if value =="":        return render(request, "search.html")    title = request.POST['category']    if title =="":        return render(request, "search.html")    if value is None or title is None:        print(value ,"Value",title)        return render(request, "search.html")    else:        if title == "Users":            data = database.child('users').shallow().get().val()            uidlist = []            requid = 'null'                         # append all the id in uidlist            for i in data:                uidlist.append(i)                             # if we have find all the uid then            # we will look for the one we need               for i in uidlist:                val = database.child('users').child(i).child('name').get().val()                val=val.lower()                value=value.lower()                print(val,value)                                 # if uid we want is value then                # we will store that in requid                if (val == value):                    requid = i            if requid=='null':                return render(request, "search.html")            print(requid)                         # then we will retrieve all the data related to that uid            name = database.child('users').child(requid).child('name').get().val()            course = database.child('users').child(requid).child('course').get().val()            branch = database.child('users').child(requid).child('branch').get().val()            img = database.child('users').child(requid).child('imgUrl').get().val()            Name = []            Name.append(name)            Course = []            Course.append(course)            Branch = []            Branch.append(branch)            Image = []            Image.append(img)            comb_lis = zip(Name, Course, Branch, Image)                         # send all data in zip form to searchusers.html            return render(request, "SearchUsers.html", {"comb_lis": comb_lis})
 Step  4: Then we will move to search.html page and write the following code to search for data in firebase. Comments are written inside to understand it better. 
HTML
{% load static %}<html lang="en">   <head>      <title>Search Page</title>      <meta name="viewport" content="width=device-width, initial-scale=1.0">      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>      <link rel='stylesheet' href="{% static '/css/Search.css' %}">      <link rel="stylesheet" type="text/css" href="{%static '/css/footer.css' %}">   </head>   <body>      <div class="container">         <div class="inner">            <form method="post" action="/searchusers/">               {% csrf_token %}               <!--Type the name you want to search and click on submit-->               <input type="text" placeholder="Enter Title..." aria-label="Search.." name="search"                  id="search">               <select name="category" id="category" name="">                  <option value="">Select Category</option>                  <!--select type to user-->                  <option value="Users">Users</option>               </select>               <input type="submit" value="Find">            </form>         </div>      </div>   </body></html>
 Step  5: Then we will move to the searchusers.html page and it will show the retrieved data on the Webpage as shown in the output. 
HTML
{% load static %}<html lang="en">   <head>      <title>User's List</title>      <meta name="viewport" content="width=device-width, initial-scale=1.0">      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>      <link rel='stylesheet' href="{% static '/css/Search.css' %}">   </head>   <body>      <div class="tm-container">         <div class="tm-main-content">            <section class="tm-section tm-section-small text-center">               <!--Showing all the details we retrieved Here-->               {% for name,course,branch,image in comb_lis %}               <h1>Here are the results:</h1>               <div class="image">                  <img src="{{image}}" alt="Profile">                  <h3 class="tm-section-header3">Name: {{name}}</h3>                  <h3 class="tm-section-header2">Course: {{ course }},  {{ branch }}  </h3>               </div>               {% endfor %}            </section>         </div>         <br>      </div>   </body></html>
Output: 
 
ruhelaa48
gabaa406
Django-models
Firebase
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions