You are on page 1of 37

TITLE: A Django Rest framework (DRF) app and React

Front-end system.

Student ID:189076015
Student Name:Md Rubayet Afsan
Major:Software Engineering
Graduation Year: 2022
Date: Wednesday, May 4, 2022
Hudong road 59, MA ‘Anshan, Anhui, China, 243002.
A Django Rest framework (DRF) app and React
Front-end system…..

Designed by
Md Rubayet Afsan
A THESIS

Submitted in partial fulfillment of the requirements for the degree

Bachelor of Software Engineering in Anhui University of

Technology.

Supervisor’s name: Dr. Zhou Yilian (周义莲)

CONTENTS
Abstract i

Declaration ii

Chapter 1 - Introduction 6-7


1.1. Introduction …………………………………………………............... 6-7

Chapter 2 - Theory 8-15

2.1. Introduction …………………………………………………………… 8


2.2. HTTP Request Methods …………………………………………….. 8-10
2.3. HTTP Status Response Codes ……………………………………… 11-13
2.4. Defining a RESTful API service ……………………………………. 13-14
2.5. Endpoints …………………………………………………………….. 14-15

Chapter 3 - Django Development 15-27

3.1. Introduction ………………………………………………………….. 15-17


3.2. Creating a new project and virtual machine………………………. 17-18
3.3. Start coding - first the URLs …………………………………………. 19
3.4. Creating the models …………………………………………………... 20
3.5. API views and serializers …………………………………………….. 21
3.6. Using the APIview …………………………………………………... 22-23
3.7. Using the built in generic class views……………………………… 23-24
3.8. Starting and using the Postman application ……………………… 24-25
3.9. Testing the application ……………………………………………… 25-26
3.10. Installing and configuring Cors …………………………………... 26-27

Chapter 4 – React Development 27-34

4.1. Introduction…………………………………………………………. 27-28


4.2. Build a new application…………………………………………… 28-29
4.3. Building the index.js component ………………………………….. 29
4.4. Material UI introduction …………………………………………… 30
4.5. Building the header and footer ……………………………………. 31
4.6. Connecting and collecting data from an API …………………… 32-33
4.7. We have data! ……………………………………………………… 34

Appendices 35-36

Appendices A – Visual Studio Code Editor ………………………… 35


Appendices B - Django Site administration Control Panel ………… 36

ABSTRACT

It is a web-based software with Backend app by python and Django which has
a connection to frontend for blogs that contains the latest posts and other
features. It includes Python, MySQL, JavaScript, TypeScript, React and all are
up to date technologies. It can maintain site administration for various kinds of
operations such as maintaining authentication, authorization, groups, users,
categories, posts, Data fetching from CSV, Crud stages and so many. This kind
of operation helps the management for future planning. This software can be
used in multiple API blogs so that the daily work will be easier. The goal of
this software is to ease all those processes and ensure a quick delivery for users.

Another core feature of my system is monitoring all the features and resources
from anywhere in the world. So, the management can monitor their users.

DECLARATION

I’m Md Rubayet Afsan, hereby declaring this research entitled “A Django


Rest framework (DRF) app and React Front-end system” is my own effort
under the supervision and guidance of Professor Dr.Zhou Yilian.

I furthermore declare that the work has not been submitted, in partial or in
full, to any other academic institution for any degree award.

Signature: Date: 05-04-2022

AUTHORIZATION

I’m Md Rubayet Afsan, certifying that Anhui University of Technology has


the right to preserve the submitted copies of the paper in photocopy, micro
printing and other forms. The confidential paper can be preserved by
Anhui University of Technology in the same way when it is declassified. It
is also certified that Anhui University of Technology has the right to open
the content of the paper, partial or full, to the public to read or borrow.

Supervisor’s Signature: Date: 05-04-2022

Chapter 1 - Introduction

1.1. Introduction

