<<

WEB APP DEVELOPMENT USING PYTHON AND

A Project

Presented to the

Faculty of

California State Polytechnic University, Pomona

In Partial Fulfillment

Of the Requirements for the Degree

Master of Science

In

Computer Science

By

Karan Kohli

2020 SIGNATURE PAGE

PROJECT: WEB APP DEVELOPMENT USING PYTHON AND DJANGO

AUTHOR: Karan Kohli

DATE SUBMITTED: Fall 2020

Department of Computer Science

Dr. Lan Yang ______Project Committee Chair Computer Science

Dr. Yu Sun ______Professor Computer Science

ii

ACKNOWLEDGEMENTS

I would first like to thank my project advisor Professor Lan Yang whose valuable guidance helped me whenever I ran into a trouble spot or had a question about my project and coding.

Professor Lan Yang consistently allowed this project to be my own work but steered me in the right the direction whenever he thought I needed it.

I would also like to thank my committee member: - Professor Yu Sun, for the participation.

Without their passionate participation and input, this project could not have been successfully conducted.

iii ABSTRACT

In today’s world there are so many people who want to be in fit, compete in the

bodybuilding competitions, lose weight, and burn fat. However, there isn’t a proper

platform where people can get all the needed information such as workout

instructions, lifting technique, diet guidance, fitness plans according to each

individual’s goals find the cheap dietary supplements and hire trainers/coaches.

In this project, I developed a web-app to help people in achieving their fitness

goals. The web-app, stay-fit.in, based Django, Python and SQL technologies, provides users information with regard to fitness, diet, training and fitness related products buying. The project is aimed to provide an efficient, secure and scalable web-app design.

iv

TABLE OF CONTENTS

SIGNATURE PAGE ...... ii

ACKNOWLEDGEMENTS ...... iii

LIST OF FIGURES ...... vi

CHAPTER 1 ...... 1

Introduction to Framework ...... 1

History of Django ...... 3

CHAPTER 3 ...... 4

Django Framework ...... 4

CHAPTER 4 ...... 7

Django Architecture ...... 7

CHAPTER 5 ...... 13

Project Code ...... 13

CHAPTER 6 ...... 28

Project Working ...... 28

CHAPTER 7 ...... 38

Conclusion ...... 38

REFERENCES ...... 39

v

LIST OF FIGURES

Figure 1 (MVT Django) ...... 8

Figure 2 (File Structure of Django) ...... 9

Figure 3 (Google OAuth2 Authorization )...... 13

Figure 4 (App Settings in Django) ...... 14

Figure 5 (Authentication Backend for Oath2) ...... 15

Figure 6 (Models Category) ...... 16

Figure 7 (List View Setup) ...... 17

Figure 8 ( for product app) ...... 17

Figure 9 (Urls for main project directory) ...... 18

Figure 10 (Add to Cart View setup) ...... 18

Figure 11 (Adding Stripe for payment) ...... 19

Figure 12 (Payments URLS) ...... 20

Figure 13 (Charge Function for handling payment) ...... 20

Figure 14 (Django Signals) ...... 22

Figure 15 (Signal Connections) ...... 22

Figure 16 (Calories Forms) ...... 23

Figure 17 (Models for Chat) ...... 24

Figure 18 (Django Serializers) ...... 25

Figure 19 (Views Setup for chat) ...... 26

Figure 20 (View Setup for messages in Chat) ...... 27

Figure 21 (Chat View for non- registered user) ...... 27

vi

Figure 22 (Homepage View) ...... 28

Figure 23 (Login View) ...... 29

Figure 24 (Add to cart) ...... 30

Figure 25 (In cart View) ...... 30

Figure 26 (Add Address) ...... 31

Figure 27 (Stripe Payment) ...... 31

Figure 28 (Add Card Info) ...... 32

Figure 29 (Order Status) ...... 32

Figure 30 (Calorie Counter) ...... 33

Figure 31 (Add Food Page)...... 34

Figure 32 (Select Food) ...... 34

Figure 33 (Chat View) ...... 35

Figure 34 (Admin Page for the trainer)...... 36

Figure 35 (Set Calorie goals) ...... 37

vii

CHAPTER 1

Introduction to Framework

