Django Framework Overview and Architecture
Django Framework Overview and Architecture
Introduction to Software
Software refers to a set of instructions, data, or programs used to operate computers and execute specific
tasks. It is the non-tangible component of computers, in contrast to the physical hardware. Software is
generally categorized into two main types: system software and application software.
1. System Software
System software is designed to provide a platform for other software. Examples include operating systems
(OS), device drivers, and utility programs.
2. Application Software
Application software allows users to perform specific tasks. It is often built on top of system software and
provides functionalities to solve user-specific problems.
Page |3
Django Notes
Stand Alone applications: - software programs that can be installed and run on a device without
requiring an internet connection.
Ex: - Notepad, Calculator, Microsoft Word, Adobe Photoshop, Autodesk 3D Max, Google Chrome
Mobile Applications: - a software application developed specifically for use on small, wireless
computing devices, such as smartphones and tablets, rather than desktop or laptop computers.
Ex: - games, social media platforms, email clients and banking apps.
Client Server applications: - A client usually does not share any of its resources, but it requests content
or service from a server. Clients, therefore, initiate communication sessions with servers, which await
incoming requests.
Examples of computer applications that use the client–server model are email, network printing, and
the World Wide Web.
Page |4
Django Notes
Framework:-
In general, a framework is a real or conceptual structure intended to serve as a support or guide for the
building of something that expands the structure into something useful.
Or Conceptual Guidelines or Architecture
Ex: - Bricks making--- Structure (molds) --- Architecture (Framework)
Or in simple words we can say that Framework is a platform that provides a foundation for developing
software applications.
Types of Frameworks
Web Frameworks:
Backend Frameworks: Handle server-side logic, database interactions, and application functionality.
Examples: Django (Python), Express ([Link]), Ruby on Rails (Ruby), Laravel (PHP), Spring (Java)
Frontend Frameworks: Manage client-side user interfaces and interactions.
Examples: React (JavaScript), Angular (JavaScript/TypeScript), [Link] (JavaScript), Svelte (JavaScript)
Mobile Frameworks:
Native Frameworks: Used for building applications specific to a particular operating system.
Examples: Swift (iOS), Kotlin (Android)
Cross-Platform Frameworks: Enable development of applications that run on multiple platforms from a
single codebase.
Examples: Flutter (Dart), React Native (JavaScript), Xamarin (C#)
Microservices Frameworks:
Support the development of microservices architecture, where applications are composed of small,
independent services.
Examples: Spring Boot (Java), Flask (Python), Service Fabric (C#)
IoT (Internet of Things) Frameworks:
Designed for building and managing IoT applications and devices.
Examples: Node-RED (JavaScript), Kaa (Java), ThingWorx (Java)
Page |5
Django Notes
Different architectures used to follow to design frameworks
Frameworks are often designed using well-established software architectures that help ensure
scalability, maintainability, and ease of use. There are much different architecture in market to design variety
of frameworks. Some of them are MVC, MVT, MVVM, MVP, N-tyre architecture, Component based
architecture, server less architecture, etc.
Here we will study only 2 types of architecture which are helpful and are basic in order to understand Django
Architecure
MVC
MVT
1. MVC:-
The Model-View-Controller (MVC) framework is an architectural/design pattern that separates an application
into three main logical components Model, View and Controller. MVC is one of the most frequently used
industry-standard web development frameworks to create scalable and extensible projects. The main goal of
this design pattern was to solve the problem of users controlling a large and complex data set by splitting a
large application into specific sections that all have their own purpose.
Model: Manages the data and business logic.
View: Presents data to the user and handles user interaction.
Controller: Acts as an intermediary between Model and View, processing user input and updating the
Model.
Example Frameworks: Ruby on Rails (Ruby), [Link] (C#).
Page |6
Django Notes
2. MVT:-
The MVT (Model View Template) is a software design pattern. It is a collection of three important components
Model View and Template. The Model helps to handle database. It is a data access layer which handles the
data.
The Template is a presentation layer which handles User Interface part completely. The View is used to
execute the business logic and interact with a model to carry data and renders a template.
Although Django follows MVC pattern but maintains its own conventions. So, control is handled by the
framework itself.
There is no separate controller and complete application is based on Model View and Template. That’s why it
is called MVT application.
See the following graph that shows the MVT based control flow.
Here, a user requests for a resource to the Django, Django works as a controller and check to the available
resource in URL.
If URL maps, a view is called that interact with model and template, it renders a template.
Django responds back to the user and sends a template as a response.
Page |7
Django Notes
What is Django?
Django is a web application framework written in Python programming language.
It is based on MVT (Model View Template) design pattern.
The Django is very demanding due to its rapid development feature.
It takes less time to build application after collecting client requirement.
This framework uses a famous tag line: The web framework for perfectionists with deadlines.
By using Django, we can build web applications in very less time. Django is designed in such a manner
that it handles much of configure things automatically, so we can focus on application development
only.
System Environment
System Environment refers to the overall setup of your operating system and the global environment where your
applications and tools run.
Virtual Environment
Virtual Environment (often abbreviated as venv in Python) is a tool that helps you create isolated environments for your
Python projects. Below are some reasons why virtual environments are used:
Isolation: Each virtual environment is a self-contained directory that contains its own Python interpreter and libraries.
This means you can have different versions of libraries for different projects without conflicts.
Dependencies: You can install and manage project-specific dependencies without affecting other projects or the global
Python installation.
Portability: Virtual environments can be recreated on other systems using a [Link] file, which lists all the
packages and their versions used in the project.
Page |8
Django Notes
Installation of Django:-
Step 1:- first create virtual environment by creating one empty folder at a specific location.
Step 2:- Now open that folder and navigate in its path and type CMD there to open command prompt.
Step 3:- After opening of command prompt, you can see that the folder is targeting to its path in the system.
Now with the help of python module you have to download virtual environment in a system by some name (let we call it
as myenv)
Step 4:- After downloading the virtual environment, now just have to activate that environment.
Command for activating the environment:- $ myenv\scripts\activate
(we have to use command prompt because it is batch file)
Page |9
Django Notes
Step 5:- After activating the virtual environment in the system, now we will download the Django.
$ pip install Django
Step 6:- After downloading Django in order to check whether it is downloaded or not, there is a command to verify,
$ pip list / pip freeze
now you can see list of different packages that are downloaded along with the Django.
Project creation
Step 7:- After downloading Django, we can start creating project and To create a Django project, we can use the
following command. projectname is the name of Django application.
$ django-admin startproject projectname
For rest of now, I will start my project by the name project1, so now my command becomes,
$ Django-admin startproject project1
P a g e | 10
Django Notes
Step 8:- Now my project folder is created so I have to change my project directory to work with my project. For that,
we have the command as
$ cd project1 (name of the project folder where we have to work)
Step 9:- now we have to move to our editor to work/develop our projects, basically we use visual studio for developing
the project
For moving into the visual studio we use, code .
P a g e | 11
Django Notes
Initially, this project is a default draft which contains all the required files and folders.
Django project has a built-in development server which is used to run application instantly without any external web
server. It means we don't need of Apache or another web server to run the application in development mode.
To run the application, we can use the following command in command prompt (default PowerShell will be opened,
change it to command prompt)
Check for the server that has started and can be accessed at localhost with port 8000. Let's access it using the browser, it
looks like the below.
P a g e | 12
Django Notes
Look server has started and can be accessed at localhost with port 8000. Let's access it using the browser, it looks like
the below.
The application is running successfully. Now, we can customize it according to our requirement and can develop a
customized web application.
P a g e | 13
Django Notes
Django App:
In this topic, we will create app inside the created project. Django application consists of project and app, it also
generates an automatic base directory for the app, so we can focus on writing code (business logic) rather than creating
app directories.
The difference between a project and app is, a project is a collection of configuration files and apps whereas the app is a
web application which is written to perform business logic.
Creating an App:
To create an app, we can use the following command.
$ python [Link] startapp appname
Let us give appname as app1, now the command will be
$ python [Link] startapp app1
P a g e | 14
Django Notes
1. Open [Link]:
Locate your project's [Link] file, which is usually found in the project directory (e.g., project1/[Link]).
Ensure that your app name is a string matching the name of the app directory, and it should be in quotes.
4. Verify:
You can verify that the app is correctly registered by running the development server and checking if the app is working
as expected.
P a g e | 15
Django Notes
Writing views:
In Django, views are Python functions or classes that receive web requests and return web responses. Views are
responsible for handling the logic of application and determining what data to send to the user. Let us study how to
write views in Django, covering both function-based views (FBVs) and class-based views (CBVs):
urlpatterns = [
path('', home, name='home'),
]
class HomeView(View):
def get(self, request):
return HttpResponse("Hello, world!")
Here HomeView class-based view handles GET requests and returns a simple text response.
P a g e | 16
Django Notes
2. Map the View to a URL
In app’s [Link] file, map the view class to a URL pattern using the ‘as_view()’ method.
urlpatterns = [
path('', HomeView.as_view(), name='home'),
]
urlpatterns = [
path('admin/', [Link]),
path(“ ”,[Link]),
]
P a g e | 17
Django Notes
To create and manage URLs within a Django app, follow these steps:
1. Create [Link] in Your App
i. Navigate to Your App Directory: Ensure you're in the app's directory, e.g., myapp/.
ii. Create [Link]: If it doesn’t already exist, create a [Link] file in the app’s directory.
iii. Define URL Patterns: In myapp/[Link], define URL patterns for your app. Use the path function to map URLs to
views.
from [Link] import path
from . import views
app_name = 'myapp'
urlpatterns = [
path('', [Link], name='index'),
]
def index(request):
return render(request, 'myapp/[Link]')
urlpatterns = [
path('admin/', [Link]),
path('myapp/', include('[Link]')),
]
path('myapp/', include('[Link]')): Includes the URLs defined in myapp/[Link] under the /myapp/ path
P a g e | 18
Django Notes
Render Function
In Django, the render function is used to generate an HTTP response by combining a given template with a context
dictionary. It's a common way to render HTML pages in Django views. The render function simplifies the process of
rendering templates and returning HTTP responses.
Basic Syntax
def my_view(request):
context = {
'key': 'value',
# other context variables
}
return render(request, 'my_template.html', context)
Parameters
request: The HTTP request object that is passed to the view function. It contains information about the request,
such as HTTP method, headers, and any submitted form data.
template_name: The name of the template file to be rendered. This should be a string representing the path
to the template relative to your TEMPLATES directory.
context: A dictionary containing the data to be passed to the template. This data will be used to populate the
template with dynamic content.
Example
Suppose you have a template called [Link] in your templates directory:
def greet_view(request):
context = {'name': 'User'}
return render(request, '[Link]', context)
P a g e | 19
Django Notes
When a user visits the URL mapped to greet_view, they will see the page with "Hello, User!" displayed.
Note:-
The render function is a shortcut for creating an HttpResponse object with the content rendered from a
template.
Using render is preferred over manually creating HttpResponse objects with raw HTML because it helps keep
your views clean and promotes better separation of concerns. It also allows for easy integration with Django's
template engine.
// [Link]
TEMPLATES = [
{
'BACKEND':
'[Link]',
'DIRS': [[Link](BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'[Link].context_processors.debug',
'[Link].context_processors.request',
'[Link].context_processors.auth',
'[Link].context_processors.messages',
],
},
},
]
P a g e | 20
Django Notes
APP_DIRS being True tells Django to look for a templates directory in each app.
3. Use Templates in views:
When rendering templates in views, refer to templates using their relative path within the ‘template’ directory
of the app.
For example, to render ‘my_template.html’ from ‘myapp/templates/myapp’ directory, we us:
from [Link] import render
def my_view(request):
context = {'key': 'value'}
return render(request, 'myapp/my_template.html', context)
Directory structure
P a g e | 21
Django Notes
Inheritance (DTL)
Template inheritance is a powerful feature in Django that helps you create a consistent look and feel across your site
while allowing for flexibility in individual pages. It works similarly to inheritance in object-oriented programming, where
you can create a base template that other templates inherit from, reusing common elements and overriding specific
sections as needed.
How Template Inheritance Works
<main>
{% block content %}
<!-- Default content -->
{% endblock %}
</main>
<footer>
<p>© 2024 My Site</p>
</footer>
</body>
</html>
In this base template, {% block title %} and {% block content %} are placeholders that child templates can
override.
P a g e | 22
Django Notes
2. Create Child Templates:
Child templates inherit from the base template and override the blocks to provide specific content for different pages.
Note:-
{% extends '[Link]' %}: This tag tells Django that the template should inherit from [Link]. It should be
the first tag in the template.
{% block blockname %}: Defines a block that can be overridden by child templates. You can define a block in the
base template and override it in child templates.
{% include 'template_name.html' %}: You can include other templates within your templates to break down
complex layouts into smaller components.
P a g e | 23
Django Notes
DTL Tags:
Django Template Language (DTL) tags are special syntax used in Django templates to control the rendering of HTML,
manage logic, and handle dynamic content. They allow you to insert logic and variables into your templates in a clean
and readable way
Commonly used DTL tags and its purposes:
P a g e | 24
Django Notes
Context passing
In Django, context passing refers to the process of sending data from your view functions to your templates. This data is
used to dynamically render HTML content based on the information provided. Here’s a comprehensive guide on how to
pass and use context in Django.
1. In a view function:
We should pass context to a template by including it in a dictionary, when we call the ‘render’ function in view.
def my_view(request):
context = {
'variable_name': 'value',
'another_variable': 123,
}
return render(request, 'template_name.html', context)
class MyView(TemplateView):
template_name = 'template_name.html'
This method allows us to add or modify context data before it’s passed to the template.
Using context in Templates
1. Displaying Variables
P a g e | 25
Django Notes
{% if user.is_authenticated %}
<p>Welcome, {{ [Link] }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
<ul>
{% for item in item_list %}
<li>{{ [Link] }}</li>
{% empty %}
<li>No items found.</li>
{% endfor %}
</ul>
3. Passing context to other templates
{% block content %}
<p>{{ variable_name }}</p> <!-- Outputs: value -->
{% endblock %}
Template tags:
1. Creating a simple Template tag:
# myapp/templatetags/my_tags.py
from django import template
register = [Link]()
@register.simple_tag
def custom_tag(arg1, arg2):
return f"Processed {arg1} and {arg2}"
P a g e | 26
Django Notes
Example:
View:
def example_view(request):
context = {
'title': 'My Page Title',
'items': ['Item 1', 'Item 2', 'Item 3'],
}
return render(request, '[Link]', context)>
Template
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ title }}</h1>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
P a g e | 27
Django Notes
Rendering data list
P a g e | 28