Introduction To Django Part-I
Introduction To Django Part-I
● 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:
● 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)
● YouTube
● Google
● Dropbox
● Yahoo
History of Django
Official Website:
Django Project
Current Version:
1. Fast Development
2. Fully Loaded
Django provides various built-in libraries for common functionalities, such as:
● User Authentication
● Email Handling
● Database Management
3. Security
● SQL Injection
● Cross-Site Request Forgery (CSRF)
4. Scalability
Django supports high traffic loads(multiple client requests simultaneously ), making it scalable.
Example:
Installing Django:
Prerequisites:
Installation Command:
Django Project:
Django Application:
Example:
● Loan App
● Insurance App
● Customer Management App
● Configuration Files (Database settings, Middleware, etc.)
Key Points:
project1/
│-- manage.py
│-- project1/
│-- __init__.py
│-- asgi.py
│-- settings.py
│-- urls.py
│-- wsgi.py
● 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. settings.py (Project Configuration):
● 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).
● 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.
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. manage.py
2. settings.py
3. urls.py
INSTALLED_APPS = [
'django.contrib.admin', # Admin panel
'django.contrib.auth', # Authentication system
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
● These are the already provided applications by Django with a startup project.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'testapp', # Custom app added manually
]
cd project1
● Run the following command to start the server
Syntax:
Example:
● It will create another folder inside the main folder project1 with some files:
testapp/
│-- migrations/
│ │-- __init__.py
│-- __init__.py
│-- admin.py
│-- apps.py
│-- models.py
│-- tests.py
│-- views.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
2. Create views for our application to provide the required functionalities inside the
views.py file present inside our application "testapp".
● Here we have to define a view function to handle the request and generate the
response to the end user.
def display(request):
● 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 urls.py file(project level).
urlpatterns = [
path('admin/', admin.site.urls),
Visit:
http://localhost:8000/hello
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.
Step2: register this app inside the settings.py file at project level
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'testapp',
'dateapp'
Step3: Define the view function inside the views.py file inside the dateapp folder
def get_date_time(request):
time = datetime.now()
Step4: Define the url mapping for the above view function inside the urls.py file of project1
folder(at the project level)
from testapp import views as v1
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', v1.display),
path('date/', v2.get_date_time),
http://127.0.0.1:8000/date/
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 views.py file).
we can create multiple view functions inside the views.py file and then need to provide url
mapping information to each of the view functions separately.
Until now, we have been defining URL patterns at the project level inside the urls.py file.
However, this approach is not recommended for large projects.
Why Should We Define URLs at the Application Level?
● Inside each application (e.g., testapp) and (dateapp), create a file named urls.py (if not
already present).
○ urls.py inside the testapp folder:
urlpatterns = [
path('hello/', views.display)
urlpatterns = [
path("date/", views.get_date_time)
Step2: Include Application-Level URLs inside the Project's level urls.py file.
urlpatterns = [
path('admin/', admin.site.urls),
path('testapp/', include('testapp.urls')),
path('dateapp/', include('dateapp.urls'))
http://127.0.0.1:8000/dateapp/date
http://127.0.0.1:8000/testapp/hello
cd UniversityProject
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'StudentApp', # Registering the application
]
● Inside the StudentApp folder, create a templates/ directory to store templates specific
to the StudentApp..
UniversityProject/
│-- manage.py
│-- UniversityProject/
│-- StudentApp/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body bgcolor="cyan">
</body>
</html>
def home_view(request):
urlpatterns = [
path("", views.home_view),
Include this StudentApp’s urls.py file in the main urls.py file at project level
(UniversityProject/urls.py file):
urlpatterns = [
path('admin/', admin.site.urls),
http://127.0.0.1:8000/student/
○ {{variable_name}}
def home_view(request):
date = datetime.now()
<body>
</body>
● Instead of defining a dictionary separately, we can pass data directly in the render()
function
def home_view(request):
date = datetime.now()
def home_view(request):
date = datetime.now()
Note: Unlike Flask, where we can pass variables directly to templates, Django requires
passing a dictionary (as context) when sending data to templates.
● In Django, we can pass multiple pieces of data from views.py to an HTML template
using a dictionary as the context.
● Example: Passing Multiple Data Items
Modify views.py in StudentApp:
def home_view(request):
date = datetime.now()
<body>
</body>
import random
def home_view(request):
selected_city = random.choice(cities)
Modify index.html:
<body>
</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.
● Static files like CSS, images, and JavaScript need to be placed inside the static folder
and referenced correctly in 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/
<!DOCTYPE html>
{% load static %}
index.html:
<!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>
</head>
<body>
</body>
</html>
a1.css:
body{
background-color: aquamarine;
http://127.0.0.1:8000/student/
<body bgcolor="cyan">
<h1>Welcome to Dashboard</h1>
</body>
import random
def home_view(request):
city = random.choice(cities)
def dashboard_view(request):
urlpatterns = [
path("", views.home_view),
path("dashboard/", views.dashboard_view),
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wish Page</title>
</head>
<body>
</body>
</html>
Assignment:
Inside the index.html 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 = [
Solution:
Step1: Define the following view function inside the views.py file of StudentApp
def student_list_view(request):
students = [
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.
css" rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6h
W+ALEwIH" crossorigin="anonymous">
</head>
<body>
<table class="table">
<tr>
<th>Roll</th>
<th>Name</th>
<th>Address</th>
<th>Marks</th>
</tr>
<tr>
</tr>
{% endfor %}
</table>
</body>
</html>
path('allstudents/', views.student_list_view)
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 urls.py file.
2. Use this name inside the index.html file inside the template tag.
2. Specify the url mapping inside the urls.py at application level with a name:
urlpatterns = [
path("", views.home_view),
path('getstudent/<int:roll>/', views.student_detail_view,
name='student_detail')
3. Specify the link of the above student_detail inside the index.html file.
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 settings.py file explicitly.
Example:
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/
|--manage.py
|--templates/
| |--StudentApp/
| |--index.html
|--StudentApp/
def home_view(request):
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.
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 settings.py file so that Django can be aware of
our static contents.
STATICFILES_DIRS = [
STATIC_DIR,
OR we can use:
import os
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
<!DOCTYPE html>
{% load static %}
index.html:
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wish Page</title>
</head>
<body>
</body>
</html>
a1.css:
body{
background-color: aquamarine;
http://127.0.0.1:8000/student/
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 allows the creation of a base template that can be extended by other
templates.
● It is similar to the Template inheritance concept in Flask.
base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.
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>
</header>
<main>
{% block main_block %}
{% endblock %}
</main>
<footer>
</footer>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle
.min.js"
integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN
7N6jIeHz"
crossorigin="anonymous"></script>
</body>
</html>
Step 2: Extend the Base Template
Modify index.html:
{% extends "base.html" %}
{% load static %}
{% block main_block %}
<ul>
</ul>
{% endblock %}
Modify dashboard.html:
{% extends "base.html" %}
{% endblock %}/
{% extends "base.html" %}
{% block main_block %}
<table class="table">
<tr>
<th>Roll</th>
<th>Name</th>
<th>Address</th>
<th>Marks</th>
</tr>
<tr>
</tr>
{% endfor %}
</table>
{% endblock %}