A is a software that supports the development of a dynamic Web sites, applications and services. It provides a set of tools and functionalities that solves many common problems associated with , such as security features, database access, sessions, template processing, URL routing, internationalization, localization and much more.

1. Why are Frameworks useful?

A web framework is a code that makes web development quicker and easily by giving basic patterns for building reliable, scalable and maintainable web applications.

Web frameworks exist to make it easier for the developer to make a web application. Think of it to create shortcuts that can prevent otherwise overwhelming and repetitive code. For example, you may have written a code to handle data validation for your web application.

In order to prevent having to re-write that code from scratch each time you make a or , the web framework does it for you. A web framework differs from a web in that a runs the web application, while the web framework is more like a virtual database or library that helps speed up the development and writing process.

 Common Web Framework Functionalities:

Frameworks give functionality in their code or through extensions to complete everyday operations needed to run web applications. These operations involve:

1

I. URL routing

II. Input form managing and validation

III. HTML, XML, JSON, and other product setups with a templating engine

IV. Database connection configuration and resolute data manipulation through an object-

relational mapper (ORM)

V. Web security against Cross-site request forgery (CSRF), SQL Injection, Cross-

site Scripting (XSS) and other frequent malicious attacks

VI. Session repository and retrieval

 Examples of Web Frameworks

There are several web frameworks that have been designed to make coding and app development much easier for those in the industry. A few of the most popular and successful web frameworks include:

I. Django

II.

These frameworks assist codes such as HTML, Ruby, and Python when it comes to

constructing web applications and web-based services. There are a variety of things

that can be done with a web framework, such as the generation of HTML, the

formation of default templates, and the ability to access a library of coding

information to keep code simple and automated each time a developer makes a

new web application.

2

CHAPTER 2

History of Django

Django was created by two working for the Lawrence Journal-World in

Kansas. The newspaper needed a web application to publish news online. Eventually, the creators of Django realized that their solution had evolved into a real framework and made it publicly available. The Django framework owes its name to jazz guitarist Django

Reinhardt, who was able to play dazzling runs on his guitar even the two of his fingers were paralyzed after an accident. Once Django formed a community, its development took off, and the number of using Django grew rapidly. Some of the best Django apps include Pinterest, The Washington Post, Dropbox and Spotify.

3

CHAPTER 3

Django Framework

Django is an open-source python framework used for rapid development, pragmatic, maintainable, clean design and secure websites. The main goal of the Django framework is to allow developers to focus on the components of the application that are new instead of spending time on already developed components. Django is fully featured than many other frameworks.

Django helps you write software that is:

 Complete

Django follows the “Batteries includes” philosophy and provides almost everything developers might want to do “out of the box”. Because everything you need is part of one product, it all works seamlessly together, follows consistent design principles, and has extensive and up-to-date documents.

 Secure

Django helps developers avoid many common security mistakes by providing a framework that has been engineered to "do the right things" to protect the website automatically. For example, Django provides a secure way to manage user accounts and passwords, avoiding common mistakes like putting session information in cookies where it is vulnerable (instead cookies just contain a key, and the actual data is stored in the database) or directly storing passwords rather than a password hash. A password hash is a fixed-length value created by sending the password through a cryptographic hash function. Django can check if an entered password is correct by running it through the

4

hash function and comparing the output to the stored hash value.

However due to the "one-way" nature of the function, even if a stored hash value is compromised it is hard for an attacker to work out the original password.

Django enables protection against many vulnerabilities by default, including SQL injection, cross-site scripting, cross-site request forgery and clickjacking

(see Website security for more details of such attacks).

 Scalable

Django uses a component- based “sharing-nothing” architecture (each part of the architecture is independent of the others and can hence be replaced or changed if needed).

Having a clear separation between the different parts means that it can scale for increased traffic by adding hardware at any level: caching servers, database servers, or application servers. Some of the busiest sites have successfully scaled Django to meet their demands e.g., and Disqus.

 Maintainable

Django code is written using design principles and patterns that encourage the creation of maintainable and reusable code. In particular, it makes use of Do not repeat yourself (DRY)

Principle so there is no unnecessary duplication, reducing the amount of code. Django also promotes the grouping of related functionality into reusable ‘applications” and at lower level, groups related code into modules (along the lines of the Model View Control (MVC) pattern).

 Portable

