[go: up one dir, main page]

0% found this document useful (0 votes)
14 views18 pages

Django Practical Notes

This document provides a comprehensive guide on setting up and using Django, including creating projects and apps, managing templates, handling HTTP requests, and implementing forms with GET and POST methods. It covers key concepts such as Object-Relational Mapping (ORM), error handling, migrations, and the structure of Django project directories. Additionally, it explains how to manage static files, use template inheritance, and implement CSRF protection for forms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views18 pages

Django Practical Notes

This document provides a comprehensive guide on setting up and using Django, including creating projects and apps, managing templates, handling HTTP requests, and implementing forms with GET and POST methods. It covers key concepts such as Object-Relational Mapping (ORM), error handling, migrations, and the structure of Django project directories. Additionally, it explains how to manage static files, use template inheritance, and implement CSRF protection for forms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 18

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 manage.py startapp app_name

-- to run project : move to project directory -> python manage.py 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. manage.py : 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. db.sqlite : default database
6. settings.py : it manages all files present in project and we have to mention
here every files like (apps, template, static, etc), because manage.py internally
hts settings.py
7. urls.py : it works as a routing by providing path to it, which tells at what
path, what page will be open.
8. forms.py : 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 manage.py migrate

--> Install DB browser for sqlite : (downlaod from : sqlitebrowser.org)

-- 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 manage.py 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 views.py file inside project directory /akshat/'akshat'

2. views.py : make functions and connect it to url in urls.py paage

Eg:

from django.http 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. urls.py : pass path and call views function

Eg:

from django.urls import path

# import views from akshat folder


from akshat import views

urlpatterns = [
path('admin/', admin.site.urls),
path('home/', views.home), # home here function name present in views.py file
path('about/', views.aboutUs), # aboutUs here function name present in
views.py file

# params in url
# path('course/<int:courseId>/', views.courseDetails)
path('course/<str:courseId>/', views.courseDetails)
]
--> 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 : Django.shortcut
2. through render function we can render html template

-- make .html page inside 'template' folder


-- call template file inside settings.py -> TEMPLATES -> 'DIRS' : [BASE_DIR,
"templates"],

1. templates/index.html
<body>
<h1>Hello bhaiya</h1>
</body>

2. views.py

from django.shortcuts import render


def homePage(request):
return render(request, "index.html")

3. urls.py

from akshat import views


urlpatterns = [
path('', views.homePage),
]

---> Passing Data from Django view to template :

-- views.py

def contactUs(request):
data = {
"title": "Contact Us",
"message": "Feel free to reach out to us!"
}
return render(request, "index.html", 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>

-- urls.py
path('contact/', views.contactUs),

---> How to apply 'For-loop' in template (html file)

-- views.py

def contactUs(request):
data = {
"title": "Contact Us",
"message": "Feel free to reach out to us!",
"subList": ['PHP', 'Django', 'Flask', 'NodeJS', 'ExpressJS']
}
return render(request, "index.html", data)

-- index.html : 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 :

-- Views.py : 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, "index.html", data)

-- index.html :
<table border="1" cellpadding="10">
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>

{% for stud in stud_details %}


<tr>
<td>{{ stud.name }}</td>
<td>{{ stud.age }}</td>
<td>{{ stud.city }}</td>
</tr>
{% endfor %}

</table>

---> How to apply 'if-else' in template (html file)

-- views.py :

def contactUs(request):
data = {
"numbers": [10, 20, 30, 40, 50],
}
return render(request, "index.html", data)

-- index.html :

{% 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 'settings.py'

-- 1. paste this at last in 'settings.py' :


STATICFILES_DIRS = [
BASE_DIR, "static"
]

2. static/css/styles.css :

body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
margin: 0;
padding: 0;
text-align: center;
}
.......

3. static/image/radheshyam.jpg :

4. home.html

{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home Page</title>
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
<header>
<h1>Welcome to My Django Website</h1>
<img src="{% static 'images/radheshyam.jpg' %}" 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>&copy; 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 "header.html"%}


1. create header.html and footer.html page with same css as in home.html

2. home.html :