A Django Rest framework (DRF) app and React Front-end system is so important
and easy for blog users to control and post blogs with updated features. Users may
need the Django REST Framework, which is widely distributed as a standard
Python module, to get started with constructing RESTful APIs. It's sophisticated,
powerful, and incredibly simple to use, with an appealing and browsable API
version. Returning JSON objects is an option in the Django REST Framework. This
framework provides a sophisticated model serialization and displays the data in a
complete REST viewer utilizing basic function-based views. It's a versatile and
robust toolkit that makes creating web APIs simple for developers. It also includes
serializes and class-based generalized views for the API. Furthermore, it is
shortened as DRF because it is source code, and it stands for a Python library for
constructing web application programming interfaces.

For frontend development, there are a plethora of frameworks and libraries to


choose from. Not all of them are excellent. React is a popular and extensively used
frontend library (not a framework). React is a Facebook-developed open-source
JavaScript library for frontend development. Its component-based library enables
you to create high-quality web app user interfaces. This package works with
Virtual DOM and allows you to put HTML code inside JavaScript. Instead of
directly altering the browser's DOM, React builds a virtual DOM in memory and
does all the necessary manipulations there before making the changes in the
browser DOM. All React apps are built on the foundation of components.

These Components can be stacked with one another to create sophisticated


applications from simple building blocks. To populate data in the HTML DOM,
ReactJS uses a virtual DOM-based technique. The virtual DOM is quick because it
simply modifies individual DOM elements rather than reloading the entire DOM
every time. React components that relate to various parts are used to develop React
apps. These components are arranged within higher-level components that define
the application's structure. For example, I created a form with several features such
as input fields, labels, and buttons. Each form element may be written as a React
component, which I can then merge into a higher-level component, the form
component itself. The form components would specify the structure of the form
along with elements inside it.
Chapter 2 - Theory

2.1. Introduction

Theory of this system consists of API, REST, Error codes/ HTTP status codes,
statelessness and endpoints. API stands for Application Programming
Interface, which is a software interface that connects two programs. You
utilize an API every time you use a social media app, send an instant message,
or check the weather on your smartphone. REST, or Representational State
Transfer, is an architectural approach for establishing standards amongst
web-based computer systems, making it easier for them to communicate.
RESTful's systems are stateless and separate client and server concerns. We'll
explain what these phrases signify and why they're good for web services.
HTTP's response status codes show whether a particular HTTP request was
completed successfully. Every HTTP request is made in total isolation, which
is known as statelessness. When a client sends an HTTP request, it includes all
the information the server needs to respond. The server never uses
information from the client's prior queries. Basically put, an endpoint is one
conclusion of a communication channel. When an API interacts with another
framework, the touchpoints of this communication are considered endpoints.
For APIs, an endpoint can incorporate a URL of a server or benefit.

2.2. HTTP Request Methods

HTTP characterizes a set of task strategies to demonstrate the required activity


to be performed for a given asset. In spite of the fact that they can be things,
these ask strategies are sometimes alluded to as HTTP verbs. Each of them
actualizes a diverse semantic, but a few common highlights are shared by a
gathering of them: e.g. an ask strategy can be secure, idempotent, or

cache-able.

GET

The GET strategy demands a representation of the desired asset. Demands


utilizing GET ought to as it were to recover data.

HEAD

The HEAD strategy inquires for a reaction indistinguishable to a GET task, but
without the reaction body.

POST

The POST method submits an entity to the specified resource, often causing a
change in state or side effects on the server.

PUT

The PUT strategy replaces all current representations of the target asset with
the ask payload.

DELETE
The Erase strategy erases the required resource.

CONNECT

The Interface strategy builds up a burrow to the server recognized by the


target resource.

OPTIONS

The Choices strategy depicts the communication choices for the target
resource.

TRACE

The Follow strategy performs a message loop-back test along the way to the
target resource.

PATCH

The Fix strategy applies fractional adjustments to an asset.


2.3. HTTP Status Response Codes

HTTP reaction status codes show whether a particular HTTP task has been
effectively completed. Reactions are gathered in five classes: Informational
reactions (100–199) Successful reactions (200–299) Redirection messages
(300–399) Client blunder reactions (400–499) Server blunder reactions (500–599).

Information responses:

100 Continue This interval reaction shows that the client ought to proceed the
ask or disregard the reaction in case the ask is as of now finished.

101 Exchanging Protocols:

This code is sent in reaction to an Update ask header from the client and shows
the convention the server is exchanging to.

102 Preparing (WebDAV):

