Django Workflow and Architecture

What is Django?

Django is a free and open-source web application framework written in Python. A framework is nothing over a group of modules that create development easier. They’re sorted along, and permit you to make applications or websites from associated existing supplies, rather than from scratch.

When you are building a website, you mostly would like the same set of components: how to handle user authentication (signing up, signing in, sign language out), a management panel for your website, forms, how to transfer files, etc.

Frameworks exist to save lots of you from having to reinvent the wheel and to assist alleviate a number of the overhead once you’re building a replacement website and the Django framework is one of all them.

The official project website describes Django as “a high-level Python net framework that encourages fast development and clean, pragmatic style. It takes care of a lot of effort of net development, thus you’ll be able to target writing your app with no need to reinvent the wheel. It’s free and open supply.”

Django offers an enormous assortment of modules that you’ll be able to use on your own. Primarily, frameworks exist to save lots of developers tons of wasted time and headaches and Django isn’t any totally different.

Django Architecture

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 MVC which is a Model, View, and Controller. The distinction between MVC and MVT here is that Django itself will do the work done by the controller half within the MVC design. Django will do this work of the controller by victimization templates. Precisely, the template file may be a mixture of hypertext markup language half and Django example Language conjointly referred to as DTL.

DijangoBenefits of Django Architecture

The Django Framework is predicated on this design and it really communicates between these 3 elements without having to put in writing complicated code. That’s why Django is gaining quality.

This design of Django has numerous blessings like:

1. Rapid Development:

Django design that separates in different components makes it easy for multiple developers to work on different aspects of the same application simultaneously. That’s additionally one among the options of Django.

2. Loosely Coupled:

Django has totally different elements that need one another at bound elements of the application, at each instant, that will increase the safety of the general website. Because the model file can currently solely save on our server instead of saving on the webpage.

3. Ease of Modification:

This can be a crucial fact of development as there is a unit of totally different elements in Django design. If there’s a modification in numerous elements, we tend not to modify it in alternative elements. This can be really one of the special options of Django, as here it provides us a way with more ability of our website than alternative frameworks.

4. Security:

When building high-end internet applications, security becomes a really crucial facet to reflect on. Django understands this concern and provides its best defender to avoid wasting your efforts. Using click-jacking, cross-site scripting, and SQL injections Django builds a robust wall for the application’s safety. User authentication is additionally a crucial feature to securely manage user accounts and passwords that Django provides.

5. Scalable:

Scalability can be understood as an ability of an application to work well when the size or volume of the platform increases. Django works effortlessly during this issue. Websites created with Django have the capability to handle multiple users at one time. Some well-liked websites victimization Django embody Spotify, Netflix, YouTube, Mozilla, Quora, etc.

Creating a New Project in Django

To start a new Django project, run the command below:

[code language=”css”]
django-admin startproject myproject
[/code]

After we run the command above, it will generate the base folder structure for a Django project.

Right now, our myproject directory looks like this:

[code language=”css”]
myproject/ <– higher level folder
|– myproject/ <– django project folder
| |– myproject/
| | |– __init__.py
| | |– settings.py
| | |– urls.py
| | |– wsgi.py
| +– manage.py
[/code]

  • manage.py: a shortcut to use the django-admin command-line utility. It’s used to run management commands related to our project. We will use it to run the development server, run tests, create migrations, and much more.
  • __init__.py: this empty file tells Python that this folder is a Python package.
  • settings.py: this file contains all the project’s configurations. We will refer to this file all the time!
  • urls.py: this file is responsible for mapping the routes and paths in our project. For example, if you want to show something in the URL /about/, you have to map it here first.
  • wsgi.py: this file is a simple gateway interface used for deployment.

Now everything is set up and we can run the server using the below command

[code language=”css”]
python manage.py runserver
[/code]

Now open the URL in a Web browser: http://127.0.0.1:8000 and you should see the success page, which means the server is running correctly.