Django is written in python, which runs on many platforms. That means it is not tied to any particular server platform and can run your applications on many flavors of Linux,

5

windows and Mac OS. Furthermore, Django is well-supported by many web hosting providers, who often provide specific infrastructure and documentation for hosting Django sites.

 Versatile

Django can be (and has been) used to build almost any type of website — from content management systems and wikis, through to social networks and news sites. It can work with any client-side framework and can deliver content in almost any format (including

HTML, RSS feeds, JSON, XML, etc.). The site you are currently reading is built with

Django! Internally, while it provides choices for almost any functionality you might want (e.g. several popular , templating engines, etc.), it can also be extended to use other components if needed.

6

CHAPTER 4

Django Architecture

For every website on the internet, there are 3 main components or code partitions, input

Logic, Business Logic and UI Logic.

These partitions of code have specific tasks to achieve, the input logic is the dataset and how the data gets to organize in the database. It takes that input and sends it to the database in the desired format. The Business logic is the main controller which handles the output from the server in the HTML or desired format. The UI Logic as the name suggest are the

HTML, CSS and JavaScript pages.

When the traditional approach was used for programming all this code was written in a single file, i.e. every piece of code increases the webpage size, which is downloaded and rendered by the browser. This was not a big problem back in the time, the webpages were largely static, and the websites did not contain much multimedia and large coding. Also, this architecture poses difficulty for developers while testing and maintaining the project as everything is inside one file.

Now, time is changing, and the websites are getting bigger and bigger while providing applications like cloud computing and online artificial intelligence training, online development environments and what not, these projects are all implemented using MVC architecture.

7

As mentioned, Django follows the MVT framework for architecture.

• M stands for Model

• V stands for View

• T stands for Template

MVT is generally very similar to that of MVC which is a Model, View, and Controller.

The difference between MVC and MVT here is the Django itself does the work done by the controller part in the MVC architecture. Django does this work of controller by using templates. Precisely, the template file is a mixture of HTML part and Django Template

Language also known as DTL.

Below is an architecture diagram for MVT.

Figure 1 (MVT Django) The Template handles the UI and architecture part of an application. The view does the logical part of the application and interacts with the Model to get the data and in turn modifies the template accordingly. Here as already mentioned, Django works as a

8

controller and gets a URL that is linked to the view part of the application and thus transports the user responses to the application. This complete interaction is dealt with this Django MVT architecture. When we create a project, there would some default files that would be created.

I used the above command to create a new project in my my_projects folder. Now let me show you the files that got created in the empty folder once the above command has been executed. These are the files that got created under the project first that we created.

There is, in turn, one more folder and a manage.py file that has been created. Now going into the first folder, we can observe the below files.

Figure 2 (File Structure of Django) So, the above files are those that got created automatically once a new project has been created.

• urls.py: As we know that our has to deal with many links, all the mappings

from one page to others can be done here.

• wsgi.py: This is used to deploy our project.

• manage.py: Gives us a URL where the project can be displayed.

9

After running this command, the output is as follows.

Output:

 Django Architecture Model

• In Django, the model does the linking to the database and each model gets mapped to

a single table in the database. These fields and methods are declared under the file

models.py

• With this linking to the database, we can each record or row from that particular table

and can perform the DML operations on the table.

• Django.db.models. The model is the subclass that is used here. We can use the import

statement by defining as from Django. dB import models.

• So, after defining our database tables, columns and records; we are going to get the

data linked to our application by defining the mapping in settings.py file under the

INSTALLED_APPS.

10

 Django View

• This is the part where actually we would be mentioning our logic. This coding is done

through the python file views.py

• This view also sends responses to the user when the application is used, to understand

briefly, we can say that this view.py can deal with HTTP Response.

• Now, after creating a view, how can we link it to our application? How do you think

that the system is going to understand to display a particular view? This can be done

by mapping the views.py in urls.py file. As already mentioned, urls.py keeps track of

all those different pages that we created and hence map each of them.

 Django Template

• This template helps us to create a dynamic website in an easy manner. The dynamic

website deals with dynamic data. Dynamic data deals with a scenario where each user

is displayed with their personalized data, as Facebook feeds, Instagram feeds, etc.