This code demonstrates that the server has gotten and is preparing the ask, but
no reaction is accessible yet.

103 Early Hints:

This status code is essentially aiming to be utilized with the Connect header,
letting the client specialist begin preloading assets whereas the server plans a
reaction.

202 Accepted:

The ask has been gotten but not however acted upon. It is noncommittal, since
there's no way in HTTP to afterward send an offbeat reaction showing the result
of the task. It is aiming for cases where another handle or server handles the
task, or for bunch processing.
203 Non-Authoritative Information:

This reaction code implies the returned metadata isn't precisely the same as is
accessible from the root server, but is collected from a local or a third-party
duplicate. This can be generally utilized for mirrors or reinforcements of another
asset. But for that particular case, the 200 Alright reaction is favored to this
status.

204 No Content:

There is no substance to send for this task, but the headers may be valuable. The
client specialist may upgrade its cached headers for this asset with the modern
ones.

205 Reset Content: Tells the client operator to reset the record which sent this
task.

206 Fractional Content:

This reaction code is utilized when the Run header is sent from the client to ask
as if it were a portion of a resource.

207 Multi-Status (WebDAV):

Conveys data around numerous assets, for circumstances where different status
codes may well be appropriate.

208 As of now Detailed (WebDAV):

Used interior a reaction component to maintain a strategic distance from more


than once identifying the inside individuals of different ties to the same
collection.

226 IM Utilized (HTTP Delta encoding):

The server has satisfied a GET request for the asset, and the reaction could be a
representation of the result of one or more instance-manipulations connected to
the current occurrence.

300 Numerous Choices:


The task has more than one conceivable reaction. The client specialist or client
ought to select one of them. (There's no standardized way of choosing one of the
reactions, but HTML joins to the conceivable outcomes are suggested so the
client can pick.)

301 Moved Permanently:

The URL of the asked asset has been changed forever. The unused URL is given
within the response.

302 Found:

This reaction code implies that the URI of the requested resource has been
changed temporarily. Further changes within the URI may well be made within
the future. Therefore, this same URI ought to be utilized by the client in future
requests.

303 See Other:

The server sent this reaction to coordinate the client to urge the asked asset at
another URI with a GET request.

304 Not Modified:

This is utilized for caching purposes. It tells the client that the reaction has not
been altered, so the client can proceed to utilize the same cached adaptation of
the reaction.

2.4.Defining a RESTful API service

A RESTful API is a structural fashion for an application program interface (API)


that employs HTTP demands to get to and utilize information. That information
can be utilized to Induce, PUT, POST and Erase information sorts, which alludes
to the perusing, overhauling, making and erasing of operations concerning
resources. An API for a web site is code that permits two software programs to
communicate with each other. The API spells out the right way for an engineer to
compose a program asking administrations from a working framework or other
application. A Serene API moreover alluded to as a Serene web benefit The REST
utilized by browsers can be thought of as the dialect of the web. With cloud
utilization on the rise, APIs are being utilized by cloud shoppers to uncover and
organize access to web administrations. REST may be a consistent choice for
building APIs that permit clients to put through to, oversee and connect with
cloud administrations adaptably in a conveyed environment. Serene APIs are
utilized by such locales as Amazon, Google, LinkedIn and Twitter. An API could
be a set of definitions and conventions for building and coordination application
programs. It’s some of the time alluded to as a contract between a data supplier
and a data user—establishing the substance required from the buyer (the call)
and the substance required by the maker (the reaction). For illustration, the API
plan for a climate benefit seems to indicate that the client supplies a zip code
which the maker answers with a 2-part reply, the primary being the tall
temperature, and the moment being the moon. In other words, in case you need
to be associated with a computer or framework to recover data or perform work,
an API makes a difference: you communicate what you need to that framework
so it can get it and fulfill the task. You can think of an API as a mediator between
the clients or clients and the assets or web administrations they need to induce.
It’s too a way for an organization to share assets and data whereas keeping up
security, control, and confirmation.

