Header Ads

Python Django with Google Firebase Tutorial: Firebase Database Retrieve Data to template #Part5


In previous tutorial we covered Pushing data to Firebase Database using Python Django & Pyrebase library. So, here next part comes i.e. Fetching/Retrieving data from Firebase database to Django Template.



Check out this video, code below follows the video to help

 If you like videos like this consider donating $1, or simply turn off AdBlocker. Either helps me to continue making tutorials.

Transcript / Cheat Sheet :

Templates :

Welcome.html :

First we need to edit our welcome.html, need to add Onclick function for redirecting check report button to check.html template

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
position : absolute;
right : 10px;
top : 5px
}
</style>
</head>
<body>
<div>
<button type="button" onclick="location.href='{% url 'log' %}'">Logout</button>
</div>
Welcome {{e}}
<br><br>
<button type="button" onclick="location.href='{% url 'create' %}'">Create Report</button>
<button type="button" onclick="location.href='{% url 'check' %}'">Check Report</button>
</body>
</html>

Check.html

<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
position : absolute;
right : 10px;
top : 5px
}
</style>
</head>
<body>
<div>
<button type="button" onclick="location.href='{% url 'log' %}'">Logout</button>
</div>
Welcome {{e}}
<br><br>
{% for time,dat,work in comb_lis %}
Date: {{dat}} &nbsp;Work: <a href="/post_check/?z={{time}}" >{{work}}</a>
<br>
{% endfor %}
</body>
</html>

Post_Check.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
position : absolute;
right : 10px;
top : 5px
}
</style>
</head>
<body>
<div>
<button type="button" onclick="location.href='{% url 'log' %}'">Logout</button>
</div>
Welcome {{e}}
<br><br>
Date: {{d}}<br>
Work : {{w}}<br>
Progress: {{p}}<br>
</body>
</html>

Views.py :

import pyrebase from django.shortcuts import render
from django.contrib import auth
config = {
'apiKey': "AIzaSyB0Il0NLQPxxDyMgoE0fOMd4pYUkbkZVvI",
'authDomain': "cpanel-5e873.firebaseapp.com",
'databaseURL': "https://cpanel-5e873.firebaseio.com",
'projectId': "cpanel-5e873",
'storageBucket': "cpanel-5e873.appspot.com",
'messagingSenderId': "579985583952"
}
firebase = pyrebase.initialize_app(config)
authe = firebase.auth()
database=firebase.database()
def signIn(request):
return render(request, "signIn.html")
def postsign(request):
email=request.POST.get('email')
passw = request.POST.get("pass")
try:
user = authe.sign_in_with_email_and_password(email,passw)
except:
message="invalid credentials"
return render(request,"signIn.html",{"messg":message})
print(user['idToken'])
session_id=user['idToken']
request.session['uid']=str(session_id)
return render(request, "welcome.html",{"e":email})
def logout(request):
auth.logout(request)
return render(request,'signIn.html')
def signUp(request):
return render(request,"signup.html")
def postsignup(request):
name=request.POST.get('name')
email=request.POST.get('email')
passw=request.POST.get('pass')
try:
user=authe.create_user_with_email_and_password(email,passw)
except:
message="Unable to create account try again"
return render(request,"signup.html",{"messg":message})
uid = user['localId']
data={"name":name,"status":"1"}
database.child("users").child(uid).child("details").set(data)
return render(request,"signIn.html")
def create(request):
return render(request,'create.html')
def post_create(request):
import time
from datetime import datetime, timezone
import pytz
tz= pytz.timezone('Asia/Kolkata')
time_now= datetime.now(timezone.utc).astimezone(tz)
millis = int(time.mktime(time_now.timetuple()))
print("mili"+str(millis))
work = request.POST.get('work')
progress =request.POST.get('progress')
idtoken= request.session['uid']
a = authe.get_account_info(idtoken)
a = a['users']
a = a[0]
a = a['localId']
print("info"+str(a))
data = {
"work":work,
'progress':progress,
}
database.child('users').child(a).child('reports').child(millis).set(data)
name = database.child('users').child(a).child('details').child('name').get().val()
return render(request,'welcome.html', {'e':name})
def check(request):
import datetime
idtoken = request.session['uid']
a = authe.get_account_info(idtoken)
a = a['users']
a = a[0]
a = a['localId']
timestamps = database.child('users').child(a).child('reports').shallow().get().val()
lis_time=[]
for i in timestamps:
lis_time.append(i)
lis_time.sort(reverse=True)
print(lis_time)
work = []
for i in lis_time:
wor=database.child('users').child(a).child('reports').child(i).child('work').get().val()
work.append(wor)
print(work)
date=[]
for i in lis_time:
i = float(i)
dat = datetime.datetime.fromtimestamp(i).strftime('%H:%M %d-%m-%Y')
date.append(dat)
print(date)
comb_lis = zip(lis_time,date,work)
name = database.child('users').child(a).child('details').child('name').get().val()
return render(request,'check.html',{'comb_lis':comb_lis,'e':name})
def post_check(request):
import datetime
time = request.GET.get('z')
idtoken = request.session['uid']
a = authe.get_account_info(idtoken)
a = a['users']
a = a[0]
a = a['localId']
work =database.child('users').child(a).child('reports').child(time).child('work').get().val()
progress =database.child('users').child(a).child('reports').child(time).child('progress').get().val()
i = float(time)
dat = datetime.datetime.fromtimestamp(i).strftime('%H:%M %d-%m-%Y')
name = database.child('users').child(a).child('details').child('name').get().val()
return render(request,'post_check.html',{'w':work,'p':progress,'d':dat,'e':name})

Urls.py :

from django.contrib import admin
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.signIn),
url(r'^postsign/',views.postsign),
url(r'^logout/',views.logout,name="log"),
url(r'^signup/',views.signUp,name='signup'),
url(r'^postsignup/',views.postsignup,name='postsignup'),
url(r'^create/',views.create,name='create'),
url(r'^post_create/',views.post_create,name='post_create'),
url(r'^check/',views.check,name='check'),
url(r'^post_check/',views.post_check,name='post_check'),
]
That's end up with great on Tutorial on Python Django with Firebase: Firebase Database Retrieve Data to Django Template, I hope you guys enjoyed it :)
Get full source code for Django Project Here.

3 comments:

  1. I think that thanks for the valuabe information and insights you have so provided here. retrieve data from USB flash drive

    ReplyDelete
  2. The method requires the combination of efforts of both the administrator and the developer for the database. Database Diagram Tool

    ReplyDelete
  3. These templates have the ability to make your online business run with efficiency and ease. They also ensure that your website approach remains systematic and organized.
    nagy pl├╝ss maci

    ReplyDelete

Powered by Blogger.