Creating Django Apps

Django project contains many apps within it. An app can’t run without a project. You can create app by the following command

[code language=”css”]
django-admin startapp articles
[/code]

This will give us the following directory structure:

[code language=”css”]
myproject/
|– myproject/
| |– articles/ <– our new django app!
| | |– migrations/
| | | +– __init__.py
| | |– __init__.py
| | |– admin.py
| | |– apps.py
| | |– models.py
| | |– tests.py
| | +– views.py
| |– myproject/
| | |– __init__.py
| | |– settings.py
| | |– urls.py
| | |– wsgi.py
| +– manage.py
+– venv
[/code]

So, let’s first explore what each file does:

  • migrations: here Django stores some files to keep track of the changes you create in the py file, and to keep the database and the models.py synchronized.
  • admin.py: this is a configuration file for a built-in Django app called Django Admin.
  • apps.py: this is a configuration file of the app itself.
  • models.py: here is where we define the entities of our Web application. The models are translated automatically by Django into database tables.
  • tests.py: this file is used to write unit tests for the app.
  • views.py: this is the file where we handle the request/response cycle of our Web application.

Now that we created our first app, let’s configure our project to use it. Open settings.py file and find installed_apps block.

settings.py

[code language=”css”]
INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘Django.contrib.staticfiles’,
‘articles’
]
[/code]

Here we have added ‘articles’ in the installed apps section. Now the app is ready to run with the Django project.

Configuring Database

By default Django project comes with sqlite3 database but you can customize it to use MySQL or Postgresql as per the requirements.

settings.py

[code language=”css”]
DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.postgresql_psycopg2’,
‘NAME’: ‘blog’,
‘USER’: ‘postgres’,
‘PASSWORD’: ‘**********’,
‘HOST’: ‘localhost’,
‘PORT’: 5432,
}
}
[/code]

Now your project is connected with Postgres database and ready to run.

So now, we have learned how the MVT pattern works and the structure of the Django application along with the database configuration.

How To Integrate JWT in Python Django REST Framework?

Django REST Framework is one of the most popular Django web frameworks that has been used to build many successful projects. It provides a simple and easy-to-use interface for designing APIs and JSON web services, which is quite popular among startups. When working with the REST framework in Python, there are a few ways you can implement the JSON Web Token (JWT) type of authentication.

What Is JWT?

JWT is an encoded JSON string that is passed in headers to authenticate requests. It is usually obtained by hashing JSON data with a secret key. This means that the server doesn’t need to query the database every time to retrieve the user associated with a given token.

How JSON Web Tokens Work

When a user successfully logs in using their credentials, a JSON Web Token is obtained and saved in local storage. Whenever the user wants to access a protected URL, the token is sent in the header of the request. The server then checks for a valid JWT in the Authorization header, and if found, the user will be allowed access.

A typical content header will look like this:

[code language=”css”]
Authorization: Bearer gdh676hghu
[/code]

Work Flow of JWT

JWT Diagram

Advantages of JWT

  • No Session to Manage (stateless)
  • Portable
  • No Cookies Required, So It’s Very Mobile Friendly
  • Good Performance
  • JWT helps in securing APIs

Django REST Framework

Django REST framework (DRF) is an open source, mature and well supported Python/Django library that aims at building sophisticated web APIs. It is a flexible and fully-featured toolkit with modular and customizable architecture that makes possible development of both simple, turn-key API endpoints and complicated REST constructs.

Main Advantages of Django REST framework

  • Simplicity, flexibility, quality, and test coverage of source code.
  • Powerful serialization engine compatible with both ORM and non-ORM data sources.
  • Pluggable and easy to customize emitters, parsers, validators and authenticators.
  • Generic classes for CRUD operations.
  • Clean, simple, views for Resources, using Django’s new class based views.
  • Support for Model Resources with out-of-the-box default implementations and input validation (optional support for forms as input validation).
  • HTTP response handling, content type negotiation using HTTP Accept headers.

