0% found this document useful (0 votes)
13 views27 pages

Django Framework Overview and Architecture

The document provides an overview of software types, frameworks, and specifically focuses on Django, a web application framework based on the MVT architecture. It details the installation process, project creation, and the structure of Django projects and apps, as well as the role of views in handling web requests. Additionally, it outlines the importance of virtual environments for managing dependencies in Python projects.

Uploaded by

Sakshi R
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views27 pages

Django Framework Overview and Architecture

The document provides an overview of software types, frameworks, and specifically focuses on Django, a web application framework based on the MVT architecture. It details the installation process, project creation, and the structure of Django projects and apps, as well as the role of views in handling web requests. Additionally, it outlines the importance of virtual environments for managing dependencies in Python projects.

Uploaded by

Sakshi R
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INDEX

Content Page no.


Software and its types 3-4
Framework 5
MVC 6
MVT 7
What is Django 8
Virtual Environment 8
Install Django 9
Project creation 10-11
Project directory structure 12
Running server 12-13
Creating apps 14
App directory structure
Registering app in setting
Writing views
Writing project URL’s
Multiple Apps creation
Creating App URL’s
Connecting app URL’s to project
Render function
App level template
Inheritance (DTL)
(extends, block, include tags)
Context passing
Rendering data list
Dynamic routing
App level static
Load static, static tags
Project level templates
Project level static
Miniproject using all the topics
Django Notes

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.

 Operating Systems: Manage the hardware and software


resources of the computer. Examples: Windows, macOS,
Linux.
 Device Drivers: Enable hardware devices to communicate
with the OS.
 Utility Programs: Perform maintenance tasks. Examples:
Antivirus software, disk cleanup tools.

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.

Productivity Software: Examples: Microsoft Office, Google Docs.


Media Software: Examples: Adobe Photoshop, VLC Media Player.
Web Browsers: Examples: Google Chrome, Firefox.
Games: Examples: Minecraft, Fortnite.

Types of Application software

Stand alone applications

Application Software Mobile Applications


Client Server Applications

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.

Three tier architecture

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)

Framework in terms of programming:-


A framework is a collection of pre-written code, tools, and conventions that provides a structured foundation
for developing software applications. Frameworks simplify the development process by providing reusable
components and standardized ways to build and organize code, enabling developers to focus on the unique
aspects of their applications rather than reinventing common functionalities.

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#)

 Desktop Application Frameworks:


Used for developing applications that run on desktop operating systems.
Examples: Electron (JavaScript), Qt (C++), WPF (Windows Presentation Foundation in .NET)

 Game Development Frameworks:


Provide tools and libraries for creating video games.
Examples: Unity (C#), Unreal Engine (C++), Godot (GDScript/C#)

 Data Science and Machine Learning Frameworks:


Facilitate data analysis, machine learning, and scientific computing.
Examples: TensorFlow (Python/C++), PyTorch (Python), Scikit-learn (Python), Apache Spark (Java/Scala)

 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 and Virtual environment

System Environment
System Environment refers to the overall setup of your operating system and the global environment where your
applications and tools run.

Key characteristics include:


Global Packages: Libraries and packages installed here are available system-wide. This can lead to conflicts if different
projects require different versions of the same package.
Permissions: System-wide installations often require administrative (root) permissions, which can be restrictive and
risky if you’re modifying or upgrading critical system packages.
Consistency: Managing dependencies globally can be tricky because updates or changes to one package can affect other
projects or system tools that depend on it.

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)

Command for downloading virtual environment:- $ python –m venv 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

Project directory structure:-


A Django project contains the following packages and files. The outer directory is just a container for the application. We
can rename it further.
[Link]: It is a command-line utility which allows us to interact with the project in various ways and also used to
manage an application.
A directory (project1): located inside, is the actual application package name. Its name is the Python package name
which we'll need to use to import module inside the application.
 __init__.py: It is an empty file that tells to the Python that this directory should be considered as a Python
package.
 [Link]: Contains the ASGI application used for handling asynchronous requests.
 [Link]: This file is used to configure application settings such as database connection, static files linking
etc.
 [Link]: This file contains the listed URLs of the application. In this file, we can mention the URLs and
corresponding actions to perform the task and display the view.
 [Link]: It is an entry-point for WSGI-compatible web servers to serve Django project.

Initially, this project is a default draft which contains all the required files and folders.

Running the Django Project

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)

Process for changing it to command prompt is:


First go to ‘terminal’ section on top
After opening the terminal section, check below type and click on + symbol and select command prompt there
After selecting, check for the server by following command

$ python [Link] runserver

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