{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home Page</title>
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>

{% include 'header.html' %}

<img src="{% static 'images/radheshyam.jpg' %}" alt="Banner" width="600">

<main>
<p>This is the home page styled with CSS and using an image from static
files.</p>
</main>

{% include 'footer.html' %}

</body>
</html>

---> How to extends in Django (one template copy structure of another template)

1. create one .html page (base.html) and add header and footer in this page

{% include 'header.html' %}

{% block content %}

{% endblock %}

{% include 'footer.html' %}

2. home.html

same add here but just


{% exclude 'base.html' %}

{% block content %}

{% endblock %}
---> URLs to pass in page to move from one page to another :

-- remember whatever url path passed in urls.py 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/index.html -- add some content


2. make one static folder - inside this all css and images will be there.
(above both should be mentioned in 'settings.py)

3. now come to view.py : here we have to make function and call this html page, it
contains multiple functions for different pages

4. urls.py : 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. userForm.html

<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. views.py :

def userForm(request):
finalAns = 0
try:
n1 = int(request.GET.get('num1'))
n2 = int(request.GET.get('num2'))
finalAns = n1 + n2
except:
pass
return render(request, "userForm.html", {'output': finalAns}) // this output
call inside 'value' to see answer

3. urls.py :

path('userForm/', views.userForm),

--->> 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. userForm.html :

<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. views.py :

def userForm(request):
finalAns = 0
try:
if request.method == "POST":
n1 = int(request.POST.get('num1'))
n2 = int(request.POST.get('num2'))
finalAns = n1 + n2
except:
pass
return render(request, "userForm.html", {'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 views.py

views.py :

def userForm(request):
finalAns = 0
try:
if request.method == "POST":
n1 = int(request.POST.get('num1'))
n2 = int(request.POST.get('num2'))
finalAns = n1 + n2

# redirect to home page after form submission


return HttpResponseRedirect("home/")
except:
pass
return render(request, "userForm.html", {'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 'form.py' file inside project directory

1. forms.py : define form fields

from django import forms

class usersForm(forms.Form):
# define how many fields you want in the form
num1 = forms.CharField(label="Enter first number", required=True,
widget=forms.TextInput(attrs={"class":"form-control"}))
num2 = forms.CharField(label="Enter first number", required=True,
widget=forms.TextInput(attrs={"class":"form-control"}))

2. Views.py : 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
forms.py

try:
if request.method == "POST":
n1 = int(request.POST.get('num1'))
n2 = int(request.POST.get('num2'))
finalAns = n1 + n2

data = {
'form' : fn,
'output': finalAns
}
except:
pass
return render(request, "userForm.html", 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 :

-- index.html :

<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>
-- views.py

def evenOdd(request):
val='' //empty var to store ans
if request.method == "POST":
n = eval(request.POST.get('num1'))
if n % 2 == 0:
val = "Even Number"
else:
val = "Odd Number"

return render(request, "evenOdd.html", {'output': val})

-- urls.py
path('evenOdd/', views.evenOdd, name='evenOdd'),

--->> Form Validation :

-- index.html

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

-- views.html

def register(request):
error = None
success = None

if request.method == "POST":
name = request.POST.get('name')
email = request.POST.get('email')
password = request.POST.get('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, "form.html", {'error': error, 'success': success})

---> Now to work with Model :

-- we need three things for model :


1. create one model app : python manage.py startapp app_name (because it has
admin, model files) --> and list this app name into 'settings.py' of project
2. python manage.py makemigrations : after writing code in model.py, run this, it
will create model
3. python manage.py migrate : convert model into table

--> Working with model, creating model, saving form data in database, and getting
it in tabular format:

1. service/models.py

from django.db import models

class Person(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(unique=True)
password = models.CharField(max_length=100)

def __str__(self):
return self.name

2. run these command after making model :

python manage.py makemigrations


python manage.py migrate

3. service/views.py

from django.shortcuts import render


from .models import Person

def register(request):
msg = ""
if request.method == "POST":
name = request.POST.get("name")
email = request.POST.get("email")
password = request.POST.get("password")

if name == "" or email == "" or password == "":


msg = "All fields are required!"
else:
# save into database
Person.objects.create(name=name, email=email, password=password)
msg = "Registered Successfully!"

people = Person.objects.all() # fetch all users


return render(request, "form.html", {"msg": msg, "people": people})

4. service/urls.py

from django.urls import path


from . import views

urlpatterns = [
path('register/', views.register, name='register'),
]

1. Project/form.html

<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>{{ person.name }}</td>
<td>{{ person.email }}</td>
<td>{{ person.password }}</td>
</tr>
{% empty %}
<tr><td colspan="3">No people found</td></tr>
{% endfor %}
</table>
</div>

2. views.py

def register(request):
error = None
success = None

if request.method == "POST":
name = request.POST.get('name')
email = request.POST.get('email')
password = request.POST.get('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, "form.html", {'error': error, 'success': success})

3. urls.py

path('', include('service.urls'))

You might also like