Implementing JWT in Django REST Framework

Django REST Framework comes with various default Authentication Classes. Basic Authentication, Session Authentication, and Token Authentication to name a few.

Token-based authentication is the most preferred method of implementing authentication in modern APIs. In this mechanism, the server generates a token for the authenticated user and the user has to send the token along with all the HTTP requests to identify themselves.

Install DRF and Django-rest-framework-jwt using pip

[code language=”css”]
pip install djangorestframework

pip install djangorestframework-jwt

pip install django
[/code]

In order to use JWT, we need to configure Django-rest-framework permissions to accept JSON Web Tokens.

In the settings.py file, add the following configurations:

[code language=”css”]
REST_FRAMEWORK = {

‘DEFAULT_AUTHENTICATION_CLASSES’: (

‘rest_framework_jwt.authentication.JSONWebTokenAuthentication’,

),

}
[/code]

Now add JWT API endpoint to the settings.py file as below

[code language=”css”]
from django.urls import path, include

from rest_framework_simplejwt import views as jwt_views

&nbsp;

urlpatterns = [

path(‘api/token/’,

jwt_views.TokenObtainPairView.as_view(),

name =’token_obtain_pair’),

path(‘api/token/refresh/’,

jwt_views.TokenRefreshView.as_view(),

name =’token_refresh’),

path(”, include(‘app.urls’)),

]
[/code]

The above endpoint will be used to generate and refresh the JWT token on every API call.

We will make use of the Django-REST Framework JWT Python module we installed at the beginning of this tutorial. It adds JWT authentication support for Django Rest Framework apps.

Let’s define some configuration parameters for our tokens and how they are generated in the settings.py file.

[code language=”css”]
import datetime

JWT_AUTH = {

&nbsp;

‘JWT_VERIFY’: True,

‘JWT_VERIFY_EXPIRATION’: True,

‘JWT_EXPIRATION_DELTA’: datetime.timedelta(seconds=3000),

‘JWT_AUTH_HEADER_PREFIX’: ‘Bearer’,

}
[/code]

  • JWT_VERIFY: It will raise a jwt. Decode Error if the secret is wrong.
  • JWT_VERIFY_EXPIRATION: Sets the expiration to True, meaning Tokens will expire after a period of time. The default time is five minutes.
  • JWT_AUTH_HEADER_PREFIX: The Authorization header value prefix that is required to be sent together with the token. We have set it as Bearer, and the default is JWT

Now you can use the JWT payload in your authentication method. Go to the views.py file and add the following code

[code language=”css”]
def authenticate_user(request):

email = request.data[’email’]

password = request.data[‘password’]

&nbsp;

user = User.objects.get(email=email, password=password)

if user:

payload = jwt_payload_handler(user)

token = jwt.encode(payload, settings.SECRET_KEY)

user_details = {}

user_details[‘name’] = "%s %s" % ( user.first_name, user.last_name)

user_details[‘token’] = token

user_logged_in.send(sender=user.__class__,request=request, user=user)

return Response(user_details, status=status.HTTP_200_OK)

[/code]

Every time the user wants to make an API request, they have to send the token in auth Headers in order to authenticate the request. You can test the API endpoint using Postman or any other API testing tools.

You can check the JWT token by using any of the PI test tools like Postman. Below is the screenshot of using postman to call the JWT API

JWTYou can find out the source code for the demo project here at Github

Conclusion

JWTs are the best way to securely exchange information between front-end and backend because they can be signed, which means we can be sure that the senders are who they say they are. The structure of a JWT allows us to verify that the content hasn’t been tampered with.

JWT makes the process of user authentication on the web much easier, providing a simpler way to exchange information between a server and a client.

The Django REST Framework is a RESTful framework for developing Django applications. It provides a high-level view on how to develop RESTful web services in Django.