App directory structure:-


Each app directory typically includes:
 migrations/: A directory that contains migration files for database schema changes.
 __init__.py: Makes this directory a Python package.
 [Link]: Contains configurations for the Django admin interface.
 [Link]: Contains the app's configuration.
 [Link]: Contains the app's data models.
 [Link]: Contains test cases for the app.
 [Link]: Contains the app's view functions or classes.
 [Link]: (Optional) Contains URL declarations specific to this app.

P a g e | 14
Django Notes

Registering app in setting:-


To register an app in your Django project, you need to add it to the INSTALLED_APPS list in your project's [Link] file.
This tells Django that the app is part of your project and enables it to be recognized for various features like models,
migrations, admin interfaces, and templates.

Here's a step-by-step guide:

1. Open [Link]:
Locate your project's [Link] file, which is usually found in the project directory (e.g., project1/[Link]).

2. Add Your App to INSTALLED_APPS:


Find the INSTALLED_APPS list in [Link]. This is where you need to include the name of your app. For
instance, if your app is named app1, add it as follows:

Ensure that your app name is a string matching the name of the app directory, and it should be in quotes.

3. Save and Close [Link]:


After adding your app to INSTALLED_APPS, save the [Link] file.

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):

Function-Based Views (FBVs)


Function-based views are the traditional way to define views in Django. They are straightforward and suitable for simple
logic.
Example of a Function-Based View
1. Create a View Function
In app’s [Link] file, define a function that takes a request object and returns an HttpResponse object or a
derived response like render or redirect.

Here home is a function which returns a simple text response.


2. Map the View to a URL
In app’s [Link] file, map the view function to a URL pattern.

from [Link] import path


from .views import home

urlpatterns = [
path('', home, name='home'),
]

Class-Based Views (CBVs)


Class-based views provide a more organized way to handle views, especially for complex scenarios. They offer built-in
generic views to handle common tasks.
Example of a Class-Based View
1. Create a View Class
In your app’s [Link] file, define a class that inherits from Django’s generic views or View class.
from [Link] import HttpResponse
from [Link] import View
from [Link] import render

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.

from [Link] import path


from .views import HomeView

urlpatterns = [
path('', HomeView.as_view(), name='home'),
]

Writing project URL’s


The project’s [Link] file is where you define the main URL configuration for your project. This file typically includes URL
patterns for the project as well as references to the URL configurations of individual apps.

Example of [Link] in the Project Directory


Assume your project is named Project1.

from [Link] import admin


from [Link] import path
from app1 import views

urlpatterns = [
path('admin/', [Link]),
path(“ ”,[Link]),
]

Multiple Apps creation:-


For creating multiple apps, we have to create one each app at a single time and register it in INSTALLED_APPS in
Project1/[Link] section and provide views for each respective app and provide a path to it in the [Link] file of
project
Now when we provide path and run the server and call particular function we sees that only one function is getting
repeated to the concept of overriding. To overcome this overriding method, we have to provide some sensible alias
name to the views and have to call that path by alias name. Now after reloading the server we can see work of each app
as working correctly as we provided the instructions.

Creating App URL’s and Connecting app URL’s to project :-


When we go for creating multiple app creation, we observed that functions were overriding on other functions due to
same name, and every time to give alias name and provide a path is not possible. In order to overcome with this
problem we will go for creating app URL in each separate app.
This creating app urls helps the developer in the following concepts:
i. Routing Requests: Directs incoming requests to the correct view.
ii. Separation of Concerns: Keeps the project organized with modular URL handling.
iii. Dynamic URL Handling: Allows for flexible URL patterns with parameters.
iv. Reusability and Scalability: Facilitates growth and extension of the application.
v. Readability and Maintainability: Makes the codebase easier to manage.
vi. Namespace Management: Avoids conflicts and ensures distinct URL patterns.
By defining and managing URLs effectively, you ensure that your Django application is both functional and maintainable,
providing a clear path for handling different user interactions.

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'),
]

2. Create Views in Your App


Ensure you have corresponding views in [Link] to handle the URL requests.

from [Link] import render


from .models import MyModel

def index(request):
return render(request, 'myapp/[Link]')

3. Include App URLs in Project URLs


Include the app's [Link] in your project's main [Link] file (found in myproject/[Link])

from [Link] import admin


from [Link] import path, include

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

from [Link] import render

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:

<!-- templates/[Link] -->


<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>

You can render this template from a view like this:

from [Link] import render

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.

App level template


In Django, app-level templates are templates that are specific to a particular Django app within project. It is useful for
organizing your templates according to the apps they belong to, making your project easier to maintain and navigate.