2.5. Endpoints
An API endpoint could be a point at which an API, the code that permits two
computer program programs to communicate with each other -- interfaces with
the computer program program. APIs work by sending demands for data from a
web application or web server and accepting a response. In other words, API
endpoints are the particular advanced area where demands for data are sent by
one program to recover the advanced asset that exists there. Endpoints indicate
where APIs can get to assets and offer assistance to ensure the correct working of
the joined program. An API's execution depends on its capacity to effectively
communicate with API endpoints. Software programs ordinarily have different
API endpoints. For example, Instagram's endpoints incorporate one that permits
businesses and makers to degree media and profile intelligence; one that permits
them to direct comments and their answers; and a third that permits them to find
hashtagged media.How API endpoints work Systems that communicate through
APIs are coordinated frameworks. One side sends the data to the API and is
called the server. The other side, the client, makes the demands and controls the
API. The server side that gives the asked data, or assets, is the API endpoint. For
a successful task to be prepared by the endpoint, the client must give a uniform
asset locator (URL), a strategy, a list of headers and a body. The headers give
metadata almost a task and the body holds the information sent by the client to
the server. Endpoints work in conjunction with API strategies. Strategies are
allowed demands that can be made, such as GET, Erase, Fix or POST. Strategies
regularly called verbs in communications sentence structure -- are regularly set
fair some time recently to the desired endpoint in a full URL.

Endpoints create: http://127.0.0.1:8000/admin/


http://127.0.0.1:8000/api/

http://127.0.0.1:8000/api/9/

Chapter 3 - Django Development

3.1. Introduction

Django may be a high-level Python web system that empowers quick


improvement of secure and viable websites. Built by experienced engineers,
Django takes care of much of the bother of web improvement, so can center on
composing apps without requiring to rehash the wheel. It is free and open
source, encompasses a flourishing and dynamic community, incredible
documentation, and numerous alternatives for complementary and paid-for
support. Django offers assistance to type in software that is: Complete Django
takes after the "Batteries included" reasoning and gives nearly everything
designers might need to do "out of the box". Since everything you wish is a
portion of the one "item", it all works consistently together, takes after reliable
plan standards, and has broad and up-to-date documentation. Versatile Django
can be (and has been) utilized to construct nearly any sort of site — from
substance administration frameworks and wikis, through to social systems and
news destinations. It can work with any client-side system, and can convey
substance in nearly any organization (counting HTML, RSS nourishes, JSON,
XML, etc). Internally, whereas it gives choices for nearly any usefulness you
might need (e.g. a few prevalent databases, templating motors, etc.), it can
moreover be expanded to utilize other components in the event that needed.
Secure Django makes a difference: designers dodge numerous common security
botches by giving a system that has been built to "do the correct things" to secure
the site naturally. For illustration, Django gives a secure way to oversee client
accounts and passwords, dodging common botches like putting session data in
treats where it is defenseless (instep treats fair contain a key, and the actual
information is put away within the database) or specifically storing passwords
instead of a watchword hash. A secret word hash may be a fixed-length esteem
made by sending the secret word through a cryptographic hash work. Django
can check in case an entered secret word is rectified by running it through the
hash work and comparing the yield to the put away hash esteem. In any case due
to the "one-way" nature of the work, indeed in case a put away hash esteem is
compromised it is difficult for an aggressor to work out the first password.
Django empowers assurance against numerous vulnerabilities by default,
counting SQL infusion, cross-site scripting, cross-site task fraud and clickjacking
(see Site security for more subtle elements of such attacks). Scalable Django
employs a component-based "shared-nothing" design (each portion of the
engineering is autonomous of the others, and can consequently be supplanted or
changed in case required). Having a clear partition between the distinctive parts
implies that it can scale for expanded activity by including equipment at any
level: caching servers, database servers, or application servers. A few of the
busiest locales have effectively scaled Django to meet their requests (e.g.
Instagram and Disqus, to title fair two). Maintainable Django code is composed
utilizing plan standards and designs that energize the creation of viable and
reusable code. In specific, it makes use of the Do not Rehash Yourself (DRY)
guideline so there's no pointless duplication, diminishing the sum of code.
Django moreover advances the gathering of related usefulness into reusable
applications and, at a lower level, bunches related code into modules (along the
lines of the Show See Controller (MVC) pattern). Portable Django is composed in
Python, which runs on many platforms. Which simply are not tied to any specific
server stage, and can run your applications on numerous flavors of Linux,
Windows, and macOS. Besides, Django is well-supported by numerous web
facilitating suppliers, who regularly give particular framework and
documentation for facilitating Django destinations. Web systems regularly allude
to themselves as "stubborn" or "unopinionated". Opinionated systems are those
with conclusions almost the "correct way" to handle any specific assignment.
They frequently bolster fast advancement in a specific space (understanding
issues of a specific sort) since the correct way to do anything is ordinarily
well-understood and well-documented. Be that as it may they can be less
adaptable at understanding issues outside their primary space, and tend to offer
less choices for what components and approaches they can use. Unopinionated
frameworks, by differentiation, have far less limitations on the most perfect way
to stick components together to attain an objective, or even what components
ought to be utilized. They make it simpler for engineers to use the foremost
appropriate apparatuses to total a specific assignment, though at the fetch that
you simply got to discover those components yourself. Django is "to some degree
stubborn", and thus conveys the "most excellent of both universes". It gives a set
of components to handle most web improvement errands and one (or two)
favored ways to use them. Be that as it may, Django's decoupled design implies
merely can ordinarily choose and select from a number of diverse alternatives, or
include back for totally unused ones on the off chance that craved. In a
conventional data-driven site, a web application holds up for HTTP demands
from the net browser (or other client). When a task is obtained the application
works out what is required based on the URL and conceivably data in POST
information or GET information. Depending on what is required it may at that
point peruse or compose data from a database or perform other assignments
required to fulfill the task. The application will then return a reaction to the net
browser, frequently powerfully making an HTML page for the browser to show
by embedding the recovered information into placeholders in an HTML format.

