2. What is Django
Django is a high-level Python Web framework.
It is free and open source.
django follow MVT Design pattern (Model,View,Template)
Django is developed using python.
We can make web application using Django
www.SunilOS.com 2
3. www.SunilOS.com 3
Why Django
It is Fast
Fully Loaded.
• Authentication
• Security
• session management
Security CSRF(Cross-site request forgery).
Scalability.
Versatile.
5. How to install
You can run following command to install Django.
o pip install Django
Or
o pip install Django==2.2.5
After installation you can check version of Django by running
the following command at python script mode.
o import django
o django.VERSION
www.SunilOS.com 5
6. Django Project
Django Provides command to generate project template.
Django project is created using command.
o django-admin startproject project-name.
We are assuming project name is SOS.
o django-admin startproject SOS.
o Above command will create project directory structure.default SOS and
manage.py file.
Inside c:/SOS folder it will create following subfolders and files.
o __pycache__
o __init__.py
o settings.py
o urls.py
o wsgi.py
www.SunilOS.com 6
7. Run the project
Execute following command to run Django project.
o py manage.py runserver
It will start Django server at default port number #8000 and
make application accessible using http://127.0.0.1:8000/
www.SunilOS.com 7
8. Create App
We are assuming that you have creates SOS project from
previous slides and we will create ORS App in same project.
Use following command in c:/SOS folder to generate ORS
App.
o py manage.py startapp ORS
Above commands will generate ORS app .
Each application you write in Django consists of a Python package that
follows a certain convention. Django comes with a utility that
automatically generates the basic directory structure of an app
www.SunilOS.com 8
9. Generated App Files
ORS
o Migrations
__init__.py
o __init__.py
o admin.py
o apps.py
o models.py
o tests.py
o views.py
www.SunilOS.com 9
11. views.py File
Views.py file work as a controller.
Controller is responsible to get data from server which is displayed
at template.
Create a function Hello_word in side Views.py file.
Import HttpResponse module for send response.
Hello_word function receive one request parameter.
from django.shortcuts import render
from django.http import HttpResponse
def hello_word (request):
return HttpResponse('<h1>Welcome to Django First
App</h1>')
www.SunilOS.com 11
12. urls.py File
Inside urls.py file be are map our views function.
from django.contrib import admin
from django.urls import path
from ORS import views
urlpatterns = [
path('admin/', admin.site.urls),
path('Hello/',views.hello_word),]
Now we can run our application.using following
Command .
py manage.py runserver
14. MVT Architecture
Django application follows MVT Architecture.
MVT is stand for Model ,View and Template.
www.SunilOS.com 14
15. MVT Architecture
Model:- Model contains persistent data and the business methods to
perform business operations on this data and store the data into a
database.
Views:-View contain navigation logic and responsible to perform
business operations submitted by template with the help of
Model. Navigation logic are used to determine next template to be
displayed after successful or unsuccessful execution of business
operation.
Template:-display HTML page along with data provided by Model .
Templates display data from model.HTML page is template in app.
www.SunilOS.com 15
17. Admin Interface
Django provides a ready-to-use user interface for administrative
activities.
admin interface is important for a web project
Django automatically generates admin UI based on your project models.
Before start your server you need to initiate the database.
o py manage.py migrate
This command create necessary tables in database.
After that we can create super user for accessing admin interface.
For super user we can execute following command.
o py manage.py createsuperuser
Now create login id and password for accessing admin interface.
Run our server and use following url for admin interface
o http://localhost:8000/admin/
20. URL-Mapping
A URL is a web address. For example http://www.raystec.com/
You can see a URL every time you visit a website .
Every page on the Internet needs its own URL.
URL configuration(URLconf ) is a set of patterns that Django will try to
match the requested URL to find the correct view.
urls.py Views.py
request Call function
21. URL-Mapping
Let's open up the SOS/urls.py file in your code editor.
o from django.contrib import admin
o from django.urls import path
o from ORS import views
o urlpatterns = [
path('admin/',admin.site.urls),
path(‘login/',views.login),
path(‘welcome/', views.welcome),
o ]
Now we can see Django has already provide admin url.
The admin URL, which you visited in the previous slide.
22. URL-Mapping
The project has just one app ORS.in real project there might be more apps.
Django differentiate this URL using Separate URL mapping file
Now we can create separate urls.py file inside app.
o ORS/
__init__.py
admin.py
apps.py
migrations/
• __init__.py
models.py
tests.py
urls.py
views.py
Now we can map our views functions inside urls.py
o from django.urls import path
o from . import views
o urlpatterns = [ path('welcome/',views.welcome),]
23. Include Function
Now we can call ORS/urls.py file in settings.py file.
o from django.contrib import admin
o from django.urls import path, include
o urlpatterns = [ path('admin/', admin.site.urls),
o path('ORS/', include("ORS.urls"))]
A function include() that takes a full Python import path to another
URLconf module that should be “included” in this place.
Now we can run server and use this url
o http://localhost:8000/ORS/welcome/
24. URL Parameters
A URL may contain parameters , parameters are called url parameters.
One url may contain one or more parameters.
o urlpatterns = [
o path(‘user/<int:id>',views.user),
o path(‘user/<int:id>/<str:name>',views.user),]
Create a function inside views.py file.
o from django.shortcuts import render
o from django.http import HttpResponse
o def user(request,id=0,name=“”):
message=”User id = ”+str(id)
return HttpResponse(message)
Now run server and call this urls
http://localhost:8000/ORS/user/9/ram
25. Model
Django provide models.py file for Database operation.
Django has a model class that represent table in our DB.
This class attribute is a field of the table.
models.py file present in app.
Django provide default SQLite DataBase .
We can see settings.py file.
o DATABASES = {
o 'default': {
o 'ENGINE': 'django.db.backends.sqlite3',
o 'NAME': os.path.join(BASE_DIR,
'db.sqlite3'),
o }
o }
26. settings.py
Now we can change our DataBase SQLite to mysql.
o DATABASES = {
o 'default': {
o 'ENGINE':'django.db.backends.mysql',
o 'NAME': 'dataBase_Name',
o 'USER': 'root',
o 'PASSWORD': 'root',
o 'HOST': 'localhost',
o 'PORT': '3306',
o }
o }
Note:-install mysql connector using following command
pip install mysqlclient
27. Models.py
Now we can create student class in models.py file.
o from django.db import models
o class Student(models.Model):
o firstName = models.CharField(max_length=50)
o lastName = models.CharField(max_length=50)
o mobileNumber=models.CharField(max_length=20)
o email = models.EmailField()
o password=models.CharField(max_length=20)
o class Meta:
o db_table = "SOS_STUDENT“
Now we can run migrate & makemigrations command.
migrate command is responsible for applying migrations.
Makemigrations command is responsible for create new migrations
based on changes in models file.
28. forms.py
Now we can create one more file that is called forms.py
This file is describes the logical structure of Model object.
ModelForm class maps a model class’s fields to HTML
form <input> elements.
o from django import forms
o from ors.models import Student
o class StudentForm(forms.ModelForm):
o class Meta:
o model=Student
o fields="__all__"
Now we can call this all function inside views.py file.
29. Views.py
Now we can create registration function.
o from django.shortcuts import render,redirect
o from ors.models import Student
o from django.http import HttpResponse
o from ors.forms import StudentForm
o def registration(request):
o if request.method=="POST":
o form=StudentForm(request.POST)
o if form.is_valid():
o form.save()
o return HttpResponse("Registration successfully")
o return render(request,"Registration.html")
30. Template
Template is a html page.it is represent User Inetrface.
User can enter input data using UI input form.
template contains presentation logic and displays data from Model object.
template submits its data to its views on a user action.
www.SunilOS.com 30
Welcome.html
Views.py
Request Call template
31. Template
Now we can create template folder in ORS app.
ORS app architecture
o Migrations
__init__.py
o __init__.py
o admin.py
o apps.py
o models.py
o tests.py
o template
Welcome.html
o views.py
www.SunilOS.com 31
32. Template
We can register this template folder inside settings.py file
o BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__f
ile__)))
o TEMPLATES_DIR=os.path.join(BASE_DIR,'templates')
o TEMPLATES = [
o {'BACKEND': 'django.template.backends.django.DjangoTemplates',
o 'DIRS': [TEMPLATES_DIR],
o 'APP_DIRS': True,
o 'OPTIONS': {
o 'context_processors': [
o 'django.template.context_processors.debug',
o 'django.template.context_processors.request',
o 'django.contrib.auth.context_processors.auth',
o 'django.contrib.messages.context_processors.messages',
o ],},},]
www.SunilOS.com 32
33. Template
Now we can create one function inside views.py file for calling template.
o from django.shortcuts import render
o def index(request):
o return render(request,"welcome.html")
Now we can write HTML code in welcome.html file.
o <html >
o <head>
o <title>template</title>
o </head>
o <body>
o <h1>Welcome to template</h1>
o </body>
o </html>
www.SunilOS.com 33
34. Template
Now we can create one function inside views.py file for calling template.
o from django.shortcuts import render
o def index(request):
o return render(request,"welcome.html")
Now we can write HTML code in welcome.html file.
o <html >
o <head>
o <title>template</title>
o </head>
o <body>
o <h1>Welcome to template</h1>
o </body>
o </html>
Now run the server
www.SunilOS.com 34
36. Template Tags
Django template has in built tags.
Print response data using {{ }} (double curly braces).
We can use this tags for print views data ,messages etc.
o for
o if
o include
o csrf_token
This tags are surrounded by {% %} braces.
www.SunilOS.com 36
37. Templat Tag
Double curly brace use for print any variable value at template. for ex.
Create a function in views.py file.
o def index(request):
o return render(request,"welcome.html“,{"firstName"
:"Ram"})
Now we can print firstName value in HTML file.
o <html >
o <head>
o </head>
o <body>
o <h1>Name is</h1>
o {{firstName}}
o </body>
o </html>
www.SunilOS.com 37
38. for Tag
For tag is used to iterate and print list in html page.
o def index(request):
o list = [ {"id":1,"name":"Virat kohli"},
o {"id":2,"name":"MS. Dhoni"},
{"id":3,"name":"Virendra sehwag"},]
o return render(request,"welcome.html",{"list":list})
Print this list in html page.
o <table>
o {% for l in list%}
o <tr>
o <td>{{l.id}}</td>
o <td>{{l.name}}</td>
o </tr>
o {% endfor %}
o </table>
www.SunilOS.com 38
39. if Tag
if tag is used to conditionally display an html DOM element.
o {% if flag%}
o <h1 style="color: green;">If is executed</h1>
o {% endif %}
Flag is a variable that contain Boolean value.
You can use else with if
o {% if flag%}
o <h1 style="color: green;">If is executed</h1>
o {% else %}
o <h1 style="color: red;">else is executed</h1>
o {% endif %}
www.SunilOS.com 39
40. include Tag
include tag used to load an html page.
This is a way to including other templates within a template.
Now we can use header and footer using include tag
o <html>
o <head>
o {% include "Header.html" %}
o </head>
o <body>
o <h1>This main Page</h1>
o </body>
o {% include "Footer.html" %}
www.SunilOS.com 40
41. Header.html & Footer.html
Create Header.html File
o <h1>
o Welcome TO Rays Technologies
o </h1>
Create Footer.html File
o <p>
o www.Sunilos.com
o </p>
www.SunilOS.com 41
42. CSRF_token
csrf stand for Cross site Request forgery.
Csrf middleware is use to protection against Cross site Request forgery.
It refers to attempts to send requests from an external site while
pretending to be from the origin application.
Now we can use this tag in html page.
o <form method="POST" action="">
o {% csrf_token %}
o <input type="text" name="login">
o <br>
o <input type="text" name="password">
o <br>
o <input type="submit" value="Login">
o </form>
www.SunilOS.com 42
43. Session - HTTP is a stateless protocol
www.SunilOS.com 43
44. What is Session
HTTP is a stateless protocol.
Session tracking mechanism is used by Controller (View) to
maintain the state of a user (browser).
A state consists of a series of requests from the same user
(browser) for a particular time.
Session will be shared by multiple controllers those are
accessed by the same user.
A good example is online Shopping Cart that contains
multiple items, selected from multiple user’s requests.
www.SunilOS.com 44
46. A Web User’s Session
www.SunilOS.com 46
Session.objects.all().delete()
47. Session Example
Now we can create a function.
This function is use to create session.
o from django.contrib.sessions.models import
Session
o from django.shortcuts import render,redirect
o from django.http import HttpResponse
o def create_session(request):
o request.session['name'] = 'Admin'
o response = "<h1>Welcome to Sessions </h1><br>"
o response += "ID : {0} <br>".format(request.sessio
n.session_key)
o return HttpResponse(response)
www.SunilOS.com 47
48. Session Example
Now we can get session attributes.
o from django.contrib.sessions.models import
Session
o from django.shortcuts import render,redirect
o from django.http import HttpResponse
o def access_session(request):
o response = "Name : {0} <br>"
.format(request.session.get('name'))
o return HttpResponse(response)
We can destroy session using session.objects.all().object()
o def destroy_session(request):
o session.objects.all().delete()
o return HttpResponse("Session is destroy")
www.SunilOS.com 48
49. Cookie Handling
A cookie is a key and value pair
(key=value), set by server at
browser.
Cookies are stored in a file.
Cookies files are owned and
controlled by browsers.
Cookies are attached with requested
URLs as header.
A cookie has maximum age and
removed by Browser after
expiration.
Desktop may have multiple
browsers.
Each browser has separate cookie
file in a separate folder.
Cookies can be enabled or disabled
by browser
www.SunilOS.com 49
Desktop
IE
KeyN=valueN
FireFox
KeyN=valueN
Web Server
50. Set Cookies
from django.shortcuts import render
from django.http import HttpResponse
def setCookie(request):
if request.method=="POST":
name=request.POST["cookieName"]
value=request.POST["cookieValue"]
res = HttpResponse("<h1>Rays Technologies</h1>")
res.set_cookie(name,value, max_age = None)
return res
return render(request,"SetCookies.html")
www.SunilOS.com 50
51. Get Cookies
Now we can get Cookies.
o from django.shortcuts import render
o from django.http import HttpResponse
o Def getCookies(request):
o show = request.COOKIES.get('rays')
o html = "<center>Value is
{0}</center>".format(show)
o return HttpResponse(html)
www.SunilOS.com 51
53. render and redirect
render combines a given template with a given context.
render return HttpResponse object.
o from django.shortcuts import render
o def index(request):
o msg="Welcome to Rays"
o return render(request,"index.html",{"message
":msg})
www.SunilOS.com 53
54. render and redirect
If we can call one function to another function .
If you want to change URL in browser’s address bar then we can use
redirect.
Redirect returns an HttpResponseRedirect.
o from django.shortcuts import redirect
o def index(request):
o return redirect("/Welcome/")
www.SunilOS.com 54
55. Middleware
Middleware is a regular python class.
Middleware classes are called twice during the request/response life
cycle.
Middleware class should define at least one of the following methods.
o Called during request:
process_request(request)
process_view(request, view_func, view_args,
view_kwargs)
o Called during response:
process_exception(request, exception) (only if the
view raised an exception)
process_template_response(request, response) (only
for template responses)
process_response(request, response)
www.SunilOS.com 55
56. How Middleware works
During the request cycle: the Middleware classes are executed top-
down.
Firstly executed SecurityMiddleware , then SessionMiddleware
all the way until XFrameOptionsMiddleware.
For each of the Middlewares it will execute the process_request()
and process_view() methods.
During the response cycle: the Middleware classes are executed bottom
- up.
Firstly executed XFrameOptionsMiddleware then
MessageMiddleware all the way until SecurityMiddleware.
For each of the Middlewares it will execute the
process_exception(), process_template_response() and
process_response() methods.
www.SunilOS.com 56
58. Create Custom Middleware
Django initializes your middleware with only the get_response argument.
You can’t define __init__() as requiring any other argument.
The __call__() method which is called once per request.
__init__() is called only once, when the Web server starts.
Now we can create custom Middleware file . inside app.
ORS/
o __init__.py
o CustomMiddleware
o admin.py
o apps.py
o migrations/
__init__.py
o models.py
o tests.py
o urls.py
o views.py
www.SunilOS.com 58
60. Unit test cases
Automated testing is useful tool for bug-tracking .
Web application testing is complex .
Django provide unit test module for testing .
Unit test module built in python standard library.
We can use django.test.TestCase class.
Django provide tests.py file .
We can write our testing code in tests.py file.
o Migrations
__init__.py
o __init__.py
o admin.py
o apps.py
o models.py
o tests.py
o views.py
www.SunilOS.com 60
61. tests.py
Now we can create TestModel class for model testing.
o from django.test import TestCase
o from ors.models import Student
o class TestModel (TestCase):
o form=Student(firstName = "Ram"
,lastName = "Sharma",mobileNumber="987654321“ ,
email = "ab@gmail.com",password="1234")
o form.save()
o print("data saved")
Now we can run this file using following command .
o py manage.py tests.py
www.SunilOS.com 61
62. Disclaimer
This is an educational presentation to enhance the skill
of computer science students.
This presentation is available for free to computer
science students.
Some internet images from different URLs are used in
this presentation to simplify technical examples and
correlate examples with the real world.
We are grateful to owners of these URLs and pictures.
www.SunilOS.com 62