Setting up App-Level Templates


To use app level templates, we need to follow some steps.
1. Create a Template Directory in App:
Inside Django app directory, create a subdirectory named ‘templates’. Inside this ‘templates’ directory we can
place our app-specific template files.

2. Configure ‘TEMPLATES’ setting:


Ensure TEMPLATES setting in [Link] is configured to include app-level templates. By default, Django is set
up to look for app-level templates if you use the APP_DIRS option in your TEMPLATES setting.
TEMPLATES setting might look like:

// [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',
],
},
},
]

Note:- DIRS is where we specify global template directories if needed.

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

1. Create a Base Template:


The base template contains the common structure and elements shared across multiple pages, such as headers,
footers, and navigation bars. Let us take example of a base template:

<!-- templates/[Link] -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}My Site{% endblock %}</title>
<link rel="stylesheet" href="{% static 'css/[Link]' %}">
</head>
<body>
<header>
<h1>Welcome to My Site</h1>
<nav>
<ul>
<li><a href="{% url 'home' %}">Home</a></li>
<li><a href="{% url 'about' %}">About</a></li>
</ul>
</nav>
</header>

<main>
{% block content %}
<!-- Default content -->
{% endblock %}
</main>

<footer>
<p>&copy; 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.

<!-- templates/[Link] --> <!-- templates/[Link] -->


{% extends '[Link]' %} {% extends '[Link]' %}

{% block title %}Home{% endblock %} {% block title %}About{% endblock %}

{% block content %} {% block content %}


<h2>Home Page</h2> <h2>About Us</h2>
<p>Welcome to the home page of our site.</p> <p>Learn more about us on this page.</p>
{% endblock %} {% endblock %}

In these child templates:

{% extends '[Link]' %} tells Django to use [Link] as the base template.


{% block title %} and {% block content %} are overridden with page-specific content.

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.

Advantages of Template Inheritance


i. Consistency: Ensures a uniform look and feel across your site by defining common elements in a base template.
ii. Maintainability: Makes it easier to update the site's design. Changes in the base template automatically apply to
all inheriting templates.
iii. Reusability: Promotes the reuse of common layout and components, reducing code duplication

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:

1. Variable Tag ({{ }})


The most basic and frequently used tag. It outputs the value of a variable.

2. Block Tags ({% %})


Block tags are used for control flow, loops, and template inheritance.

{% extends %} = Inherits from a base template.


{% block %} = Defines a block that child templates can override.
{% if %} = Conditional logic
{% for %} = Loops through a list or queryset.
{% include %} = includes another template.
{% with %} = Assigns a value to a variable within a block
{% url %} = Generates a url for a given view
{% static %} = Generates the url for static files

3. Filter Tags ({{ variable|filter }})


Filters modify the output of variables

‘date’ = formats date and time values.


‘lower’ = converts text to lowercase.
‘length’ = gets the length of a list or string.

4. Other useful tags


{% comment %} = adds comment to the template that are not rendered in the HTML output.
{% cycle %} = cycles through a list of values, useful for alternating row colors in a table.

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.

How to pass the context:-

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.

from [Link] import render

def my_view(request):
context = {
'variable_name': 'value',
'another_variable': 123,
}
return render(request, 'template_name.html', context)

In this, ‘variable_name’ and ‘another_variable’ are keys in the context dictionary.


‘value’ and ‘123’ are the corresponding values that will be accessible in the template.

2. In a class-Based view (CBV):


By using class-based views, we can pass context data by overriding the ‘get_content_data’ method.

from [Link] import TemplateView

class MyView(TemplateView):
template_name = 'template_name.html'

def get_context_data(self, **kwargs):


context =
super().get_context_data(**kwargs)
context['variable_name'] = 'value'
context['another_variable'] = 123
return context

This method allows us to add or modify context data before it’s passed to the template.
Using context in Templates

Once we pass context to a template, we can use it to render dynamic content.

1. Displaying Variables

<!-- template_name.html -->


<p>{{ variable_name }}</p> <!-- Outputs: value -->
<p>{{ another_variable }}</p> <!-- Outputs: 123 -->

2. Using context in control flow

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

<!-- [Link] -->


<header>
<p>Header Content</p>
</header>
<main>
{% block content %}
{% endblock %}
</main>

<!-- child_template.html -->


{% extends '[Link]' %}

{% 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}"

2. Using the template tag:


{% load my_tags %}

<p>{% custom_tag 'value1' 'value2' %}</p>

P a g e | 26
Django Notes
Example:

View:

from [Link] import render

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

You might also like