3.2. Creating a new project and virtual machine

1. Install Package and get Virtual Machine:


At First, install the python3-venv package environment by using the following
command below:

>Py .m venv venv

>venv\Scripts\activate

>pip install django

>django-admin startproject core .

>py manage.py startapp blog

>py manage.py startapp blog_api


3.3. Start coding - first the URLs

To plan URLs for an app, you make a Python module casually called a URLconf
(URL arrangement). This module is unadulterated Python code and could be a
mapping between URL way expressions to Python capacities (your views). This
mapping can be as brief or as long as needed. It can reference other mappings.
As a result of its unadulterated Python code, it can be developed dynamically.
Django moreover gives a way to interpret URLs agreeing to the dynamic dialect.
3.4. Creating the models

Django web applications get to and oversee information through Python objects
alluded to as models. Models characterize the structure of put away information,
counting the field sorts and conceivably moreover their greatest estimate, default
values, choice list choices, offer assistance content for documentation, name
content for shapes, etc. The definition of the show is autonomous of the basic
database select one of a few as a portion of extended settings. Once a chosen
database is utilized, then don’t go to conversation to it specifically at all, just
compose the model structure and other code, and Django handles all the messy
work of communicating with the database. A model is the single, conclusive
source of data for almost all the information. It contains the basic areas and
behaviors of the information that is put away. For the most part, each model
maps to a single database table. The basics: Each show could be a Python course
that subclasses django.db.models.Model. Each quality of the model speaks to a
database field. With all of this, Django gives you an automatically-generated
database-access AP.

3.5. API views and serializers

API views permit us to characterize capacities that coordinate standard HTTP


strategies like GET, POST, PUT, Fix, etc. Viewsets permit us to characterize
capacities that coordinate to common API question activities like : LIST, CREATE,
RETRIEVE, UPDATE, etc. To create objects available through the API to perform
a serialization. A serializer may be a system that permits complex information
such as querysets and show occurrences to be changed over to local Python
information sorts. At that point, these can at that point be effectively rendered
into JSON or other substance sorts. The turn around preparation is called
deserialization. The serializers work in a way comparable to Django’s Shape
classes. The Model Serializer class gives an alternate route that lets naturally
make a Serializer course with areas that compare to the Show areas and it'll
consequently create validators for the serializer.

3.6. Using the APIview

The API view and The ViewSet both classes are marginally distinctive and offer
their claim benefits in this post we'll be diving into API View. The API See is the
foremost essential sort of see able to utilize to construct our API. It empowers us
to portray the rationale which makes our API endpoint.
3.7. Using the built in generic class views

