Building a Budget Manager with Django and Fauna

Written in connection with the Write with Fauna program.

This article will guide you to build a simple budget management application using the Django web framework and implement the database with Fauna. This budget manager would allow users to calcul…


This content originally appeared on DEV Community and was authored by Chukslord

Written in connection with the Write with Fauna program.

This article will guide you to build a simple budget management application using the Django web framework and implement the database with Fauna. This budget manager would allow users to calculate their expenditures, keep track of their savings and get financial advice based on their budget reports.

Prerequisites

To fully understand this tutorial, you are required to have the following in place:

  • Python 3.7 or newer.
  • Basic understanding of Fauna.
  • Basic understanding of Django.
  • A text editor.

With the above prerequisites out of the way, we can now begin building our budget management application.

Introduction to Fauna

If this is the first time you hear about Fauna, visit my previous article here for a brief introduction.

Creating The Budget Report Database

To create a Fauna database, you have to first sign up for an account. After signing up, you can create a new database by clicking on the CREATE DATABASE button on the dashboard.

After clicking on the button as shown in the image above, you need to give your database a name then save it.

Creating The Collections

You need to create a collection in your database, the Budget_Report collection. The Budget_Report collection will store the documents for all the reports created on the application. For the History days and TTL, use the default values provided and save.

Alt Text

After saving, your collection should be similar to the one in the image below. However, you don’t have data stored in your collection yet.

Alt Text

Creating The Indexes

You will create two indexes for your collections; report_index, and report_previous_index. The report_index index will allow you to scroll through data in the Budget_Report collection. It has one term, which is the date field. This term will enable you to match data with the username for easy querying. The date field is unique.

The budget_previous_index also allows you to scroll through data in the Budget_Report collection. However, this index allows matching with the report field to perform queries.

Below are what your indexes will look like after saving them.

Alt Text

Creating an API key

To create an API key, go to the security tab on the left side of your dashboard, then click New Key to generate a key. You will then be required to provide a database to connect to the key. After providing the information required, click the SAVE button.

Alt Text

You will be presented with your secret key as in the image above (hidden here for privacy) after saving your key. Make sure to copy your secret key from the dashboard and save it somewhere you can easily retrieve it for later use.

Building the Django App

Now you will be learning how to implement the various functionalities of the budget management application.

Cloning the App

Run the code below in your command line to clone the repo containing the Django app on Github.

git clone https://github.com/Chukslord1/FAUNA_BUDGET_MANAGER.git 

Importing the  Required Libraries

from django.shortcuts import render,redirect
from django.contrib import messages
from django.http import HttpResponseNotFound
from faunadb import query as q
import pytz
from faunadb.objects import Ref
from faunadb.client import FaunaClient
import datetime 

Initializing Fauna Client

To initialize the Fauna client, copy the code below and replace secret_key with the API key you created earlier.

client = FaunaClient(secret="secret_key") 

The Budget Manager Logic

This application will allow the user to enter his monthly allowance, then calculate his budget report. This report will include the user’s; expenditure rate, extra funds, and a bit of financial advice from the system.

Implementing the Application Logic