• The configuration of the template is done in settings.py file under

INSTALLED_APPS. So, python code would search for the files under the template

subdirectory. We can create an HTML file or import any from the

browser and place it under the template folder.

• And after that our usual linking of this file in urls.py and views.py to get a response is

mandatory.

• In this way after linking all these together and running the server, we can get our web

application ready.

11

 Django Template Language

In short, it is called as DTL. Django template has its own syntax in rendering the data on to the web page. For displaying a dynamic variable, the variable name is written inside the curly braces; denoted by “{{variable_name}}”. And to write if conditions, the syntax would be defined as: {% if condition %}. The same would be followed for the end if syntax also. Django uses render function in DTL. This render function takes three parameters.

• Request

• Mentioning the path of template in settings.py

• Parameters that contain all variables and can create as many as possible.

By these render functions we can have our DTL to make dynamic web pages.

• Create project command

Django-admin-startproject (name)

• Create the app

After creating the project now, we need to have an app for our products. So again use python manage.py startapp products the command to create the app. We are not focusing on the basic stuff. We know you knew that already just create the app and install the app in the settings.py file of the project.

12

CHAPTER 5

Project Code

I. Login Logout using Google Oath2

 OAuth

To provide user authentication Google supports several protocols including OAuth 2.

OAuth is an open protocol that provides secure authorization for web, mobile and desktop

applications in a simple and standard way. The protocol relies on a trusted third party to

establish the authentication process. It grants client access to a resource delegating the

authorization process to an external authorization server with the approval of the

resource owner.

Figure 3 (Google OAuth2 Authorization )

Fig. 1

13

 Installing the library

As a first step, we must install and enable the social-auth-app-Django library in our

Django project. We can install this library using either pip or pipenv according to our environment/personal preferences.

If we choose pip: pip install social-auth-app-django

Or if we choose pipenv:

Pip install social-auth-app-django

Once the library has been installed, we must add the app to the INSTALLED_APPS list in the project settings file using the social_django identifier:

Figure 4 (App Settings in Django)

14

 Adding the Google Oath2 authentication backend

Figure 5 (Authentication Backend for Oath2)

 Configuring the Google Authentication API

Once we added the backend, we must configure it to be used in the application. To perform this task, we go to the Google Developers Console and, once there, we navigate to the Credentials section in the left menu. A dialog will be displayed to either select or create a project. Currently, we still don’t have any project, so we’ll choose the second option to create it.

• Create the credentials selecting OAuth client ID in the Create Credentials menu.

• Select Web application and fill the required data. The Authorized redirect URIs are

used by the Google Authentication Backend in order to redirect the users to the

application again once the authentication is performed.

• Click on Create button and a key and a secret will be generated.

15

II. Setting up Ecommerce for the website

• Category Model

Created a field called primary category

Figure 6 (Models Category)

• Installed Pillow

Pillow is a python’s library that is used to show the image field on a webpage. It can be

installed using the same command as used for installing oAth that is pip install Pillow.

• Create view for showing the products

In the view.py I used class-based view called Home and the home page have a list of

products by using ListView.

16

ListView can be imported from django.views.genric

Figure 7 (List View Setup)

• Create a new for home view

To create a new url a new python file named urls.py is created in the product app and then path and view is imported

Figure 8 (Urls for product app)

17

After creating the url, urls need to be mapped in the project urlpatterns. That is in the main project directory.

Figure 9 (Urls for main project directory)

• Adding products to the cart o As we know adding product to the cart is the main function of any ecommerce website.

To start adding the products in the cart another app is created by using the same

Django command.

Figure 10 (Add to Cart View setup)

18

o In the Add to cart function product id or slug needs to be added so I passed the parameter of the function. Then product is filtered using get_object_or_404 method

and stored the product in the variable called item. o After creating the cart object by using get_or_create method to return a tuple. That is used to add the item in the cart every time the user clicks the add to cart button.

• Payments

The payment processing for the orders is done by using Stripe.

Figure 11 (Adding Stripe for payment)

Stripe can be installed by using pip install stripe and can be imported by using import stripe to the code. I used stripe.Charge function to charge the user. Stripe has Stripe

Payment documents which is super easy to use and can be implemented very easily for processing the payments.

19

