0% found this document useful (0 votes)
57 views42 pages

Introduction To Django Part-I

Django is a free, open-source web framework written in Python that simplifies web application development through its MVT architecture. It offers features like fast development, built-in libraries, security, scalability, and versatility, making it suitable for various applications. The document also covers installation, project and application structure, and best practices for URL management and template-based applications.

Uploaded by

dhrr8709
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)
57 views42 pages

Introduction To Django Part-I

Django is a free, open-source web framework written in Python that simplifies web application development through its MVT architecture. It offers features like fast development, built-in libraries, security, scalability, and versatility, making it suitable for various applications. The document also covers installation, project and application structure, and best practices for URL management and template-based applications.

Uploaded by

dhrr8709
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

Django Notes

●​ Django makes it easier to build better web apps more quickly and with less code.

Introduction to Django
●​ Django is a free, open-source, Python-based web framework used for developing web
applications.

Key Points:

●​ Free: No cost is required to develop commercial applications using Django.


●​ Open Source: The source code is publicly available, allowing customization and
modification according to our requirement and creating new frameworks (e.g.,
Chitkarago).

Examples of Open-Source Software:

●​ Operating Systems: Linux/Unix and its various distributions like Ubuntu, Fedora,
HP-Linux, CentOS.
●​ Python Variants:
○​ IronPython (for C#)
○​ Jython (for Java)
○​ Anaconda (for Data Science)

Django Framework Overview


●​ Django is written in Python.
●​ It follows the MVT (Model-View-Template) architecture.
○​ Model → Handles database interactions.
○​ View → Contains business logic and processes user requests.
○​ Template → Controls the presentation layer (HTML).

●​ It is maintained by the Django Software Foundation (DSF), a non-profit organization.


●​ Comparable to other technologies:
○​ Java → Maintained by Oracle
○​ C# → Maintained by Microsoft

Popular Websites Built with Django:

●​ YouTube
●​ Google
●​ Dropbox
●​ Yahoo

History of Django

●​ Created in 2003 as an internal project for the Lawrence Journal-World newspaper.


●​ Developed by Adrian Holovaty and Simon Willison.
●​ Released for public use on July 21, 2005.
●​ Named after the famous guitarist Django Reinhardt.

Official Website:

Django Project

Django’s Tagline: "The web framework for perfectionists with deadlines."

Current Version:

Django 5.1 (Check the official site for updates).


Top 5 Features of Django

1. Fast Development

●​ Django automates most of the development process, reducing coding efforts.


●​ Out of 100% work, minimum 95% work will be done by Django, only for 5%
developers are responsible.
●​ Example:
○​ A task that requires 20+ lines in Servlet(Java) can be done in just 2-3 lines in
Django.
○​ A basic project can be developed within a single day.

2. Fully Loaded

Django provides various built-in libraries for common functionalities, such as:

●​ User Authentication
●​ Email Handling
●​ Database Management

3. Security

Django protects against common security threats, including:

●​ SQL Injection
●​ Cross-Site Request Forgery (CSRF)

4. Scalability

Django supports high traffic loads(multiple client requests simultaneously ), making it scalable.

Example:

●​ Initially handling 100 requests, later scaling up to 500,000 requests without


performance issues.
5. Versatile

Django is used in various domains, such as:

●​ YouTube → Video streaming


●​ NASA → Scientific applications
●​ Universities → Educational platforms

For more details, visit:


Django Project Overview

Installing Django:

Prerequisites:

●​ Ensure that Python is installed on your system.

Installation Command:

​ pip install django

Installing a Specific Version:

●​ To install a particular version of Django, use:

​ ​ pip install django==3.2.4

Checking the Installed Django Version:

​ ​ python -m django --version


Django Project vs Django Application

Django Project:

●​ A Django project is a collection of multiple applications along with configuration files,


forming a complete web application.

Django Application:

●​ A Django application is a modular component of a project that can be reused across


different projects.

Django Project = django applications + configuration informations

Example:

A Banking Project may contain multiple applications:

●​ Loan App
●​ Insurance App
●​ Customer Management App
●​ Configuration Files (Database settings, Middleware, etc.)

Key Points:

●​ A Django project consists of multiple Django applications + configuration files.


●​ Individual applications can be reused in different projects.
●​ Multiple developers can work on different applications simultaneously.
●​ A Django application cannot exist without a Django project.
●​ First, we create a Django project, and then we create applications inside it.

Creating a Django Project:


Using django-admin Command:

●​ Django provides the django-admin command-line tool to create projects.

​ ​ django-admin startproject project1

Project Directory Structure:

●​ After running the command, the following structure will be created:

project1/
│-- [Link]
│-- project1/
│-- __init__.py
│-- [Link]
│-- [Link]
│-- [Link]
│-- [Link]

●​ Outer project1/ → The project folder.


●​ Inner project1/ → Stores project settings and configurations.

Understanding Django Project Files:

1.​ __init__.py (Package Indicator):

●​ if any folder contains __init__.py file then that folder is treated as a python
package. But this rule is applicable only up to python 3.3 version, it is an empty
file.
2.​ [Link] (Project Configuration):

●​ Stores project settings, similar to mobile phone settings.


●​ All the project related settings we have to configure here
●​ Contains configurations for:
○​ Installed apps
○​ Database settings
○​ Middleware
○​ Static files handling

3.​ [Link] (URL Routing):

●​ Here we have to store all the urls of our projects, basically mappings to the view
functions.

●​ A Django project contains the django apps and each app may contain the
various view functions which are responsible to trap the request and generate
the response.
●​ For every view we have to define a separate url pattern inside this file.
●​ These views can be a class based view(CBV) or a function based view(FBV).

4.​ [Link] (Web Server Gateway Interface)


●​ Required for deploying the application to production servers.
●​ Helps Django interact with web servers like Gunicorn, Apache, or Nginx.
●​ The required configuration is required in this file

5. [Link] (Asynchronous Server Gateway Interface)

●​ Handles asynchronous operations in Django.


●​ Enables real-time applications like chat, notifications, and WebSockets.

Difference Between Synchronous & Asynchronous:

●​ Synchronous (WSGI): A phone call – the next action happens only after the call
ends.
●​ Asynchronous (ASGI): A text message – you send it and continue with other
tasks.
🔹 Modern web applications prefer asynchronous processing for better performance.​
🔹 Python implements async using coroutines, async, and await keywords.

6. [Link] (Django Management Utility)

●​ This file contains the command-line utilities for administrative tasks.


●​ It contains various scripts to manage our application like:
○​ To start the django server
○​ Database migrations
○​ Creating applications
​ Example:
​ ​
●​ python [Link] runserver # Start the Django server
●​ python [Link] migrate # Apply database migrations
●​ python [Link] startapp app_name # Create a new app

Note: Django by default uses its own integrated web server and sqlite database, but we can
configure our own server or any other RDBMS s/w also.

Note: Inside the above generated files, only 3 files is required as a beginner:

1.​ [Link]
2.​ [Link]
3.​ [Link]

Django’s Pre-Installed Apps:

●​ Inside [Link], Django includes built-in applications:

INSTALLED_APPS = [
'[Link]', # Admin panel
'[Link]', # Authentication system
'[Link]',
'[Link]',
'[Link]',
'[Link]',
]

●​ These are the already provided applications by Django with a startup project.

Adding a Custom Application

●​ If you create an app named testapp, add it to INSTALLED_APPS:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'testapp', # Custom app added manually
]