def index(request):
    if request.method=="POST":
        income=int(request.POST.get("income"))
        rent=int(request.POST.get("rent"))
        food=int(request.POST.get("food"))
        utilities=int(request.POST.get("utilities"))
        insurance=int(request.POST.get("insurance"))
        date=request.POST.get("date")
        extra=income-(rent+food+utilities+insurance)
        save=20*income/100
        if extra>0:
            if extra>save:
                advice= "Your expenditure rate is very good keep it up ?. At this rate you going to be rich ??. You have an extra $"+str(extra)
            else:
                advice= "Your expenditure rate is just fine ?. You have $"+str(extra)+" . You should try to save atleast "+" $"+str(save)+" "
        else:
            advice= "Your expenditure rate is very poor ? . At this rate you might go broke. You have $"+str(extra)+" . You should try to save atleast "+" $"+str(save)+" "
        try:
            report_date = client.query(q.get(q.match(q.index("report_index"), date)))
            messages.add_message(request, messages.INFO, 'Report Already Exists')
            return redirect("App:index")
        except:
            book = client.query(q.create(q.collection("Budget_Report"), {
                "data": {
                    "monthly_income":income,
                    "rent": rent,
                    "food": food,
                    "utilities":utilities,
                    "insurance":insurance,
                    "date":date,
                    "extra":extra,
                    "advice":advice,
                    "report":"True"
                }
            }))
            messages.add_message(request, messages.INFO, 'Report Created Successfully')
            return redirect("App:index")

    try:
        check_report= client.query(q.paginate(q.match(q.index("report_index"), datetime.datetime.today().strftime("%Y-%m"))))
        previous_report= client.query(q.paginate(q.match(q.index("report_previous_index"), "True")))
        all_reports=[]
        previous_reports=[]
        for i in check_report["data"]:
            all_reports.append(q.get(q.ref(q.collection("Budget_Report"),i.id())))
        for j in previous_report["data"]:
            if q.get(q.ref(q.collection("Budget_Report"),j.id())) in all_reports:
                pass
            else:
                previous_reports.append(q.get(q.ref(q.collection("Budget_Report"),j.id())))
        reports=client.query(all_reports)
        previous_reports=client.query(previous_reports)
        context={"reports":reports,"previous_reports":previous_reports}
        return render(request,"index.html",context)
    except:
        return render(request,"index.html")

In the python code above, we collected the user’s monthly income and other required information in the POST request sent. From this information, we calculated the extra funds and the amount the user needs to save. We then created an advice for the user based on the value of the save and extra variables. To add a report to the Budget_Report collection, we first checked if any report exists in the database carrying the date provided by making a request to the Fauna client with the report_index. If the data does not exist, you create a report and send a success message to the dashboard page.

Now we need to render the reports created on the dashboard for the user to see. The user needs to see all the reports for both the current month and other months. For the current month, we made a query to the Fauna client using the report_index to match all data for the current month, then saved it in the all_reports list to be queried and passed to the dashboard. While for the other months, we simply made a query to the Fauna client using the report_previous_index to match all active reports, stored the data in the previous_reports list, then eliminated the reports for the current month. Finally, we queried the previous_reports list then passed the data to be displayed on the dashboard.

After submitting the required information, the budget report will be displayed to you, as seen in the image below.

The App URLs

Here, we imported the required modules and defined our app’s urls connected to our created views.

from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
from . import views

app_name = "App"

urlpatterns = [

    path("", views.index, name="index"),

]

Conclusion

In this article, you learned how to build a budget management application with Fauna's serverless database and Django. We saw how easy it is to integrate Fauna into a Python application and got the chance to explore some of its core features and functionalities.

The source code of our budget manager application is available on Github. If you have any questions, don't hesitate to contact me on Twitter: @LordChuks3.


This content originally appeared on DEV Community and was authored by Chukslord


Print Share Comment Cite Upload Translate Updates
APA

Chukslord | Sciencx (2021-05-14T13:28:38+00:00) Building a Budget Manager with Django and Fauna. Retrieved from https://www.scien.cx/2021/05/14/building-a-budget-manager-with-django-and-fauna/

MLA
" » Building a Budget Manager with Django and Fauna." Chukslord | Sciencx - Friday May 14, 2021, https://www.scien.cx/2021/05/14/building-a-budget-manager-with-django-and-fauna/
HARVARD
Chukslord | Sciencx Friday May 14, 2021 » Building a Budget Manager with Django and Fauna., viewed ,<https://www.scien.cx/2021/05/14/building-a-budget-manager-with-django-and-fauna/>
VANCOUVER
Chukslord | Sciencx - » Building a Budget Manager with Django and Fauna. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/14/building-a-budget-manager-with-django-and-fauna/
CHICAGO
" » Building a Budget Manager with Django and Fauna." Chukslord | Sciencx - Accessed . https://www.scien.cx/2021/05/14/building-a-budget-manager-with-django-and-fauna/
IEEE
" » Building a Budget Manager with Django and Fauna." Chukslord | Sciencx [Online]. Available: https://www.scien.cx/2021/05/14/building-a-budget-manager-with-django-and-fauna/. [Accessed: ]
rf:citation
» Building a Budget Manager with Django and Fauna | Chukslord | Sciencx | https://www.scien.cx/2021/05/14/building-a-budget-manager-with-django-and-fauna/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.