SlideShare una empresa de Scribd logo
1 de 63
www.SunilOS.com 1
Django
www.sunilos.com
www.raystec.com
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
www.SunilOS.com 3
Why Django
 It is Fast
 Fully Loaded.
• Authentication
• Security
• session management
 Security CSRF(Cross-site request forgery).
 Scalability.
 Versatile.
www.SunilOS.com 4
Famous applications
 Instagram
 Spotify
 YouTube
 The Washington post
 Bitbucket
 Dropbox
 Eventbrite
 Mozilla
 Prezi
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
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
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
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
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
Register App
 Register ORS App in settings.py file.
 Inside INSTALLED_APPS arraye be can register our App.
 INSTALLED_APPS = [
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'ORS'
 ]
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
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
Output
MVT Architecture
 Django application follows MVT Architecture.
 MVT is stand for Model ,View and Template.
www.SunilOS.com 14
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
MVT vs MVC
www.SunilOS.com 16
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/
Admin Interface
 Enter login_ID and password
Admin Interface
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
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.
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),]
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/
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
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 }

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
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.
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.
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")
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
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
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
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
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
Template
www.SunilOS.com 35
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
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
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
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
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
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
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
Session - HTTP is a stateless protocol
www.SunilOS.com 43
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
A Student’s Session
www.SunilOS.com 45
A Web User’s Session
www.SunilOS.com 46
Session.objects.all().delete()
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
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
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
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
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
render and redirect
www.SunilOS.com 52
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
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
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
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
Middleware
 MIDDLEWARE_CLASSES = [
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddl
eware’,
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 ]

www.SunilOS.com 57
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
Create Custom Middleware
 from django.conf import settings
 from django.http import HttpResponse
 class SimpleMiddleware(object):
 def __init__(self, get_response):
 self.get_response = get_response

 def __call__(self, request):
 response = self.get_response(request)
 return HttpResponse('Welcome to Middleware')
www.SunilOS.com 59
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
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
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
Thank You!
www.SunilOS.com 63
www.SunilOS.com

Más contenido relacionado

La actualidad más candente

Java Basics
Java BasicsJava Basics
Java BasicsSunil OS
 
Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...Edureka!
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC FrameworkBala Kumar
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To DjangoJay Graves
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoKnoldus Inc.
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJames Casey
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Djangomcantelon
 
Intro to Web Development Using Python and Django
Intro to Web Development Using Python and DjangoIntro to Web Development Using Python and Django
Intro to Web Development Using Python and DjangoChariza Pladin
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to djangoIlian Iliev
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture IntroductionHaiqi Chen
 
JavaScript
JavaScriptJavaScript
JavaScriptSunil OS
 
Django Interview Questions and Answers
Django Interview Questions and AnswersDjango Interview Questions and Answers
Django Interview Questions and AnswersPython Devloper
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial之宇 趙
 
Python Pandas
Python PandasPython Pandas
Python PandasSunil OS
 
Collection v3
Collection v3Collection v3
Collection v3Sunil OS
 

La actualidad más candente (20)

Java Basics
Java BasicsJava Basics
Java Basics
 
django
djangodjango
django
 
Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC Framework
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To Django
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Django
 
Intro to Web Development Using Python and Django
Intro to Web Development Using Python and DjangoIntro to Web Development Using Python and Django
Intro to Web Development Using Python and Django
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture Introduction
 
Python/Django Training
Python/Django TrainingPython/Django Training
Python/Django Training
 
JavaScript
JavaScriptJavaScript
JavaScript
 
CSS
CSS CSS
CSS
 
Django Interview Questions and Answers
Django Interview Questions and AnswersDjango Interview Questions and Answers
Django Interview Questions and Answers
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Collection v3
Collection v3Collection v3
Collection v3
 

Similar a DJango

Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST FrameworkEasy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST FrameworkInexture Solutions
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
An Introduction to Django Web Framework
An Introduction to Django Web FrameworkAn Introduction to Django Web Framework
An Introduction to Django Web FrameworkDavid Gibbons
 
Django tutorial
Django tutorialDjango tutorial
Django tutorialKsd Che
 
Mini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesMini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesLeonardo Fernandes
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath Shenoy
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django frameworkKnoldus Inc.
 
Django Frequently Asked Interview Questions
Django Frequently Asked Interview QuestionsDjango Frequently Asked Interview Questions
Django Frequently Asked Interview QuestionsAshishMishra308598
 
بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگوrailsbootcamp
 
Django for mobile applications
Django for mobile applicationsDjango for mobile applications
Django for mobile applicationsHassan Abid
 
Django Workflow and Architecture
Django Workflow and ArchitectureDjango Workflow and Architecture
Django Workflow and ArchitectureAndolasoft Inc
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting startedMoniaJ
 

Similar a DJango (20)

Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST FrameworkEasy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
 
Django by rj
Django by rjDjango by rj
Django by rj
 
Django
DjangoDjango
Django
 
Django web framework
Django web frameworkDjango web framework
Django web framework
 
Mini Curso de Django
Mini Curso de DjangoMini Curso de Django
Mini Curso de Django
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
An Introduction to Django Web Framework
An Introduction to Django Web FrameworkAn Introduction to Django Web Framework
An Introduction to Django Web Framework
 
React django
React djangoReact django
React django
 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
 
Mini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesMini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico Ces
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
 
Treinamento django
Treinamento djangoTreinamento django
Treinamento django
 
Basic Python Django
Basic Python DjangoBasic Python Django
Basic Python Django
 
Django Frequently Asked Interview Questions
Django Frequently Asked Interview QuestionsDjango Frequently Asked Interview Questions
Django Frequently Asked Interview Questions
 
بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگو
 
Django for mobile applications
Django for mobile applicationsDjango for mobile applications
Django for mobile applications
 
Django Workflow and Architecture
Django Workflow and ArchitectureDjango Workflow and Architecture
Django Workflow and Architecture
 
Django introduction
Django introductionDjango introduction
Django introduction
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
 

Más de Sunil OS

Threads V4
Threads  V4Threads  V4
Threads V4Sunil OS
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4Sunil OS
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3Sunil OS
 
Threads v3
Threads v3Threads v3
Threads v3Sunil OS
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3Sunil OS
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJSunil OS
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and OperatorsSunil OS
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays TechnologiesSunil OS
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFCSunil OS
 

Más de Sunil OS (20)

Threads V4
Threads  V4Threads  V4
Threads V4
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
OOP V3.1
OOP V3.1OOP V3.1
OOP V3.1
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
 
OOP v3
OOP v3OOP v3
OOP v3
 
Threads v3
Threads v3Threads v3
Threads v3
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
 
Angular 8
Angular 8 Angular 8
Angular 8
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays Technologies
 
Hibernate
Hibernate Hibernate
Hibernate
 
C++ oop
C++ oopC++ oop
C++ oop
 
C++
C++C++
C++
 
C Basics
C BasicsC Basics
C Basics
 
Log4 J
Log4 JLog4 J
Log4 J
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
 

Último

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 

Último (20)

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 

DJango

  • 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.
  • 4. www.SunilOS.com 4 Famous applications  Instagram  Spotify  YouTube  The Washington post  Bitbucket  Dropbox  Eventbrite  Mozilla  Prezi
  • 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
  • 10. Register App  Register ORS App in settings.py file.  Inside INSTALLED_APPS arraye be can register our App.  INSTALLED_APPS = [  'django.contrib.admin',  'django.contrib.auth',  'django.contrib.contenttypes',  'django.contrib.sessions',  'django.contrib.messages',  'django.contrib.staticfiles',  'ORS'  ]
  • 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/
  • 18. Admin Interface  Enter login_ID and password
  • 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
  • 57. Middleware  MIDDLEWARE_CLASSES = [  'django.middleware.security.SecurityMiddleware',  'django.contrib.sessions.middleware.SessionMiddleware',  'django.middleware.common.CommonMiddleware',  'django.middleware.csrf.CsrfViewMiddleware',  'django.contrib.auth.middleware.AuthenticationMiddleware',  'django.contrib.auth.middleware.SessionAuthenticationMiddl eware’,  'django.contrib.messages.middleware.MessageMiddleware',  'django.middleware.clickjacking.XFrameOptionsMiddleware',  ]  www.SunilOS.com 57
  • 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
  • 59. Create Custom Middleware  from django.conf import settings  from django.http import HttpResponse  class SimpleMiddleware(object):  def __init__(self, get_response):  self.get_response = get_response   def __call__(self, request):  response = self.get_response(request)  return HttpResponse('Welcome to Middleware') www.SunilOS.com 59
  • 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

Notas del editor

  1. www.sunilos.com
  2. www.sunilos.com
  3. www.sunilos.com
  4. www.sunilos.com