Figure 12 (Payments URLS) Then I created a new function called charge that handles the payments and check if the

payment went through or not.

Figure 13 (Charge Function for handling payment)

I. Calories Counter

For the calorie tracking I have made three models.

• Food:

This model is made for storing all the food items that the user wants in their profile. Each

user is connected so that users can have food inventory of their own choice.

• Profile:

20

This is the main model that stores all the required data of the user for tracking calories. We got fields like calorie_count for counting calories for each day, food_selected for the food that the user selects for consuming, calorie_goal for setting a goal for calorie consumption each day. Date field is given to keep track of calorie consumption each day. Last field is all_food_selected_today for storing all the foods consumed in a day. This field is connected to PostFood class by a through argument. I am going the explain the reason later in views.py section. Lastly, I performed some calculations before saving each Model instance by overriding save method in the model. Here each time a food is selected

PostFood is created and connected to all_food_selected_today by a through field.

• Post Food:

This model is used for a through connection with all_food_selected_today field in Profile class. It will be used for keeping tracking of all food consumed by the user. More on this in our views.py section.

• Django Signals

Django signals is the feature that helps allow decoupled applications get notified when actions occur elsewhere in the framework. In a nutshell, signals allow certain senders to notify a set of receivers that some action has taken place. They are especially useful when many pieces of code may be interested in the same events.

In the calorie app I am defining a profile model instance for each day for that I have to create a profile instance that get created automatically when a user gets registered in the database. So, I have created a file called signals.py and the code is given below

21

Figure 14 (Django Signals)

So, Django signals send signals when something is changed, created or deleted in the

User model. The signals are connected by giving the arguments to post_save.connect method.

Figure 15 (Signal Connections)

22

• Forms

For the calories counter I have created four forms using Django forms.

Figure 16 (Calories Forms)

Create User Form

This is used for registering a new user.

SelectFoodForm

This form is used for the user to select the food that they consumed and wants to keep the track of.

AddFoodForm

This form is used for adding food items by the user or the trainer.

23

II. Chat

For creating the live chat, I have used Django Rest Framework. In addition, I have used

I. MaterializeCSS- For designing the Web UI

II. Jquery – For

III. Django Widget Tweaks- For handling the forms.

• Models

Here I have created 5 models

1. Sender - That identify the message sender.

2. Receiver – Identifies the message receiver.

3. Message – Its is CharField to store the messages.

4. Timestamp – To stores the date and time of the messages.

5. is_read – Keeps the track of the message is read or not.

Figure 17 (Models for Chat)

24

• Serializers

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

Figure 18 (Django Serializers)

Serializes can be imported from rest_framework. The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields.

In UserSerializer, password is specified write_only to avoid gettting the password displayed on GET request. We only need it on POST request in case of creation of a new user.

The sender and receiver of Message is serialized as SlugRelatedField to represent the target of the relationship using a field on the target. The field is specified as slug_field. It

25

also takes a 'many' arguments which identifies the relation is many-to-many or not. We gave it false since a message can only contain a single sender and receiver.

The 'queryset' argument takes the list of objects from which the related object is to be chosen.

• Views

In the user view when the message is sent by the sender it checks if the username is there in the primary key if not its gets all the user list. And then it returns the data to the serializer. The parser is used to parse the request object data in json format. If data is valid it gets saved or error 404 is shown

Figure 19 (Views Setup for chat)

26

• Message View

The message view is very similar to the User View, excepts it requires sender and receiver as URL parameters. The sender and the receiver expect the id of the users, associated with the message.

Figure 20 (View Setup for messages in Chat)

• Chat View

The chat view is simple as it renders the template with required context variables. If the

user is authenticated it directs the user to the main index file. If there is a new user it

directs the user to the register page.

Figure 21 (Chat View for non- registered user)

27

CHAPTER 6

Project Working

I. Home Page

The screenshot below is the home page view of my website where user can view different

plans the trainer offers and can buy trainer’s custom products and supplements. The user

has to sign in in order to make any purchase on the website. There is a search bar located

on the left side of the screen, user can search using the name of the product and per price.

On the nav bar there is a button to login and register for the web site including calories

counter page and chat page shortcut.

Figure 22 (Homepage View)

28

I. Login Page