Running the Django Development Server:

●​ Django itself provides an integrated webserver.


●​ Move inside the project1 main folder where "[Link]" file is available

cd project1
●​ Run the following command to start the server

​ python [Link] runserver

●​ Access the project at:


○​ [Link]
●​ To run the server at different port:
​ ​
​ ​ python [Link] runserver 7777

●​ Now, access it at:


○​ [Link]

Creating our first application inside the project project1:

Syntax:

python [Link] startapp <app_name>

Example:

​ python [Link] startapp testapp

●​ It will create another folder inside the main folder project1 with some files:

testapp/
│-- migrations/
│ │-- __init__.py
│-- __init__.py
│-- [Link]
│-- [Link]
│-- [Link]
│-- [Link]
│-- [Link]

●​ Purpose of Each File


1.​ [Link]:
○​ To customize the admin page
○​ We can register our models in this file, to use those models in django
admin interface
2.​ [Link]:
○​ Application level configurations(application specific) we need to define
inside this file.
3.​ [Link]:
○​ Application specific models we have to define inside this file.
4.​ [Link]:
○​ To define test cases to test our app functionality
5.​ [Link]: (most important file)
○​ In this file we have to define a view function to handle requests and
responses.
6.​ migrations folder:
○​ This folder is used to hold the Database migrations related information.