Django tries to require a few of that dullness at the show and format layers, but
web designers moreover encounter this boredom at the sea level.Django’s non
specific sees were created to ease that torment. They take certain common figures
of speech and designs found in see advancement and unique them so that we can
rapidly type in common sees of information without having to type in as well
much code.We can recognize certain common assignments, like showing a list of
objects, and type in code that shows a list of any protest. At that point the show in
address can be passed as an additional contention to the URLconf.Display list and
detail pages for a single object.Allow clients to form, overhaul, and erase objects –
with or without authorization. Taken together, these sets give interfacing to
perform the foremost common assignments engineers experience.
3.8. Starting and using the Postman application

Postman is an API client that produces simple for engineers to form, share, test
and document APIs. This can be done by permitting clients to make and spare
straightforward and complex HTTP/s demands, as well as peruse their reactions.
The result - more proficient and less monotonous work. Postman is exceptionally
helpful when it comes to executing APIs. Once entered and spared them, can
essentially utilize them over and over once more, without having to keep in mind
the precise endpoint, headers, API keys, etc.

3.9. Testing the application


For testing we need to run following command:

>pip install coverage

>coverage run --omit='*/venv/*' manage.py test

3.10. Installing and configuring Cors


A CORS setup could be a report that defines rules that recognize the roots that you
just will permit to get to your bucket, the operations (HTTP strategies) backed for
each beginning, and other operation-specific data. Within the S3 support, the
CORS arrangement must be a JSON report.

For installing and configuring Cors we need to run following command:

>pip install django-cors-headers


Chapter 4 - React Development

4.1. Introduction

React makes it effortless to intelligently make UIs. Plan straightforward sees for
each state in your application, and Respond will efficiently update and render
fair the proper components when your information changes.Declarative sees
make your code more unsurprising and less demanding to investigate. Respond
components execute a render() strategy that takes input information and returns
what to show. This example employs an XML-like language structure called JSX.
Input information that's passed into the component can be gotten to by render()
through this.props.In expansion to taking input information (gotten to through
this.props), a component can keep up inner state information (gotten to by
means of this.state). When a component’s state information changes, the
rendered markup will be upgraded by re-invoking render(). Utilizing props and
state, ready to put together a little Todo application. This case employs state to
track the current list of things as well as the content that the client has entered. In
spite of the fact that occasion handlers show up to be rendered inline, they will
be collected and executed utilizing occasion delegation.React permits you to
interface with other libraries and systems. This case employs surprising, an
outside Markdown library, to change over the esteem in genuine time.

4.2. Build a new application


For create a new react application we need to use following commands bellow:

>npx create-react-app blogapi .


>cd blogapi
>npm start
We also need to create components folder under the src folder and add files: Footer.js,
Header.js, PostLoadings.js, Posts.js

4.3. Building the index.js component


index. js regularly handles the app startup, steering and other capacities of the
application and does require other modules to include usefulness. In the event that
somebody running a website or web app it would too handle gotten to be an essential
HTTP web server supplanting the part of something more conventional like Apache.
4.4. Material UI introduction
Material UI is an open-source, front-end system for Respond components that has 60,500
also stars on github. It is built utilizing Less. Less (stands for Leaner Fashion Sheets),
could be a backward-compatible dialect expansion for CSS. Material UI is based on
Google’s Material Plan to supply a high-quality, computerized involvement whereas
creating front-end illustrations. Material Plan centers on giving strong and fresh plans – it
builds surfaces by focusing on how the components cast shadows and reflect light.There
are many key preferences of planning with Material UI: A few frontend systems are not
very well reported, this makes it difficult to create with them. In any case, Material UI has
nitty gritty documentation that makes it simple to explore through the system.Material
UI remains later with customary overhauls. The components all through are steady in
plan and color tones, which permits the created application/webpage to see stylishly
engaging.
4.5. Building the header and footer
Header.js:

Footer.js:
4.6. Connecting and collecting data from an API

First need to create app.js from React:


Then connect it with settings.py from Django:
4.7. Finally We have data!
Appendices

Appendix A---Visual Studio code editor:


Appendices B - Django Site administration Control
Panel:

You might also like