installed virtual env and Django globally in system we can check by -- pip freeze
(in cmd)
--> Remember : whatever you write code or later you update also, press 'ctrl+s' to
save it then only output will show on screen
or else go to : File -> autosave
-- to create new project : django-admin startproject project_name
--> to create app inside project : python [Link] startapp app_name
-- to run project : move to project directory -> python [Link] runserver
(if we want specify any port no. then you can add at last else by default run at
8000)
--> Object relationship Mapping (ORM)
---> Template tags :
1. include : is used to insert reusable html code into another html file. i.e.,
{% include "file_name" %}
2. extends : it is like inheritance, means one template can reuse the structure of
another template. ie., {% extends "file_name" %}
-- exclude : used to hide unwanted fields from forms.
---> Error handling : it can be done using 'try - except' block
--> Project directory folder details :
1. [Link] : it is the main file which is used to run project, migrate project
2. create 'template' name folder inside project directory : where we add our html
pages
3. create 'static' name folder inside project directory : where javascript, css,
fonts files are present
4. create 'media' name folder inside project directory : it contains dynamic images
and files
--these above three folders we have to make by ourself
5. [Link] : default database
6. [Link] : it manages all files present in project and we have to mention
here every files like (apps, template, static, etc), because [Link] internally
hts [Link]
7. [Link] : it works as a routing by providing path to it, which tells at what
path, what page will be open.
8. [Link] : its is used to handle user input(text boxes) and save data into
model.
--> HTTP Request (hyper text tranfer protocol) : is a message sent by client(such
as browser) to a server.
Http methods :
Get : fetching data
post : adding data
put : update data
delete : delete the data
--> Error handling :
-- Django automatically handles error like :
404 not found -> URL not mapped
500 Server error -> view code crashed
--> Migration :
-- Migrations are a way to keep track of changes in your database structure
(schema) when your models change. Its like git.
-- migrate : It is used to create default table (admin, auth, session) in
db.sqlite3 file. It is used to apply changes to database or update the database.
-- Command : python [Link] migrate
--> Install DB browser for sqlite : (downlaod from : [Link])
-- db browser is a software through which we can see what data, table stored in
sqlite file
-- download app then open db.sqlite3 file into this app to see all tables and data
--> Superuser :
-- It give access to enter in admin account with full permission to manage entire
project via Django admin site.
-- how to create superuser : python [Link] createsuperuser
-- give it username and password and email
-- username : akshatsingh password : akshat2901
-- visit for login into admin page : http/localhost:8000/admin
-- after generating this you can see in SQLite app by opening user auth_user table,
that data is stored \
--> View and URLs
1. URLs :
-- it is like routing, it tells user that on what path, which view or page will be
open.
2. View :
-- View is a python function/class that takes request and return response (like
html, json, text).
--> How to create and work on view and url
1. create one [Link] file inside project directory /akshat/'akshat'
2. [Link] : make functions and connect it to url in [Link] paage
Eg:
from [Link] import HttpResponse
def aboutUs(request):
return HttpResponse("<h1>About Us</h1><p>This is the about us page. Akshat
SIngh from up</p>")
def home(request):
return HttpResponse("<h1>Home Page</h1><p>Welcome to the home page!</p>")
#for params
def courseDetails(request, courseId):
return HttpResponse(f"<h1>Course Details</h1><p>Details for course ID:
{courseId}</p>")
3. [Link] : pass path and call views function
Eg:
from [Link] import path
# import views from akshat folder
from akshat import views
urlpatterns = [
path('admin/', [Link]),
path('home/', [Link]), # home here function name present in [Link] file
path('about/', [Link]), # aboutUs here function name present in
[Link] file
# params in url
# path('course/<int:courseId>/', [Link])
path('course/<str:courseId>/', [Link])
]
--> Template : HTML file with dynamic data (python data + html design)
--> DTL (Django Template language) : allows to write python like code inside html.
It uses :
1. {{ }} : for variables
2. {% %} : for tags (loops, if-else, logic, etc)
---> Render HTML Template :
-- for this we will use:
1. import library : [Link]
2. through render function we can render html template
-- make .html page inside 'template' folder
-- call template file inside [Link] -> TEMPLATES -> 'DIRS' : [BASE_DIR,
"templates"],
1. templates/[Link]
<body>
<h1>Hello bhaiya</h1>
</body>
2. [Link]
from [Link] import render
def homePage(request):
return render(request, "[Link]")
3. [Link]
from akshat import views
urlpatterns = [
path('', [Link]),
]
---> Passing Data from Django view to template :
-- [Link]
def contactUs(request):
data = {
"title": "Contact Us",
"message": "Feel free to reach out to us!"
}
return render(request, "[Link]", data)
(call this key (title and message) in html page to see data)
-- html :
<body>
<h1>Hello bhaiya</h1>
<p>{{title}}</p>
<p>{{message}}</p>
</body>
-- [Link]
path('contact/', [Link]),
---> How to apply 'For-loop' in template (html file)
-- [Link]
def contactUs(request):
data = {
"title": "Contact Us",
"message": "Feel free to reach out to us!",
"subList": ['PHP', 'Django', 'Flask', 'NodeJS', 'ExpressJS']
}
return render(request, "[Link]", data)
-- [Link] : printing sublist using for loop
<body>
{% for n in subList%}
<div>{{n}}</div>
{% endfor %}
</body>
--> How to display data into 'table' from views to html using for-loop :
-- [Link] : fetching stud_detials in table
def contactUs(request):
data = {
"stud_details":[
{"name" : "Akshat Singh", "age": 20, "city": "UP"},
{"name" : "John Doe", "age": 22, "city": "NYC"},
],
}
return render(request, "[Link]", data)
-- [Link] :
<table border="1" cellpadding="10">
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
{% for stud in stud_details %}
<tr>
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr>
{% endfor %}
</table>
---> How to apply 'if-else' in template (html file)
-- [Link] :
def contactUs(request):
data = {
"numbers": [10, 20, 30, 40, 50],
}
return render(request, "[Link]", data)
-- [Link] :
{% if numbers|length %}
{% for n in numbers %}
{% if n > 20 %}
<div>{{n}}</div>
{% endif %}
{% endfor %}
{% else %}
<div>No numbers found</div>
{% endif %}
---> Managing static files (images, javascript, CSS) :
-- for these above things (images, js, css) present in 'static' folder to use them,
we have to pass this file name inside '[Link]'
-- 1. paste this at last in '[Link]' :
STATICFILES_DIRS = [
BASE_DIR, "static"
]
2. static/css/[Link] :
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
margin: 0;
padding: 0;
text-align: center;
}
.......
3. static/image/[Link] :
4. [Link]
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home Page</title>
<link rel="stylesheet" href="{% static 'css/[Link]' %}">
</head>
<body>
<header>
<h1>Welcome to My Django Website</h1>
<img src="{% static 'images/[Link]' %}" alt="Banner" width="600">
</header>
<main>
<p>This is the home page styled with CSS and using an image from static
files.</p>
</main>
<footer>
<p>© 2025 My Website</p>
</footer>
</body>
</html>
---> How to add header and footer page in home page : (because header footer made
separately so that use in all pages)
-- It can be done using : 'include' function in Django
i.e., {% include "[Link]"%}
1. create [Link] and [Link] page with same css as in [Link]
2. [Link] :
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home Page</title>
<link rel="stylesheet" href="{% static 'css/[Link]' %}">
</head>
<body>
{% include '[Link]' %}
<img src="{% static 'images/[Link]' %}" alt="Banner" width="600">
<main>
<p>This is the home page styled with CSS and using an image from static
files.</p>
</main>
{% include '[Link]' %}
</body>
</html>
---> How to extends in Django (one template copy structure of another template)
1. create one .html page ([Link]) and add header and footer in this page
{% include '[Link]' %}
{% block content %}
{% endblock %}
{% include '[Link]' %}
2. [Link]
same add here but just
{% exclude '[Link]' %}
{% block content %}
{% endblock %}
---> URLs to pass in page to move from one page to another :
-- remember whatever url path passed in [Link] page that same should be passed
in .html page inside anchor tag i.e., <a href="/about">About</a>
--> Steps to know how html , views and urls page work
1. make one html page - template/[Link] -- add some content
2. make one static folder - inside this all css and images will be there.
(above both should be mentioned in '[Link])
3. now come to [Link] : here we have to make function and call this html page, it
contains multiple functions for different pages
4. [Link] : now provide path and call function from view page, so that it can show
that html page to that url
--->> HTTP Request : (hyper text tranfer protocol) :
-- HTTP Request is a message sent by client(such as browser) to a server,
requesting for specific resource
--> Http methods :
1. Get : used to fetch data from server. Data is sent in URL query string, starting
with '?'
2. Post : used to send data to the server (submitting form). Data is sent in the
request body.
3. Put : update the data
4. Delete : remove the data
---> Implement "GET" method into the FORM : (doing addition by giving two values)
-- to get value on screen - we use value stored inside 'name' in a tag and use in
view file
-- using 'value' inside tag we get value
1. [Link]
<div class="form-container">
<h2>Welcome! Please Fill the Form</h2>
<form>
<div class="form-group">
<label for="username">Value1: </label>
<input type="text" id="num1" name="num1">
</div>
<div class="form-group">
<label for="email">Value2: </label>
<input type="text" id="num2" name="num2">
</div>
<button type="submit">Submit</button>
// getting value
<input type="text" value="{{output}}">
</form>
</div>
2. [Link] :
def userForm(request):
finalAns = 0
try:
n1 = int([Link]('num1'))
n2 = int([Link]('num2'))
finalAns = n1 + n2
except:
pass
return render(request, "[Link]", {'output': finalAns}) // this output
call inside 'value' to see answer
3. [Link] :
path('userForm/', [Link]),
--->> Implement POST method with CSRF :
--> CSRF :
-- CSRF (cross-site request forgery) token : it protects the form from hackers by
verifying the POST requests really come from your own website.
-- When we load page, django generate random unique hidden token
-- CSRF is used with POST method
-- If CSRF is missing then it gives error : forbidden (403)
-- use : {% csrf_token %}
1. [Link] :
<div class="form-container">
<h2>Welcome! Please Fill the Form</h2>
<form method="POST">
{% csrf_token %}
<div class="form-group">
<label for="username">Value1: </label>
<input type="text" id="num1" name="num1">
</div>
<div class="form-group">
<label for="email">Value2: </label>
<input type="text" id="num2" name="num2">
</div>
<button type="submit">Submit</button>
<input type="text" value="{{output}}">
</form>
</div>
2. [Link] :
def userForm(request):
finalAns = 0
try:
if [Link] == "POST":
n1 = int([Link]('num1'))
n2 = int([Link]('num2'))
finalAns = n1 + n2
except:
pass
return render(request, "[Link]", {'output': finalAns})
--->> How to redirect to another pager just afer submission of form : like when we
login, we redirect to home page
-- just we need to return "HTTPResponseRedirect" ("path_to_which_page_redirect")
-- lets use in above example : when we submit form, we redirect to home page : we
have to use it in [Link]
[Link] :
def userForm(request):
finalAns = 0
try:
if [Link] == "POST":
n1 = int([Link]('num1'))
n2 = int([Link]('num2'))
finalAns = n1 + n2
# redirect to home page after form submission
return HttpResponseRedirect("home/")
except:
pass
return render(request, "[Link]", {'output': finalAns})
--->> How to see submitted data into another page : add 'action'
<div class="form-container">
<h2>Welcome! Please Fill the Form</h2>
<form method="POST" action="{% url 'submitForm' %}">
{% csrf_token %}
<div class="form-group">
<label for="username">Value1: </label>
<input type="text" id="num1" name="num1">
</div>
<div class="form-group">
<label for="email">Value2: </label>
<input type="text" id="num2" name="num2">
</div>
<button type="submit">Submit</button>
<input type="text" value="{{output}}">
</form>
</div>
--->> How to make form :
-- first create one '[Link]' file inside project directory
1. [Link] : define form fields
from django import forms
class usersForm([Link]):
# define how many fields you want in the form
num1 = [Link](label="Enter first number", required=True,
widget=[Link](attrs={"class":"form-control"}))
num2 = [Link](label="Enter first number", required=True,
widget=[Link](attrs={"class":"form-control"}))
2. [Link] : import your form here
def userForm(request):
finalAns = 0
fn = usersForm()
data={'form':fn} # call this form key over html page to see fields made in
[Link]
try:
if [Link] == "POST":
n1 = int([Link]('num1'))
n2 = int([Link]('num2'))
finalAns = n1 + n2
data = {
'form' : fn,
'output': finalAns
}
except:
pass
return render(request, "[Link]", data)
3. html:
<div class="form-container">
<h2>Welcome! Please Fill the Form</h2>
<form method="POST">
{% csrf_token %}
{{form}}
<button type="submit">Submit</button>
<input type="text" value="{{output}}">
</form>
</div>
--->> Q. Check by taking input, whether input value is even or odd :
-- [Link] :
<div class="form-container">
<h2>Welcome! Please Fill the Form</h2>
<form method="POST">
{% csrf_token %}
<div class="form-group">
<label for="username">Value1: </label>
<input type="text" id="num1" name="num1">
</div>
<button type="submit">Submit</button>
<input type="text" value="{{output}}">
</form>
</div>
-- [Link]
def evenOdd(request):
val='' //empty var to store ans
if [Link] == "POST":
n = eval([Link]('num1'))
if n % 2 == 0:
val = "Even Number"
else:
val = "Odd Number"
return render(request, "[Link]", {'output': val})
-- [Link]
path('evenOdd/', [Link], name='evenOdd'),
--->> Form Validation :
-- [Link]
<div class="form-container">
<h2>Register Form</h2>
<form method="POST">
{% csrf_token %}
{% if error %}
<div class="alert alert-danger" role="alert">
{{ error }}
</div>
{% endif %}
<div class="form-group">
<label for="name">Name: </label>
<input type="text" id="name" name="name">
</div>
<div class="form-group">
<label for="email">Email: </label>
<input type="email" id="email" name="email">
</div>
<div class="form-group">
<label for="password">Password: </label>
<input type="password" id="password" name="password">
</div>
<button type="submit">Submit</button>
{% if success %}
<p class="success">{{ success }}</p>
{% endif %}
</form>
</div>
-- [Link]
def register(request):
error = None
success = None
if [Link] == "POST":
name = [Link]('name')
email = [Link]('email')
password = [Link]('password')
# Validation checks
if not name:
error = "Name is required!"
elif not email:
error = "Email is required!"
elif not password:
error = "Password is required!"
elif len(password) < 6:
error = "Password must be at least 6 characters long!"
else:
success = f"Registration successful! Welcome {name}"
return render(request, "[Link]", {'error': error, 'success': success})
---> Now to work with Model :
-- we need three things for model :
1. create one model app : python [Link] startapp app_name (because it has
admin, model files) --> and list this app name into '[Link]' of project
2. python [Link] makemigrations : after writing code in [Link], run this, it
will create model
3. python [Link] migrate : convert model into table
--> Working with model, creating model, saving form data in database, and getting
it in tabular format:
1. service/[Link]
from [Link] import models
class Person([Link]):
name = [Link](max_length=100)
email = [Link](unique=True)
password = [Link](max_length=100)
def __str__(self):
return [Link]
2. run these command after making model :
python [Link] makemigrations
python [Link] migrate
3. service/[Link]
from [Link] import render
from .models import Person
def register(request):
msg = ""
if [Link] == "POST":
name = [Link]("name")
email = [Link]("email")
password = [Link]("password")
if name == "" or email == "" or password == "":
msg = "All fields are required!"
else:
# save into database
[Link](name=name, email=email, password=password)
msg = "Registered Successfully!"
people = [Link]() # fetch all users
return render(request, "[Link]", {"msg": msg, "people": people})
4. service/[Link]
from [Link] import path
from . import views
urlpatterns = [
path('register/', [Link], name='register'),
]
1. Project/[Link]
<div class="form-container">
<h2>Register Form</h2>
<form method="POST">
{% csrf_token %}
{% if error %}
<div class="alert alert-danger" role="alert">
{{ error }}
</div>
{% endif %}
<div class="form-group">
<label for="name">Name: </label>
<input type="text" id="name" name="name">
</div>
<div class="form-group">
<label for="email">Email: </label>
<input type="email" id="email" name="email">
</div>
<div class="form-group">
<label for="password">Password: </label>
<input type="password" id="password" name="password">
</div>
<button type="submit">Submit</button>
{% if success %}
<p class="success">{{ success }}</p>
{% endif %}
</form>
<br><br>
<h2>Registered People</h2>
<table border="1">
<tr>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>
{% for person in people %}
<tr>
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr>
{% empty %}
<tr><td colspan="3">No people found</td></tr>
{% endfor %}
</table>
</div>
2. [Link]
def register(request):
error = None
success = None
if [Link] == "POST":
name = [Link]('name')
email = [Link]('email')
password = [Link]('password')
# Validation checks
if not name:
error = "Name is required!"
elif not email:
error = "Email is required!"
elif not password:
error = "Password is required!"
elif len(password) < 6:
error = "Password must be at least 6 characters long!"
else:
success = f"Registration successful! Welcome {name}"
return render(request, "[Link]", {'error': error, 'success': success})
3. [Link]
path('', include('[Link]'))