Activities required for the application:

1.​ After creating an app, register it inside INSTALLED_APPS in [Link]:

INSTALLED_APPS = [

'[Link]',

'[Link]',

'[Link]',

'[Link]',

'[Link]',

'[Link]',

'testapp', # Add this line

]
2.​ Create views for our application to provide the required functionalities inside the
[Link] file present inside our application "testapp".

Django supports two types of views:

1.​ Function-Based Views (FBVs)


2.​ Class-Based Views (CBVs)

Example of Function-Based View

Edit [Link] inside testapp:

●​ Here we have to define a view function to handle the request and generate the
response to the end user.

from [Link] import render

from [Link] import HttpResponse

def display(request):

return HttpResponse("<h1>Welcome to Django!</h1>")

●​ Each view function should take at least one argument: request, which
represents the HttpRequest object, this view function will be called by Django
internally by passing the request object.
●​ The view function must return an HttpResponse object.

3. Define the url-pattern for our view function inside the [Link] file(project level).

from [Link] import admin


from [Link] import path

from testapp import views # Import the view

urlpatterns = [

path('admin/', [Link]),

path('hello/', [Link]), # Map the view to a URL

Access the View

Visit:​
​ [Link]

Note: to mention the root url we need to use as follows:

path('', [Link]), #django internally manages '/' to start the url

Assignment:

Develop an application in the above Django project to display the current date and time on the
webpage.

Solution:

Step1: create another app called dateapp inside the above project.

python [Link] startapp dateapp

Step2: register this app inside the [Link] file at project level

​ INSTALLED_APPS = [
'[Link]',

'[Link]',

'[Link]',

'[Link]',

'[Link]',

'[Link]',

'testapp',

'dateapp'

Step3: Define the view function inside the [Link] file inside the dateapp folder

from [Link] import render

from datetime import datetime

from [Link] import HttpResponse

# Create your views here.

def get_date_time(request):

time = [Link]()

return HttpResponse(f"<h1>The Current date time is: {str(time)} </h1>")

Step4: Define the url mapping for the above view function inside the [Link] file of project1
folder(at the project level)
from testapp import views as v1

from dateapp import views as v2

urlpatterns = [

path('admin/', [Link]),

path('hello/', [Link]),

path('date/', v2.get_date_time),

Step5: run the server

​ python [Link] runserver

Step6: access the app using following url:

​ [Link]

Note: inside the single Django project we can define multiple applications and inside a single
application we can have multiple views also.(multiple view function inside the [Link] file).

we can create multiple view functions inside the [Link] file and then need to provide url
mapping information to each of the view functions separately.

Defining the url-patterns at the application level instead of project level:

Until now, we have been defining URL patterns at the project level inside the [Link] file.
However, this approach is not recommended for large projects.
Why Should We Define URLs at the Application Level?

1.​ Better Modularity:


○​ A Django project may contain multiple applications. If we define all URL
patterns in the project-level [Link], the file can become large and
unorganized, making it harder to manage.
2.​ Avoid Mixing URLs from Different Applications:
○​ If each application has 100+ views, managing all URL patterns in a single
[Link] will cause clutter and reduce readability.
3.​ Improved Reusability:
○​ Defining URLs inside an application-level [Link] allows us to reuse the entire
application in another project without modifying URLs.
○​ We can simply copy and paste the application folder into another Django
project and include its URLs easily.

Recommended Approach: Application-Level URL Configuration

Step 1: Create an [Link] File Inside each Application

●​ Inside each application (e.g., testapp) and (dateapp), create a file named [Link] (if not
already present).
○​ [Link] inside the testapp folder:

from [Link] import path

from . import views

urlpatterns = [

path('hello/', [Link])

○​ [Link] inside the dateapp folder:

from [Link] import path

from . import views

urlpatterns = [
path("date/", views.get_date_time)

Step2: Include Application-Level URLs inside the Project's level [Link] file.

○​ [Link] inside the project1 subfolder.

from [Link] import admin

from [Link] import path, include

urlpatterns = [

path('admin/', [Link]),

path('testapp/', include('[Link]')),

path('dateapp/', include('[Link]'))

Step3: Give the request as follows:

[Link]

[Link]

Advantages of Using Application-Level URLs:

✅ Keeps the project-level [Link] clean and organized​


✅ Improves maintainability and readability​
✅ Enhances reusability – applications can be used in multiple projects
Steps to develop template based application:

●​ In Django, templates help separate the presentation logic (HTML) from


the business logic ([Link]), making the application more modular and
maintainable.

Step 1: Create a Django Project

●​ Use the following command to create a Django project:

​ ​ django-admin startproject UniversityProject

●​ Navigate into the project directory:

​ cd UniversityProject

Step 2: Create a Django Application:

●​ Inside the project directory, create a Django application named StudentApp:

​ ​ python [Link] startapp StudentApp

Step 3: Register the Application in [Link]:

●​ To make Django aware of the new application, add StudentApp to the


INSTALLED_APPS list inside [Link]:

​ INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'StudentApp', # Registering the application
]

Step 4: Create the templates/ Folder

●​ Inside the StudentApp folder, create a templates/ directory to store templates specific
to the StudentApp..

UniversityProject/

│-- [Link]

│-- UniversityProject/

│-- StudentApp/

│-- templates/ # All templates for StudentApp application

Step 5: Create a Template ([Link])


●​ Inside the StudentApp/templates folder, create an HTML file named [Link]:
StudentApp/
│-- templates/
├── [Link]

●​ Add the following content to [Link]:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">


<title>Wish Page</title>

</head>

<body bgcolor="cyan">

<h1>Welcome to the Student App!</h1>

<p>This is the Student Home Page</p>

</body>

</html>

Step 6: Define a View in [Link] of StudentApp/ folder

●​ Inside the StudentApp/[Link], define a view function to render [Link]:​ ​

​ from [Link] import render

def home_view(request):

return render(request, "[Link]")

Step 7: Define a URL Pattern

●​ Define URLs at the App Level (StudentApp/[Link])

○​ Inside the StudentApp folder, create a [Link] file:

​ ​ from [Link] import path

from . import views

urlpatterns = [
path("", views.home_view),

Include this StudentApp’s [Link] file in the main [Link] file at project level
(UniversityProject/[Link] file):

from [Link] import admin

from [Link] import path, include

urlpatterns = [

path('admin/', [Link]),

path('student/', include('[Link]')), # Include URLs from StudentApp

Step 8: Start the Development Server

●​ Run the following command to start the server:

​ ​ python [Link] runserver

Step 9: Send a Request and Test the Application

●​ Open your browser and visit:

[Link]

Django Template Tags

What are Template Tags?


●​ Template tags allow us to inject dynamic content (data) from Python's [Link] into an
HTML template file.
●​ Template tags are also known as template variables.
●​ Django template tags follow the Jinja2-style syntax (similar to Flask).

Syntax for Inserting Dynamic Data:

●​ inside the html template

○​ {{variable_name}}

Example: Using Template Tags in Django

Step 1: Define a View in [Link]

●​ Modify the [Link] file to pass data to the template.

from [Link] import render

from datetime import datetime

# Create your views here.

def home_view(request):

date = [Link]()

my_dict = {"msg": date}

return render(request, "[Link]", context=my_dict)

Step 2: Use Template Tags in [Link]


●​ Inside the [Link] file, use {{ msg }} to display the dynamic data.

​ <body>

<h1>Welcome to the Student Home Page!</h1>

<p>The Current Date and Time is : {{msg}}</p>

</body>

Alternative Approach: Passing Data Directly

●​ Instead of defining a dictionary separately, we can pass data directly in the render()
function

​ def home_view(request):

date = [Link]()

my_dict = {"msg": date}

return render(request, "[Link]", my_dict)

●​ Or we can pass the dictionary directly:

def home_view(request):

date = [Link]()

return render(request, "[Link]", {"msg": date})

Note: Unlike Flask, where we can pass variables directly to templates, Django requires
passing a dictionary (as context) when sending data to templates.

Passing Multiple Data from [Link] to Template:

●​ In Django, we can pass multiple pieces of data from [Link] to an HTML template
using a dictionary as the context.
●​ Example: Passing Multiple Data Items
Modify [Link] in StudentApp:

​ ​

from [Link] import render

from datetime import datetime

def home_view(request):

date = [Link]()

my_dict = {"date": date, "name": "Chitkara University", "batch":


"CSE(AI)", "year": 2024}

return render(request, "[Link]", my_dict)

Modify [Link] Template:

<body>

<h1>Welcome to Student Home Page</h1>

<p>Have a great day!</p>

<h3>The Date and Time is: {{ date }}</h3>

<h3>University Name: {{ name }}</h3>

<h3>Batch: {{ batch }}</h3>

<h3>Year: {{ year }}</h3>

</body>

Random city selection example:

●​ To generate a dynamic city name and pass it to the template:


Modify [Link]:

import random

def home_view(request):

cities = ["Chandigarh", "Mohali", "Amritsar", "Jalandhar"]

selected_city = [Link](cities)

return render(request, "[Link]", {"city": selected_city})

Modify [Link]:

<body>

<h1>Welcome to the Wish Page!</h1>

<h3>The Selected City is: {{ city }}</h3>

</body>

Assignment:

●​ Pass the list of 5 city names from the view function to the template and display them
inside the template (HTML) using <li> tag.

Working with Static Files (CSS, Images, JavaScript) in Django:

●​ Static files like CSS, images, and JavaScript need to be placed inside the static folder
and referenced correctly in templates.

Steps to include the static files inside the html templates:

Step1: Create a folder named with "static" inside the application folder. same as templates
folder.
Step2: Inside the StudentApp/static folder create the "images" folder to keep all the images,
and the "css" folder to keep all the external css files.

StudentApp/

│-- static/

│ ​ │-- images/

│ ​ │-- css/

Step3: Using Static Files in Templates

(a) Load Static Files in Templates

●​ At the beginning of your HTML file, load the static tag:

<!DOCTYPE html> ​

{% load static %}

(b) Referencing an Image File

​ <img src="{% static 'images/[Link]' %}" alt="oops image not


found" width="200px" height="200px">

(c) Linking an External CSS File

​ <link rel="stylesheet" href="{% static 'css/[Link]' %}">

[Link]:

<!DOCTYPE html>

{% load static %}

<html lang="en">

<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Wish Page</title>

<link rel="stylesheet" href="{% static 'css/[Link]' %}">

</head>

<body>

<h1>Welcome to Student Home Page!</h1>

<h3>The City is: {{citydata}}</h3>

<img src="{% static 'images/[Link]' %}" alt="oops image not found"


width="200px" height="200px">

</body>

</html>

[Link]:

​ body{

background-color: aquamarine;

Now access the application using:

[Link]

Inter-Template Communication in Django:


●​ Django templates do not communicate with each other directly. Instead, templates
interact through views and URL routing.
Example: Navigating Between Templates

1. Create a New [Link] File

●​ Place this inside StudentApp/templates folder

<body bgcolor="cyan">

<h1>Welcome to Dashboard</h1>

</body>

2. Modify the View Function in [Link] in StudentApp folder

from [Link] import render

from datetime import datetime

import random

def home_view(request):

cities = ["Chandigarh", "Mohali", "Amritsar", "Jalandhar"]

city = [Link](cities)

return render(request, "[Link]", {"citydata": city})

def dashboard_view(request):

return render(request, "[Link]")

3. Configure URLs in [Link] (at application level)

from [Link] import path

from . import views

urlpatterns = [
path("", views.home_view),

path("dashboard/", views.dashboard_view),

4. Add Navigation Links in [Link]

<!DOCTYPE html>

{% load static %}

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Wish Page</title>

<link rel="stylesheet" href="{% static 'css/[Link]' %}">

</head>

<body>

<h1>Welcome to Student Home Page</h1>

<h3>The City is: {{citydata}}</h3>

<img src="{% static 'images/[Link]' %}" alt="oops image not found"


width="200px" height="200px">

<a href="./dashboard">Go To Dashboard</a>

</body>

</html>

Assignment:
Inside the [Link] file of the StudentApp create a link called Get All Student Details

when clicking on this link it should display the following Students list inside the bootstrap table:

students = [

{"roll": 101, "name": "Raj", "address": "amritsar", "marks": 700},

{"roll": 102, "name": "Simran", "address": "mohali", "marks": 720},

{"roll": 103, "name": "Rahul", "address": "", "chandigarh": 800},

{"roll": 104, "name": "Ankit", "address": "jalandhar", "marks": 750}

Solution:

Step1: Define the following view function inside the [Link] file of StudentApp

def student_list_view(request):

students = [

{"roll": 101, "name": "Raj", "address": "Amritsar", "marks": 700},

{"roll": 102, "name": "Simran", "address": "Mohali", "marks": 720},

{"roll": 103, "name": "Rahul", "address": "Chandigarh", "marks": 800},

{"roll": 104, "name": "Ankit", "address": "Jalandhar", "marks": 750}

return render(request, "[Link]", {"students": students})

Step2: Create a [Link] file inside the StudentApp/templates folder.

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<link
href="[Link]
css" rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6h
W+ALEwIH" crossorigin="anonymous">

</head>

<body>

<h1 class="text-center">All Student Details</h1>

<table class="table">

<tr>

<th>Roll</th>

<th>Name</th>

<th>Address</th>

<th>Marks</th>

</tr>

{% for student in students %}

<tr>

<td>{{ [Link] }}</td>

<td>{{ [Link] }}</td>

<td>{{ [Link] }}</td>

<td>{{ [Link] }}</td>

</tr>
{% endfor %}

</table>

</body>

</html>

Step3: Map the student_list_view function inside the StudentApp/[Link] file:

​ path('allstudents/', views.student_list_view)

Step4: Create the following link inside the [Link] file:

​ <a href="./allstudents">Get All Student Details </a>

Working with Dynamic URL:

Note: to generate the dynamic url instead of hardcoding it inside the html file, (similar to
url_for in flask) here we need to use the following approach:

1.​ specify a name to the url mapping. inside the [Link] file.

path("dashboard/", views.dashboard_view, name="dash"),

2.​ Use this name inside the [Link] file inside the template tag.

<a href="{% url 'dash' %}" class="btn btn-primary">Go To Dashboard</a>

Example passing the dynamic value using the url:

1.​ Define a view function inside the [Link] file:

from [Link] import HttpResponse

def student_detail_view(request, roll):


return HttpResponse(f"Student Roll is: {roll}")

2.​ Specify the url mapping inside the [Link] at application level with a name:

from [Link] import path

from . import views

urlpatterns = [

path("", views.home_view),

path("dashboard/", views.dashboard_view, name="dash"),

path('getstudent/<int:roll>/', views.student_detail_view,
name='student_detail')

3.​ Specify the link of the above student_detail inside the [Link] file.

<a href="{% url 'student_detail' roll=10 %}" class="btn


btn-success">View Student</a>

Optional: Managing the templates for all the applications at Project level:

●​ We can also manage the templates and static files for all the applications of a project at
project level. In this case we need to create the templates folder and static folder at project
level and specify their locations inside the [Link] file explicitly.

Example:

# Define TEMPLATE_DIR dynamically

TEMPLATE_DIR = BASE_DIR / "templates"

TEMPLATES = [

'DIRS': [TEMPLATE_DIR], # Use the dynamically generated path

]

And to keep all the app specific html files by creating app specific folders inside the templates
folder at project level.

​ UniversityProject2/

​ ​ |--[Link]

​ ​ |--templates/

​ ​ |​ |--StudentApp/

​ ​ |​ ​ |--[Link]

​ ​ |--StudentApp/

●​ Inside the StudentApp/[Link], define a view function to render [Link]:

​ ​

​ from [Link] import render

def home_view(request):

return render(request, "StudentApp/[Link]")

Optional: Managing the static files for all the applications at Project level:

●​ Similar to the templates, we can manage the static files for all the applications at Project
level also.

Steps to include the static files inside the html templates:


Step1: Create a folder named with "static" inside the main project
folder(UniversityProject2) folder. same as templates folder at project level.

Step2: Create the folder with the application name(here StudentApp) inside the static
folder to keep all the application specific static contents.

Step3: Inside the static/StudentApp/ folder create the "images" folder to keep all the
images, and the "css" folder to keep all the external css files.

Step4: Add the static folder path to the [Link] file so that Django can be aware of
our static contents.

STATIC_DIR = BASE_DIR / 'static'

STATICFILES_DIRS = [

STATIC_DIR,

OR we can use:

​ import os

STATICFILES_DIRS = [

[Link](BASE_DIR, 'static')

Step5: Using Static Files in Templates

(a) Load Static Files in Templates

●​ At the beginning of your HTML file, load the static tag:

<!DOCTYPE html> ​

{% load static %}

(b) Referencing an Image File

​ <img src="{% static 'StudentApp/images/[Link]' %}" alt="oops


image not found" width="200px" height="200px">
(c) Linking an External CSS File

​ <link rel="stylesheet" href="{% static 'StudentApp/css/[Link]' %}">

[Link]:

<!DOCTYPE html>

{% load static %}

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Wish Page</title>

<link rel="stylesheet" href="{% static 'StudentApp/css/[Link]' %}">

</head>

<body>

<h1>Welcome to Student Home Page</h1>

<h3>The City is: {{citydata}}</h3>

<img src="{% static 'StudentApp/images/[Link]' %}" alt="oops image


not found" width="200px" height="200px">

</body>

</html>

[Link]:
​ body{

background-color: aquamarine;

Now access the application using:

[Link]

Limitation for the managing templates and static files at project level:

●​ App Independence is Lost – If multiple apps rely on the same template, it may cause
conflicts.
●​ Harder to Maintain – Large projects require careful organization.
●​ Namespace Conflicts – If multiple apps have files with the same name, Django may get
confused.

Template Inheritance in Django:

●​ Template inheritance allows the creation of a base template that can be extended by other
templates.
●​ It is similar to the Template inheritance concept in Flask.

Step 1: Create a Base Template ([Link])

[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_block %} {% endblock %}</title>

<link
href="[Link]
css" rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6h
W+ALEwIH" crossorigin="anonymous">

<style>

body {

margin: 0;

padding: 0;

header {

background-color: aquamarine;

height: 10vh;

main {

background-color: beige;

height: 80vh;

}
footer {

background-color: aqua;

height: 10vh;

</style>

</head>

<body>

<header>

<h1 class="text-center">Welcome to the Chitkara University</h1>

</header>

<main>

{% block main_block %}

{% endblock %}

</main>

<footer>

<p class="text-center">&copy; This is the Footer Section</p>

</footer>

<script
src="[Link]
.[Link]"
integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN
7N6jIeHz"

crossorigin="anonymous"></script>

</body>

</html>
Step 2: Extend the Base Template

Modify [Link]:

{% extends "[Link]" %}

{% load static %}

{% block title_block %} Home Page {% endblock %}

{% block main_block %}

<h2 class="text-center">Welcome to Student Home Page</h2>

<h4>The Date and Time is: {{ date }}</h4>

<h4>University Name: {{ name }}</h4>

<h4>Batch: {{ batch }}</h4>

<h4>Year: {{ year }}</h4>

<img src="{% static 'images/[Link]' %}" alt="oops image not found"


width="200px" height="200px">

<ul>

<li><a href="{% url 'dash' %}">Go To Dashboard</a></li>

<li><a href="./allstudents">Get All Student Details </a></li>

<li><a href="{% url 'student_detail' roll=10 %}">View


Student</a></li>

</ul>

{% endblock %}

Modify [Link]:

{% extends "[Link]" %}

{% block title_block %} Dashboard {% endblock %}


{% block main_block %}

<h1 class="text-center">Welcome to Dashboard</h1>

{% endblock %}/

Modify the [Link]:

{% extends "[Link]" %}

{% block title_block %} All Student Page {% endblock %}

{% block main_block %}

<h1 class="text-center">All Student Details</h1>

<table class="table">

<tr>

<th>Roll</th>

<th>Name</th>

<th>Address</th>

<th>Marks</th>

</tr>

{% for student in students %}

<tr>

<td>{{ [Link] }}</td>

<td>{{ [Link] }}</td>

<td>{{ [Link] }}</td>

<td>{{ [Link] }}</td>

</tr>
{% endfor %}

</table>

{% endblock %}

You might also like