• Below is the fig of the login page user or trainer can sign in using their email id or

using google.

• User can sign up using the different email id if they don’t have an google account.

• On the nav bar there are the shortcuts to navigate the contents of the website like

Shop, Add Food, Select Food, profile and Chat

Figure 23 (Login View)

29

II. Shop

• To Shop user can click on the desired product and it will take the user to the add to

cart page where user can add the product to the cart.

Figure 24 (Add to cart)

• After Clicking add to cart the website will show the cart page where user can proceed

to check out, continue shopping or add or remove items from the cart.

Figure 25 (In cart View)

30

• If the user clicked on proceed to checkout then the website will ask for the shipping

address. If the user had previously shopped, then his/her address will be saved. Or if

the user wishes to modify the address it can be done.

Figure 26 (Add Address)

• After entering the address user can make the payment with their card. The new page

going to open where the user can enter the card information.

Figure 27 (Stripe Payment)

31

• On this page user can enter the email address for the receipt followed by the credit

card information.

Figure 28 (Add Card Info)

• After successfully placing the order user can view the status of the order

Figure 29 (Order Status)

32

III. Calories Counter

• In the calories counter page trainer can set the calories for the day for their client.

• In the all food item section shows the list of all the food added by the trainer.

• User can update and delete the food items according to their wish

• It also shows the records from the past by date.

Figure 30 (Calorie Counter)

• In the add food page client or trainer can add food that will be consumed throughout

the day.

• The quantity of the item can be updated as well.

33

Figure 31 (Add Food Page)

• In the select food page client can select the food according to their meal plan by the

trainer and the calories will be updated automatically in the day’s goal

Figure 32 (Select Food)

34

IV. Chat

• In the chat page client can chat with the trainer and discuss the goals and ask for the

tips to stay fit.

• It shows online status for the client and the trainer.

Figure 33 (Chat View)

35

V. Admin Page for the trainer

• On the admin page trainer can add the products like clothing, supplements and the

fitness plans with the pictures that he wants offers on his website for the clients.

Figure 34 (Admin Page for the trainer)

36

• From the admin/calories page trainer can set the days calories goal as well as set the

diet for the day for his clients.

Figure 35 (Set Calorie goals)

37

CHAPTER 7

Conclusion

 Django

Django is an excellent choice for any developer who wants to build modern, robust web

applications with a minimal amount of code. As Django framework is versatile and

allows developers to concentrate on business logic instead of writing common utilities

which will be taken care of by Django itself. Django can complete the web application or

website within a short time with full security and offers fast, reliable and scalable

services based on traffic. It is popular, under active development, and thoroughly battle-

tested by the largest websites in the world.

 Project

• In my project I learned a lot about Django especially it is very easy to set up and gets

ready to go in no time. All the apps work independently so there is very less confusion.

• I want to design this website for the fitness trainers who are starting their carrier or

already established their carrier.

• They can use this platform to attract more clients and use its functions to establish a great

relationship with their clients and help them staying in good shape and healthy.

• Trainer can sell his custom-made shirts, plans and supplements.

• Trainer can setup calories goals and set a meal plan for a day or for the whole week for

their clients.

38

REFERENCES

1. Jaiswal, Sanjeev; Kumar, Ratan (22 June 2015), Learning Django Web

Development (1st ed.), Packt, p. 405, ISBN 1783984406

2. Ravindrun, Arun (31 March 2015), Django Design Patterns and Best

Practices (1st ed.), Packt,p. 180, ISBN 1783986646

3. Osborn, Tracy (May 2015), Hello Web App (1st ed.), Tracy Osborn,

p. 142, ISBN 0986365912

4. Bendoraitis, Aidas (October 2014), Web Development with Django

Cookbook (1st ed.), Packt, p. 294, ISBN 178328689X

5. Baumgartner, Peter; Malet, Yann (2015), High Performance Django (1st ed.),

Lincoln Loop, p. 184, ISBN 1508748128

6. Elman, Julia; Lavin, Mark (2014), Lightweight Django (1st ed.), O'Reilly Media,

p. 246, ISBN 149194594X

7. Percival, Harry (2014), Test-Driven Development with Python (1st ed.), O'Reilly

Media, p. 480, ISBN 1449364829

39