What Is Django And Why Is It One Of The Most Popular Web Application Development Frameworks?
Django Is A Python-based Web Application Development Framework That Enables The Rapid Development Of Secure, Highly Maintainable Websites.
Django helps web developers write clean, efficient, and robust code. Besides being among the most popular web frameworks, it is one of the most widely used web development technologies.
The mentioned framework has been used by popular platforms such as Instagram, YouTube, Google, etc. Django allows developers to produce applications faster by writing less code.
In addition, it is free and open source, supported by an active developer community, has excellent documentation, and provides developers with many valuable features.
How did Django come about?
Django was first developed in 2003 by Adrian Holovaty and Simon Willison and demonstrated its ability to handle high-traffic sites. Over the years, various versions of this framework have been published, the latest version of which is version 4.0, which was released in 2022.
Today, Django is a collaborative open source project with a wide range of developers worldwide actively involved in its development and bug fixes. In general, Django came about for the following reasons:
Clean design: Django code is highly readable because Django encourages developers to follow standard application development rules.
Short coding: less coding allows developers who work based on the rapid development methodology to produce a prototype in the shortest possible time.
Non-repetition: Django allows developers to write each program module instead of repeating it in different application parts, only in one piece, and use it many times (reusability).
Rapid development: Django allows developers to develop applications in the shortest possible time.
The relative independence of different components: Django has been developed in such a way that each of the elements and features of this framework is almost independent of each other. Of course, in some cases, there are dependencies.
General familiarity with Django architecture
Django is a platform for developing web-based applications using Python and supports MVC and MVT architectures. When we talk about applications with a user interface, we’re referring to a specific architecture called the Model-View-Controller (MVC) architecture. As it is clear from the name of the mentioned architecture, the MVC architecture consists of three components: Model, View, and Controller. MVT architecture is slightly different from MVC architecture.
The main difference between the above two architectures is that the Django library manages the controller component in the MVT model. The controller component is the software code that controls the interaction between the model and display components.
Considering that, in the MVT architecture, the Django library manages the controller component, it also monitors the operation of the Template component. The Template component is an HTML file combined with the Django Template Language.
Figure 1 shows how different components of the MVT architecture interact with each other to serve the user’s request. Based on the mentioned architecture, the developer defines the Model module, then, using View and Template, the specified Model is mapped to an Internet address. Finally, the Django platform provides the desired content or service to the user.
figure 1
Why do developers use Django?
Django provides the following features to developers:
Extensive functionality: Django offers various modules and functions for developers to do things most simply. Django provides integrated functionality and supports standard coding policies. In addition, it has up-to-date and complete documentation.
It’s flexible: Django can be used to build any website, from content management systems and wikis to social networks and news sites. The above approach can work with any user-side framework and serve content in almost any format (including HTML, RSS feeds, JSON, XML, etc.).
It’s safe: Django prevents developers from making common security mistakes that could put a website at serious risk. For this reason, compared to frameworks such as PHP programming language Laravel, its codes are of better quality from a security point of view. For example, Django provides a secure way to manage user accounts and passwords, avoids common mistakes like putting session information in vulnerable cookies or storing passwords directly, and uses a hash mechanism to protect passwords. Django cookies contain only one key; the actual data is stored in the database.
A password hash is a fixed-length value that encrypts the password using a hash function. Once the password is encrypted, the hash function is then used to compare the output of the hash with the original value to confirm the correctness of the password. Due to the one-way nature of the function, if the stored hash value is tampered with, Django will quickly notice this, preventing hackers from easily gaining access to passwords.
Django’s great benefits are protecting web-based applications against vulnerabilities such as SQL code injection, cross-site scripting, cross-site request forgery, and clickbait.
It’s scalable: Django uses an exceptional component-oriented architecture called “de-partitioning” so that each part of the architecture is independent of other parts and can be replaced or changed as needed. This explicit separation mechanism means that when traffic increases, hardware such as cache servers, database servers, or application servers can add to the infrastructure most easily. It is why websites with heavy traffic like Instagram use this framework.
Maintainable: Django code uses design principles and patterns that encourage developers to write maintainable and reusable code. This framework supports the principle of “Don’t Repeat Yourself” in the best way so that duplicate codes are not registered and the volume of regulations is reduced. In addition, it supports grouping related functions for reusability and grouping related code into modules aligned with the MVC architecture.
It is portable: Django is written in Python, which can run on different platforms. More precisely, you are not tied to any particular server platform and can run your applications on Linux, Windows, and macOS. Additionally, Django is supported by most web hosting providers.
What does Django code look like in programing?
Data may be read or written to a database depending on what is needed. In a traditional data-driven website, a web application waits for HTTP requests from the user’s web browser. The application checks the requirements when a request is received based on the URL and the POST or GE information data.
The program then sends a response to the web browser, often dynamically creating and sending an HTML page so the browser can display the received data correctly in HTML format. Typically, Django web-based programs put the codes needed to perform the mentioned steps in separate files (Figure 2). The components shown in Figure 2 are as follows:
figure 2
URLs: While handling requests from any URL through a single function is possible, writing a separate display function to manage each resource simplifies code maintenance. Here, a URL mapper is used to direct HTTP requests to the appropriate display component based on the requested URL. A URL mapper can match specific patterns of strings or digits that appear in a URL and pass them as data to a display function.
View: A request handler function receives HTTP requests and returns HTTP responses. Views access the data needed to respond to requests through models and delegate the process of formatting the response to models.
Models are Python objects that define the data structure of an application and provide mechanisms for managing (adding, modifying, deleting) and querying records in the database.
Templates: A template is a text file that defines the structure or layout of a file (such as an HTML page) with variables that are used to display the actual content. A template can be used to define the structure of any file and does not have to be HTML. A view can dynamically create an HTML page using an HTML template and provide the required data for a model.
As we mentioned at the beginning of the article, Django supports MVT and MVC, and the above pattern is based on the MVT architecture.
Send the request to the correct display function (urls.py)
Typically, a URL mapper is stored in a file called urls.py. In the following code snippet, the mapper (URL patterns) defines a list of mappings between paths (specific url patterns) and the corresponding display functions.
If an HTTP request with a URL matching the specified pattern is received, the corresponding display function is called, and the request is sent. The following code snippet illustrates this.
URL patterns = [
path(‘admin/’, admin.site.urls),
path(‘book/<int:id>/’, views.book_detail, name=’book_detail’),
path(‘catalog/’, include(‘catalog.urls’)),
re_path(r’^([0-9]+)/$’, views.best),
]
Request handling and management (views.py)
The View component is the heart of web applications. It receives HTTP requests from web clients and returns HTTP responses. For this purpose, display components have access to databases, processing patterns, etc.
The following code snippet shows an index display function that can be called by the URL mapper component of the previous code snippet. The following code snippet takes an HttpRequest object as a parameter (request) and returns an HttpResponse object. In this case, we don’t do anything with the request and get the response as a string.
# filename: views.py (Django view functions)
from Django.HTTP import HttpResponse
def index(request):
# Get an HttpRequest – the request parameter
# perform operations using information from the request.
# Return HttpResponse
return HttpResponse(‘Hello from Django!’)
Views are stored in a file called views.py.
Defining data models (models.py)
Django -based web applications manage and interact with data through Python objects called “models.” Models define stored data structure such as field types and maximum sizes, default values, picklist options, help text for documents, label text for forms, etc. The model definition is independent of the underlying database.
The code snippet below is a straightforward Django model for a Team object. The Team class is derived from the models. Model class. The following code snippet defines team name and team level as character fields. Also, the maximum number of characters stored for each record is specified. team_level can be one of several values; Hence, we define it as an optional field and provide a mapping between the displayed options and the stored data along with a default value.
# filename: models.py
from Django.DB import models
class Team(models. Model):
team_name = models.CharField(max_length=40)
TEAM_LEVELS = (
(‘U09’, ‘Under 09s’),
(‘U10’, ‘Under 10s’),
(‘U11’, ‘Under 11s’),
… #list other team levels
)
team_level = models.CharField(max_length=3, choices=TEAM_LEVELS, default=’U11’)
Running queries on data (views.py)
The Django model provides programmers with a functional programming interface to run simple queries on the database. The above interface can work with several fields simultaneously using different criteria and support complex expressions. The following code snippet shows a display function (resource controller) to display all U09 teams.
The line list_teams = Team.objects.filter(team_level__exact=” U09″) shows how we can use the model query API to filter out all records where the team_level field has exactly the value “U09” (note how this criterion acts as a filter for the argument).
## filename: views.py
from Django. shortcuts import render
from .models import Team
def index(request):
list_teams = Team.objects.filter(team_level__exact=”U09”)
context = {‘youngest_teams’: list_teams}
return render(request, ‘/best/index.html’, context)
The code above uses the render function to create an HttpResponse sent to the browser and act as a shortcut. The above code snippet creates an HTML file by combining a specified HTML template and some data added to the format (provided in a variable called context).
Data processing (HTML templates)
Templates allow you to specify the structure of an output document in which data is to be placed. Templates are most often used to create HTML, but they can make other types of documents.
Django supports its native template system and a popular Python library called Jinja2. The following code snippet shows what the render function calls the HTML template. The template is written assuming it will access a list variable called Youngest_teams when processed.
In the HTML body, we have a command that checks whether the Youngest_teams variable exists and reads its content through a loop.
The template displays the team_name value via each iteration’s <li> element.
## filename: best/templates/best/index.html
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>
<title>Home page</title>
</head>
<body>
{% if youngest_teams %}
<ul>
{% for the team in youngest_teams %}
<li>{{ team.team_name }}</li>
{% endfor %}
</ul>
{% else %}
<p>No teams are available.</p>
{% endif %}
</body>
</html>