Skip to content
Related Articles

Related Articles

Improve Article

Retrieve PDF File in Django From Firebase

  • Last Updated : 04 Aug, 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 and uses NoSQL for the storage of data.

Django, on the other hand, is a Python-based web framework which allows you to quickly create web application without all the installation or dependency problems that you normally will find with other frameworks.

Here we will learn how can we implement a simple Django app that can retrieve PDF files stored in firebase.  In this article, we will primarily focus on the Django aspect of it. If you wish to follow along, upload a dummy PDF in your firebase storage. If you are new to firebase then please refer to this.

Here, We are going to learn How we can retrieve PDF using Django in Firebase

Creating a project in Django:

Use the below command to create a Django project:



$ django-admin startproject pdffinder

Let’s verify your Django project works. Change into the outer project directory, if you haven’t already, and run the following commands:

$ python manage.py runserver

You’ll see the following output on the command line:

Performing system checks...
System check identified no issues (0 silenced).
You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate' to apply them.
April 14, 2021 - 15:50:53
Django version 3.2, using settings 'pdffinder.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Integrating Firebase Database to Django Project:

Now, we hope that you have already created a project in Django. If not then refer to How to Create a Basic Project using MVT in Django? Since we are using firebase as a Database, we need to install pyrebase . For this type the following command in terminal:

$pip install pyrebase4

Implementation:

Follow the below steps to retrieve PDF file in Django from firebase:

Step 1: Move into the pdffinder project directory.

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 admin
from django.urls import path
from . import views
 
urlpatterns = [
   
    path('search/', views.search),
]

Step 3: Then move to views.py file and write the following function to render to the HTML page. 



Python




from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
import pyrebase
 
config={
    
    "databaseURL": "YOUR DATABASE URL",
    "projectId": "YOUR PROJECT ID",
     
}
 
#firebase configuration & authentication
firebase=pyrebase.initialize_app(config)
authe = firebase.auth()
database=firebase.database()
 
def search(request):
    return render(request, "search.html")

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="{% 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 of pdf you want to retrieve
               <input type="text" placeholder="Enter Title..." aria-label="Search.." name="search"
                  id="search">
               
                // We will be selecting category of search
                // pdf as we want to retrieve odf
               <select name="category" id="category" name="">
                  <option value="">Select Category</option>
                  <option value="Question-papers">Search Pdf</option>
               </select>
               <input type="submit" value="Find">
            </form>
         </div>
      </div>
   </body>
</html>

 
 

Step 5: Go to urls.py file and create a path to move to searchnotes function in views.py to search for data.

 

Python




from django.contrib import admin
from django.urls import path
from . import views
 
urlpatterns = [
      path('searchpdf/', views.searchnotes),
]

Step 6: Then move to views.py file and write the following function to search for the PDF with the given name. 

Python




from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
import pyrebase
 
config = {
    "databaseURL": "********************",
    "projectId": "********************",
}
firebase = pyrebase.initialize_app(config)
authe = firebase.auth()
database = firebase.database()
 
# function to request a query
# to the firebase database
def searchpdf(request):
    value = request.POST.get("search")
    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:
        print(value)
        if title == "Question-papers":
 
            # search
            # for content inside the node Question-papers in firebase
            data = database.child("Question-papers").shallow().get().val()
            id = []
 
            # if found then append the value of i in id
            for i in data:
                id.append(i)
            for i in id:
                val = (
                    database.child("Question-papers")
                    .child(i)
                    .child("filename")
                    .get()
                    .val()
                )
                 
                # if id is equal to what we are
                # looking for the get the link or
                # return to serach page
                if val == value:
                    requid = i
                    fileurl = (
                        database.child("Question-papers")
                        .child(requid)
                        .child("fileurl")
                        .get()
                        .val()
                    )
                    return render(request, "searchNotes.html",
                                  {"fileurl": fileurl})
                else:
                    return render(request, "search.html")

Step 7: Then we will move to searchnotes.html page and will show the PDF as we got the link of PDF from firebase.

Python




{% load static %}
 
<html lang="en">
<head>
  <title>Questions & Notes</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="Search.css">
        <link rel='stylesheet' href="{% static '/css/Search.css' %}">
 
</head>
<body>
<div class="tm-container">
      <div class="tm-main-content text-center">
<embed
    src={{fileurl}}
    type="application/pdf"
    frameBorder="0"
    scrolling="auto"
    height="100%"
    width="100%"
></embed>
      </div>
 
  <br>
  <script>
    $(document).ready(function(){
      $('.dropdown-submenu a.test').on("click", function(e){
        $(this).next('ul').toggle();
        e.stopPropagation();
        e.preventDefault();
      });
    });
    </script>
    
</div>
</body>
</html>

Output Code:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :