Wokring With Python Django-Web Framework Define Statement
Wokring With Python Django-Web Framework Define Statement
Wokring With Python Django-Web Framework Define Statement
Define Statement:
It is type of Logical Instruction.
Define Command:
It is a precompiled or an executable program.
Define Shell:
Collection of commands is called Shell.
Define Program:
Collection of Logical Instructions/Statements
Define Software?
Collection of specialized programs.
Types of Softwares?
Generally softwares are classified into two types:
1. System Software 2. Application Software
Define OS?
1|Page
It is System Software that manages computer hardware and software
resources.
Types of OSs?
OS is classified into the following three types:
1. Single User Single Tasking (SUST)
2. Single User Multi Tasking (SUMT)
3. Multi User Multi Tasking (MUMT)
Library:
A library is a collection of precompiled routines that a program can use.
FRAMEWORK
Platform for developing software applications.
Web Framework (WF)/WAF-Web App Framework:
It is server side application framework, It is designed to support the
development of dynamic websites.
Popular Stacks
Django (Full) Stack: JavaScript - Python - Django - Any RDBMS
MERN Stack: JavaScript-MongoDB-Express-ReatJS-Node.js
MEAN Stack: JavaScript-MongoDB-Express-AngularJS-Node.js
LAMP Stack: JavaScript - Linux - Apache - MySQL - PHP
LEMP Stack: JavaScript - Linux - Nginx - MySQL - PHP
Full Stack JavaScript Developer
Who can develop both Client & Server Software.
1 Program a browser (HTML, CSS, JavaScript, jQuery, Angular, or Vue)
2 Program a server (Node.js)
3 Program a database (MongoDB)
2|Page
Python Frameworks:
Python Frameworks are two types:
Micro-Frameworks:
To refer to minimalistic web application frameworks, suitable for Small Apps.
Example: Flask, Bottle, cherrypy, web.py etc.
Full-Stack Frameworks
There are two main components of a website:
1. The Front-End (Client Side) 2. The Back-End (Server Side)
1. The Front-End:
It is what you see as user on the website.
1. HTML & HTML5 2. CSS & CSS3 3. JavaScript 4. jQuery, AngularJS,
Angular 5. Bootstrap
2. The Back-End:
1. The Language (PYTHON) JAVA(Servlets&JSP), PHP, ASP, RoR..!!
2. The framework (Django) JSF, Struts, Spring, MVC, Flask, Pyramid
3. The Database(SQLite) Oracle, MySQL, MongoDB
Example:
Django, TurboGears, Web2py etc.
What are web Components ..!
Define DJANGO:
It is PYTHON's MVT Web Framework. (Model-View-Template)
OR
The Web framework for perfectionists with deadlines
OR
It encourages rapid development and clean, pragmatic design.
OR
It is a free open-source full-stack Python web framework
3|Page
OR
It makes it easier to build better Web apps more quickly & with less code
OR
It is a backend framework used to resolve problems of connectivity with
databases, other server problems, SEO solutions.
Django PIC?
Who Developed?
Django was created by two web developers Adrian Holovaty & Simon Willison
working at the Lawrence Journal-World Newspaper in 2003. It was released
publicly as a BSD license in July 2005. It is dedicated to famous guitarist Django
Reinhardt.
PYTHON WEB Frameworks:
Django, TurboGears, Pylons, Zope, Quixote,web2py, GAE, CherryPY, Pyramid,
Flask, Dash, Bottle, Web.PY..!!
Django Popularity:
Django is widely accepted and used by various well-known sites such as:
1 Instagram 2 Mozilla
3 Disqus 4 Pinterest
5 Bitbucket 6 The Washington Times
7 NASA(NationalAeronautics&SpaceAdministration)
8 ONION 9 Yahoo Maps 10 National Geographic
Django Version History
1.0 3 Sep 2008
1.5 26 Feb 2013
2.0 Dec 2017 (LongTermSupport-MobileFriendly)
3.0 Oct 2019
4|Page
Django Features:
1.Object Relational Mapper-ORM
2.MVT (Mode View Template) Architecture
3. Rapid Development & Fully loaded
4. Secure, SQL Injection Attack, Cross Site Scripting, Cross-Site Request Forgery
(CSRF)
5. Scalable & Open Source
6. Versatile, SmallAps, Big Apps, Scientific Apps, Orgnizations, GovApps
7. LTS (LongTermSupport) & Mobile-Friendly
8. Simplified URL Routing Syntax
9 Forms & Generic Views
10 Pagination
Django MVT
It is a software design pattern. The Model helps to handle database.
The Template is a presentation layer which handles User Interface part
completely.
The View is used to execute the business logic and interact with a model to
carry data and renders a template.
5|Page
Template=>Front-End=>UI=>Presentation Logic (HTML, CSS, JS)
Control is handled by the Django framework itself.
PYTHON Web Server (WSGI):https://wsgi.readthedocs.io
Web Server Gateway Interface. It is a specification that describes how a web
server communicates with web applications.
Frameworks that run on WSGI:
1.Django 2.bobo
3.Bottle 4.CherryPy
5.Appier 6.Falcon
7.Flask 8.TurboGears
9.Pyramid 10.web2py
Define pip?
It is a package manager for the Python programming language.
Syntax:
pip list [options]
Download get-pip.py, save in a specific location and run the following
command from DOS prompt.
Installation
$python get-pip.py
Upgrading pip: UNIX:
$pip install -U pip
Upgrading pip:Windows:
$python -m pip install -U pip
$python -m pip install -U --user pip
pip Commands:
$pip list
6|Page
$pip help
$pip help install
$pip show django
$pip download django
$pip install virtualenv
$pip freeze > requirements.txt
Output installed packages in requirements format
https://pip.pypa.io/en/stable/reference/
Django Environment Setup:
Django development environment consists of installing and setting up Python,
Django, and a Database System.
$ pip install django
$ conda install django
$ pip install --upgrade django
$ pip install Django==3.0.4
$ py -m django --version
$ django.VERSION
$ django.get_version()
7|Page
==> Bank Accounts Application
==> Fund Transfer Application
==> Transactions Application
==> Beneficiary Application
==> WReports Application
NOTE:
Django Applications are Reusable and Pluggable..!!
Example:
Polling App, News App, Every app provide one or more Services to the end
user.
Create a Folder or Directory for Django Projects:
$mkdir djangoprojects6PM
$cd djangoprojects6PM
Creating the First Project in Django:
Syntax:
$ django-admin startproject projectname
django-admin ==> Command
startproject ==> Option
projectname ==> Name of the Project as per the business Reqs.
Example
$ django-admin startproject BFSI
$cd BFSI
$dir
#System Hidden Directories
. ==> Current Directory
.. ==> Root Directory/Parent Directory
manage.py ==> manage django project root
8|Page
BFSI ==> Django level Directory
tree:
Displays directory paths and (optionally) files in each subdirectory
Syntax:
tree [/A][/F]
Example:
$ tree /f
Django Project Architecture:
[BFSI]/ <== Project root
├── [BFSI]/ <== Django root
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
Running the Django Project
Django project has a built-in development server.
Example:
$py manage.py runserver (Windows)
OR
$python manage.py runserver (Unix/Linux/Windows)
OR
$python3 manage.py runserver (Unix/Linux/Mac)
py or python or python3 ==> Interpreter name
manage.py ==> to mangage project resources
runserver ==> Command
9|Page
Server will run with few warnings, Just open any Major Web Browser , type==>
http://127.0.0.1:8000
It displays successful message with a rocket symbol..!
To Quit the web-server hit the key Ctrl+C OR Ctrl+Break
DJANGO Project Files & Description:
__init__.py:
It is an empty file that tells to the Python that this directory should be
considered as a Python package.
settings.py:
It is the central configuration for all Django projects.
By default, INSTALLED_APPS contains the following apps:
django.contrib.admin–The admin site. You’ll use it shortly.
django.contrib.auth–An authentication system.
django.contrib.contenttypes–A framework for content types.
django.contrib.sessions–A session framework.
django.contrib.messages–A messaging framework.
django.contrib.staticfiles–Aframework for managing static files
Middleware:
It is a framework of hooks into Django's request/response processing. It has
the following major components...!!
1 TEMPLATES 2 DATABASES
3 WSGI 4 SECRET_KEY
5 ALLOWED_HOSTS 6 AUTH_PASSWORD_VALIDATORS
Managing Static Files:
Websites generally need to serve additional files such as images, JS, or CSS.
urls.py :
Contains URL patterns for the Django project.
10 | P a g e
wsgi.py:
Contains WSGI configuration properties for the Django project. It is the
recommended approach to deploy Django applications on production.
manage.py:
It is a command-line utility,which allows us to interact with the project in
various ways, also used to manage an application. It can perform app creation,
runserver, run test cases and migrations.
Django Admin Commnds:
$ django-admin help --commands:
To display list of commands related django environment..!!
1. check
2. compilemessages
3. createcachetable
4. dbshell
5. diffsettings
6. dumpdata
7. flush
8. inspectdb
9. loaddata
10. makemessages
11. makemigrations
12. migrate
13. runserver
14. sendtestemail
15. shell
16. showmigrations
17. sqlflush
11 | P a g e
18. sqlmigrate
19. sqlsequencereset
20. squashmigrations
21. startapp
22. startproject
23. test
24. testserver
$django-admin help <subcommand>
Syntax:
$django-admin help <subcommand>
Example:
$django-admin help check
Example:
django-admin help shell
Example:
$ django-admin version
How to change Django Server Port:
$ py manage.py runserver 8888
Now Server running on port number: 8888
We have to send the request with this port number only
http://127.0.0.1:8888/
NOTE:
$python manage.py runserver 6666
http://127.0.0.1:6666/
If a port number already existed, It displays "This address is restricted"
BEST BOOKS FOR DJANGO
12 | P a g e
Django for Beginners =>William S Vincent
Build Your First Website with Django 2.2.2 =>Nigel George
13 | P a g e
WebApp Consist following Structure :
├──WebApp
│ ├── __init__ .py
│ ├──admin.py
│ ├──apps.py
│ ├──migrations
│ │ └── __init__ .py
│ ├──models.py
│ ├──tests.py
│ └──views.py
1 __init__.py
It is an empty file that tells to the Python that this directory should be
considered as a Python package.
2 admin.py
You can register your models here which Django will use them with Django's
admin interface.
3 apps.py
Here you can place application specific configurations
4 models.py
We define our database models, which Django automatically translates into
database tables
5 tests.py
Here you can store test functions to test your code.
6 views.py
Here we handle the request/response logic for our web app
7 migrations
14 | P a g e
This directory stores database specific information as it relates to the models.
Configuring App in Project: //settings.py
Go to Installed_apps, at the end or start, provide recently created .
Example:
#User Defined Apps
'WebApp',
views:
A view is a place where we put our business logic of the application.
urls:
This is Python script that will store all URL patterns for your project.
How URLs, Views are working?
The following diagram describes urls and views working principle..!!
PIC:
LIVE EXAMPLE on VIEWs & URLs:
STEP1: Create Project
$django-admin startproject djAppConfig
$cd djAppConfig
STEP2:Create Application
$django-admin startapp WebApp
STEP3:$py manage.py runserver
STEP4:Open Project with PyCharm or Any IDE(ATOM, Visual Studio Code,
Sublime, Brackets..)
STEP5: Do required settings, App configuration @ Installed Apps..!!
STEP6: views.py
from django.http import HttpResponse
# Create your views here.
def HomePage(request):
15 | P a g e
return HttpResponse("Welcome to DJANGO Web World..!!")
STEP7:urls.py
from django.contrib import admin
from django.urls import path
from WebApp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('home/',views.HomePage),
]
STEP8:Run the server
$python manage.py runserver
STEP9: Open web browser, send the request to Server
127.0.0.1:8000/home
Example:
STEP1: Create Project
$django-admin startproject ViewsUrls
$cd ViewsUrls
STEP2:Create Application
$django-admin startapp WebApp
STEP3:$py manage.py runserver
STEP4:Open Project with PyCharm or Any IDE(ATOM, Visual Studio Code,
Sublime, Brackets..)
STEP5: Do required settings, App configuration @ Installed Apps..!!
STEP6: views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
16 | P a g e
def Home_Page(request):
return HttpResponse("<h1>Welcome to Django World</h1>")
STEP7:urls.py
from django.contrib import admin
from django.urls import path
from WebApp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('home/',views.Home_Page),
]
STEP8:Run the server
$python manage.py runserver
STEP9:Open web browser, send the request to server
127.0.0.1:8000/home
Example:
STEP1: Create Project
$django-admin startproject ViewsUrlsTwo
$cd ViewsUrlsTwo
STEP2:Create Application
$django-admin startapp WebApp
STEP3:$py manage.py runserver
STEP4:Open Project with PyCharm or Any IDE(ATOM, Visual Studio Code,
Sublime, Brackets..)
STEP5: Do required settings, App configuration @ Installed Apps..!!
STEP6 views.py
from django.shortcuts import render
from django.http import HttpResponse
17 | P a g e
# Create your views here.
def Index(request):
return HttpResponse("<h1>Welcome to Django World</h1>")
def Home(request):
return HttpResponse("Welcome to Home Page..!!")
STEP7: urls.py
from django.contrib import admin
from django.urls import path
from WebApp import views
from WebApp import views as MyView
urlpatterns = [
path('admin/', admin.site.urls),
path('Index/',views.Index),
path('Home/',MyView.Home),
]
STEP8: Run the Server
$ python manage.py runserver
STEP9:Open any web browser and enter the URL
http://127.0.0.1:8000/Index/
http://127.0.0.1:8000/Home/
18 | P a g e
What is a URL?
It is a web address / A resource on the Internet.
Example:
http://127.0.0.1:8000
https://www.nareshit.com
http: Transfer Protocol, A Common language between Client & Server
s ==> SSL ==>Secure Sockets Layer for Encryption
:// ==> Speical Characters
www ==> Default Domain or Sub Domain
. ==> Period or Embedded Character
nareshit ==> Primary Level Domain(PLD)
com ==> Top Level Domain(TLD)
To customize urls in django, we are having the following three builtin
functions:
1.path() 2.re_path() 3.include()
path():
It returns an element for inclusion in url patterns. It is used to map the URL and
call the specified view.
Syntax:
path(route, view, kwargs=None, name=None)
a. The route argument should be a string, that contains a URL pattern.
b. The view argument is a view function
c. The kwargs argument allows you to pass additional arguments to the view
function or method.
d. The name argument allows Naming URL patterns
Example:
STEP1: Create Project
19 | P a g e
$django-admin startproject URLS
$cd URLS
STEP2:Create Application
$django-admin startapp WebApp
STEP3:$py manage.py runserver
STEP4:Open Project with PyCharm or Any IDE(ATOM, Visual Studio Code,
Sublime, Brackets..)
STEP5: Do required settings, App configuration @ Installed Apps..!!
STEP6:views.py
from django.http import HttpResponse
# Create your views here.
def Home_Page(request):
return HttpResponse("<h1>Welcome to Home Page</h1>")
def Index_Page(request):
return HttpResponse("<h2>Welcome to Index Page</h2>")
STEP7:urls.py
from django.urls import path
from WebApp import views
urlpatterns=[
path('',views.Home_Page),
path('index/',views.Index_Page),
]
STEP8:Runserver
$py manage.py runserver
STEP9:Send the request to Server
http://127.0.0.1:8000
http://127.0.0.1:8000/index
20 | P a g e
Example: Passing Int values to a Web Page..!!
NOTE:
In PYTHON 'f' indicates that these strings are used for formatting.
formatted string literals or simply called "f-strings"
STEP7:urls.py from django.urls import path from
WebApp import views urlpatterns=[
path('',views.Home_Page),
path('index/<int:id>/',views.Index_Page),
]
STEP8:Runserver
$py manage.py runserver
21 | P a g e
STEP9:Send the request to Server http://127.0.0.1:8000/
http://127.0.0.1:8000/index/1
Example:kwargs attribute:
It allows you to pass additional arguments to the view function or method. It is
in dictionary format.
STEP1: Create Project
$django-admin startproject URLSTHREE
$cd URLSTHREE
STEP2:Create Application
$django-admin startapp WebApp
STEP3:$py manage.py runserver
STEP4:Open Project with PyCharm or Any IDE(ATOM, Visual Studio Code,
Sublime, Brackets..)
STEP5: Do required settings, App configuration @ Installed Apps..!!
STEP6:views.py from django.shortcuts
import render from django.http import
HttpResponse # Create your views
here. def MyView(request,val1,val2):
Msg=val1+" "+val2+" "+"Home Page"
return HttpResponse(Msg)
22 | P a g e
STEP9:Send the request to Server
http://127.0.0.1:8000/home
Example:
EXAMPLE:
$django-admin startproject URLSFOUR
$cd
URLSFOUR
STEP2:Create Application
$django-admin startapp WebApp
STEP3:$py manage.py runserver
STEP4:Open Project with PyCharm or Any IDE(ATOM, Visual Studio Code,
Sublime, Brackets..)
STEP5: Do required settings, App configuration @ Installed Apps..!!
STEP6 views.py from django.shortcuts import render from
django.http import HttpResponse,HttpResponseRedirect from
django.urls import reverse # Create your views here. def
home(request):
return HttpResponse("<a href='/hi'>Hello</a>") def
MyView(request):
return HttpResponseRedirect(reverse('bye')) def
ByeView(request): return
HttpResponse("Good Bye")
STEP7: urls.py
23 | P a g e
from django.contrib import admin
from django.urls import path
from WebApp import views
urlpatterns = [
path('admin/',admin.site.urls),
path('home/',views.home,name='home')
path('hi/',views.MyView,name='hi'),
path('bye/',views.ByeView,name='bye')
]
STEP8:Runserver
$py manage.py runserver
STEP9:Send the request to Server http://127.0.0.1:8000/home
27/03/2020
24 | P a g e
STEP5: Do required settings, App configuration @ Installed Apps..!!
STEP6:views.py from django.http import HttpResponse
# Create your views here. def
Home_Page(request):
return HttpResponse("<h1>Welcome to Home Page</h1>") def
Index_Page(request):
return HttpResponse("It is Index Page")
STEP7:urls.py
from django.contrib import admin
from django.urls import path, re_path
from WebApp import views
urlpatterns = [ path('admin/',
admin.site.urls),
re_path(r'^home/$',views.Home_Page),
re_path(r'^index/$',views.Index_Page),
]
STEP8:Runserver
$py manage.py runserver
STEP9:Send the request to Server http://127.0.0.1:8000/home
http://127.0.0.1:8000/index
Example:
$django-admin startproject URLSSIX
$cd URLSSIX
STEP2:Create Application
$django-admin startapp WebApp
STEP3:$py manage.py runserver
STEP4:Open Project with PyCharm or Any IDE(ATOM, Visual Studio Code,
Sublime, Brackets..)
STEP5: Do required settings, App configuration @ Installed Apps..!!
STEP6:views.py
25 | P a g e
from django.http import HttpResponse
# Create your views here. def
Home_Page(request):
return HttpResponse("<h1>Welcome to Home Page</h1>")
def Index_Page(request,year):
return HttpResponse(f'Welcome to Index Page of {year}')
STEP7:urls.py
from django.urls import path,re_path
from WebApp import views
urlpatterns=[ path('',views.Home_Page),
re_path(r'^index/(?P<year>[0-9]{4})/$',views.Index_Page),
]
STEP8:Runserver
$py manage.py runserver
STEP9:Send the request to Server http://127.0.0.1:8000/index/2019
include():
A function that takes a full Python import path to another URLconf module
that should be "included" in this place.
Syntax:
include(module,namespace=Non
e) OR include(pattern_list)
Parameter:
module ==>URLconf module (or module name) namespace (str)
==>Instance namespace for the URL entries being included pattern_list
==> Iterable of path() and/or re_path() instances.
EXAMPLE:
$django-admin startproject URLSIX
$cd URLSIX
STEP2:Create Application
$django-admin startapp WebApp
26 | P a g e
STEP3:$py manage.py runserver
27 | P a g e
27/03/2020 day-7
WORKING WITH DJANGO TEMPLATES
Django needs a convenient way to generate HTML dynamically. The most
common approach relies on templates. It is not recommended to write html
code inside python script (views.py):
1 It reduces readability, if Python code mixed with html code.
2 Python developer need to concentrate on PYTHON & HTML.
NOTE:
1 To overcome these problems by seperate html. This html file is nothing but
Template.
2 Write templates at project level one time, We can use these in multiple Apps.
Django Template Configuration(DTC):
Do the following updates in settings.py, Run in command Prompt:
STEP1:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(__file__)
$py settings.py
STEP2:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(os.path.abspath(__file__))
$py settings.py
STEP3:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(BASE_DIR)
$py settings.py
28 | P a g e
1. $django-admin startproject TemplateProject
2.$cd TemplateProject
3.$py manage.py startapp WebApp
4. Configure this WebApp to the project in settings.py file
5. Create a 'templates' folder inside main project folder. In that, create a
seperate folder to hold templates.
6. Configure templates folder in settings.py file @ TEMPLATES
TEMPLATES = [
{...,
'DIRS': ['I:\TemplateProject\templates'],
},]
NOTE:
In Django, never recommended to hard-code specific locations.!
Configuring relative path in TEMPLATES:
STEP1:Assigning Template Variable
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STEP2: Specify this TEMPLATE_DIR in settings.py:
TEMPLATES = [{...,
'DIRS': [TEMPLATE_DIR,],
},]
render() function:
Combines a given template with a given context dictionary and returns an
HttpResponse object with that rendered text.
Syntax:
29 | P a g e
render(request, template_name, context=None)
Arguments:
1 request: The request object used to generate this response
2 template_name: The full name of a template to use or sequence of template
names.
3 context: A dictionary of values to add to the template context. By default,
this is an empty dictionary.
LIVE EXAMPLE ON TEMPLATE(s):
STEP1: Create Project
$django-admin startproject TemplateProject
$cd TemplateProject
STEP2:Create Application
$django-admin startapp WebApp
STEP3:$py manage.py runserver
STEP4:Open Project with PyCharm or Any IDE(ATOM, Visual Studio Code,
Sublime, Brackets..)
STEP5: Do required settings, App configuration @ Installed Apps, Template
configuration @ TEMPLATES
Step6:Welcome.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Django Templates...!!</title>
<style type="text/css">
h1{
color:red;font-family:candara;
30 | P a g e
text-decoration:underline;
}
</style>
</head>
<body>
<h1>Welcome to Django World..!!</h1>
<h1>Say Hey Django Templates.!</h1>
</body>
</html>
Step7: views.py:
from django.shortcuts import render
# Create your views here.
def MyTempView(request):
return render(request,'MyApp/Welcome.html')
Step8:urls.py
from django.contrib import admin
from django.urls import path
from WebApp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('temp/',views.MyTempView),
]
Step9:Send the request to web server
http://127.0.0.1:8000/temp/
31 | P a g e
EXAMPLE ON TEMPLATES USING TABLE TAG:
STEP1: Create Project
$django-admin startproject TemplateProject
$cd TemplateProject
STEP2:Create Application
$django-admin startapp WebApp
STEP6:Welcome.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Django Templates..!!</title>
</head>
<body>
<table>
<tr>
<th>StdNo</th>
<th>StdName</th>
<th>Result</th>
</tr>
<tr>
<td>101</td>
<td>Raaj</td>
<td>Pass</td>
</tr>
<tr>
<td>102</td>
<td>SARA</td>
<td>Fail</td>
</tr>
32 | P a g e
</table>
</body>
</html>
STEP7: Thanks.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Django Templates..!!</title>
</head>
<body>
<h1>Thanks you for Visiting Our Page...!!</h1>
</body>
</html>
STEP8:views.py: from
django.shortcuts import render #
Create your views here. def
Welcome_Page(request):
return render(request,'MyApp/Welcome.html')
def Thanks_Page(request):
return render(request,'MyApp/Thanks.html')
STEP9:urls.py from
django.contrib import admin
from django.urls import path
from WebApp import views
urlpatterns = [ path('admin/',
admin.site.urls),
path('wish/',views.Welcome_Page),
path('thank/',views.Thanks_Page),
]
33 | P a g e
What is Jinja?
A full featured template engine for Python.
OR
It is a modern and designer-friendly templating language for Python,
modelled after Django’s templates. It is fast, widely used and secure with
the optional sandboxed template execution environment:
NOTE:
A Jinja template doesn’t need to have a specific extension: .html, .xml, or
any other extension is just fine.
Features:
1 sandboxed execution (Evaluate untrusted code)
2 powerful automatic HTML escaping system for XSS(Cross-site scripting)
prevention
3 template inheritance
4 compiles down to the optimal python code just in time 5 optional ahead-
of-time template compilation 6 easy to debug.
7 configurable syntax
Cross-site scripting:
XSS is a security breach that takes advantage of dynamically generated
Web pages. It is a client-side code injection attack. The attacker aims to
execute malicious scripts in a web browser. XSS attacks are possible in
VBScript, ActiveX, Flash, and even CSS.
Prerequisites:
Jinja2 works with Python 2.6.x, 2.7.x and => 3.x.
Installation:
$easy_install Jinja2
$pip install Jinja2
There are a few kinds of delimiters. The default Jinja delimiters are
configured as follows: {% ... %} for Statements
{{ ... }} for Expressions to print to the template output
{# ... #} for Comments not included in the template output
# ... ## for Line Statements
34 | P a g e
4 {% if %} .. {% endif %}
5 {% macro %}..{% endmacro %}
6 {% call %} ..{% endcall %}
7 {% filter %} ..{% endfilter %}
8 {% set %} .. {% endset %}
9 {% trans %} .. {% endtrans %}
10 {% with %}..{% endwith %}
11 {% autoescape %}..{% endautoescape %}
12 {% pluralize %}
13 {% extends %}
14 {% include %}
https://jinja.palletsprojects.com/en/2.10.x/templates/#variables
31/03/2020 day-9
35 | P a g e
Available all static files for our template file or html file(s).
To include image follow the Syntax:
<img src="{% static 'images/django.png' %}" alt="SorryNoImage"/>
To Include our css file follow the Syntax:
<link href="{% static 'css/MyFile.css' %}" rel="stylesheet">
NOTE:
At the beginning of HTML file, next to <!DOCTYPE html> we have to include
template tag:
{% load static %}
LIVE Example on STATIC RESOURCES:
STEP1: Create Project
$django-admin startproject StaticProject
$cd StaticProject
STEP2:Create Application
$django-admin startapp WebApp
STEP3:$py manage.py runserver
STEP4:Open Project with PyCharm or Any IDE(ATOM, Visual Studio Code,
Sublime, Brackets..)
STEP5: Do required settings, App configuration @ Installed Apps, Template
configuration @ TEMPLATES, Static Configuration @ End of the settings.py.
STEP6:Welcome.html
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en-IN">
<head>
<meta charset="utf-8">
<title>Hello Static Page</title>
36 | P a g e
<link href="{% static 'css/MyFile.css' %}" rel="stylesheet"/>
</head>
<body>
<h1>{{ dt }}</h1>
<h2>{{ name }}</h2>
<h3>{{ wish }}</h3>
<img src="{% static 'images/django.png' %}" alt="SorryNoImg">
<img src="{% static 'images/IndiaElections.png' %}" alt="Sorry NoImage">
</body>
</html>
Step7: MyFile.css
h1{
color:#FF0000;text-align:right;text-decoration:overline;
}
h2{
color:#0000FF;text-align:left;text-decoration:underline;
}
h3{
color:#00FFFF;text-align:center;text-decoration:line-through;
}
Step8: views.py
from django.shortcuts import render
from datetime import datetime
# Create your views here.
def TimeInfo(request):
dt=datetime.now()
37 | P a g e
name = 'NareshIT-HYDERABAD'
th=int(dt.strftime('%H'))
if th<12:
wish="Good Morning Buddy"
elif th<16:
wish="Good Afternoon Dude"
else:
wish="Good Night Guys-Sleep Well"
PyDict={'dt':dt,'name':name,'wish':wish}
return render(request,'MyApp/Welcome.html',context=PyDict)
Step9:urls.py:
from django.contrib import admin
from django.urls import path
from WebApp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('tinfo/',views.TimeInfo),
]
Step10:
Run the django server, Open the url on the web browser..!!
http://127.0.0.1:8000/tinfo/
Adding More in HTML file:
<marquee scrollamount="40" onmouseover="this.stop()"
onmouseout="this.start()">
<img src="{% static 'images/django.png' %}" alt="SorryImageNotFound">
<img src="{% static 'images/butterfly.gif' %}" alt="SorryImageNotFound">
</marquee>
38 | P a g e
NOTE:
if url is 'static' name, django framework returns Page not found (404) error.
Directory indexes are not allowed here..!
2/4/2020
Define Database?
A database is an organized collection of data, generally stored and accessed
electronically from a computer system.
Define DBMS
It is system software for creating and managing databases.
Define RDBMS
It is a database management system based on the relational model of data. It is
introduced by E.F. Codd.
What is Model?
A model is a class that represents table or collection in our DB. It maps to a
single database table. Each model is a Python class that subclasses
django.db.models.Model
What is SQLite?
SQLite is embedded relational database management system. It is self-
contained, serverless, zero configuration and transactional SQL database
engine. It was designed by D. Richard Hipp.
SQLite Features:
1.SQLite is totally free
2.SQLite is serverless
3.SQLite is very flexible
4.Configuration Not Required
5.SQLite is a cross-platform DBMS
Download & Installation:
39 | P a g e
https://www.sqlite.org/download.html
SQLite Commands
There are three types of SQLite commands:
DDL: Data Definition Language
CREATE, ALTER, DROP
DML: Data Manipulation Language
INSERT, UPDATE, DELETE
DQL: Data Query Language
SELECT
SQLite dot Command
These commands are not terminated by a semicolon (;).
.help==> Displays list of help info..!!
Special dot commands
1 .header on 2 .mode column 3 .timer on
Comments:
It begin with two consecutive "-" characters.
It also appears with "/*" and extend up to and including the next "*/" .
SQLite Statements
All the SQLite statement is started with any of the keywords like CREATE,
SELECT, INSERT, UPDATE, DELETE, ALTER, DROP, etc. All the statement will
ends with a semicolon (;).
SQLite Create Database:
Sytax:
sqlite3 DatabaseName.db
Example:
sqlite3 Django.db
You can check the created database by using the ".databases" command.
40 | P a g e
.databases
The .quit Command
It is used to be come out of the sqlite prompt:
.quit
SQLite Create Table:
Syntax:
CREATE TABLE DBName.TableName(
column1 datatype PRIMARY KEY(one or more columns),
column2 datatype,
column3 datatype,
.....
columnN datatype,
);
Example:
CREATE TABLE STUDENT(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50)
);
use the ".tables" command to see if your table(s)
.tables
Django Model Commands:
1 dbshell
django-admin dbshell
2 dumpdata
41 | P a g e
django-admin dumpdata [app_label[.ModelName] [app_label[.ModelName]
...]]
3. flush
django-admin flush
4. inspectdb
django-admin inspectdb [table [table ...]]
5. loaddata
django-admin loaddata fixture [fixture ...]
6. makemessages
django-admin makemessages
7. makemigrations
django-admin makemigrations [app_label [app_label ...]]
8. migrate
django-admin migrate [app_label] [migration_name]
9. shell
django-admin shell
Starts the Python interactive interpreter.
10. showmigrations
django-admin showmigrations [app_label [app_label ...]]
Shows all migrations in a project. You can choose from one of two formats:
--list, -l
--plan, -p
11. sqlflush
django-admin sqlflush
12. sqlmigrate
django-admin sqlmigrate app_label migration_name
13. sqlsequencereset
42 | P a g e
django-admin sqlsequencereset app_label [app_label ...]
14. squashmigrations
django-admin squashmigrations app_label [start_migration_name]
migration_name
SQLite Database Configuration:
The simplest possible settings file is for a single-database setup using SQLite.
settings.py: It is the dictionary format, in dictionary we can take any order...!!
DATABASES = {'default':
{'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
Configuring Database with the following parameters.
ENGINE: Name of Database engine (It is like driver software, It is responsable
to convert our python code into database specific terminology. It is vary from
DB to DB)
NAME: Database Name (Required database name)
USER: Database Login user name
PASSWORD: Database Login password
HOST: The Machine on which database server is running
PORT: The port number on which database server is running
Checking Django DB Connection:
We can check whether django db configurations are properly configured or
not.
$py manage.py shell
In [2]: or >>> from django.db import connection
43 | P a g e
In [3]: or >>> d=connection.cursor()
In [4]: or >>> print(d)
In [5]: or >>> exit() or quit()
NOTE:
If we are not getting any error, means db configurations success
3/4/2020
MYSQL & DJANGO : MySQL is an open-source RDBMS
Configuration of MySQL DB:
We have to install mysqlclient by using pip as follows:
$ pip install --only-binary :all: mysqlclient
settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'student',
'USER':'root',
'PASSWORD':'root',
'HOST':'localhost',
'PORT':3306
}
}
Checking Django DB Connection(MySQL):
$py manage.py shell
In [2]: or >>> from django.db import connection
In [3]: or >>> d=connection.cursor()
44 | P a g e
In [4]: or >>> print(d)
In [5]: or >>> exit()
If any Error in MySQL:
Authentication plugin 'caching_sha2_password' cannot be loaded.
Syntax:
ALTER USER 'username'@'ip_address' IDENTIFIED WITH
mysql_native_password BY 'password';
ORACLE:
Oracle is an ORDBMS developed and marketed by Oracle Corporation. It has
four editions of the Oracle DB.
1 Enterprise Edition 2 Standard Edition
3 eXpress Edition 4 Oracle Lite
Configuring Oracle Database:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'XE',
'USER':'scott',
'PASSWORD':'tiger'
'HOST':'192.168.2.5',
'PORT':1521
}
}
PostgreSQL:
Post-gresS-Q-L is an open source ORDBMS.
DATABASES = {
'default': {
45 | P a g e
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'myproject',
'USER': 'ksraju',
'PASSWORD': 'root',
#Optional
'HOST': 'localhost',
'PORT': '5432',
}
}
DJANGO+MONGODB=DJONGO
Django with MongoDB without changing the Django ORM Use MongoDB as a
backend database for your Django project.
$pip install djongo
Into settings.py file of your project, add:
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'your-db-name',
'HOST': 'your-db-host',
}
}
Python-Data Base Conmmunications(PDBC):-
It stores a collection of data. Each database has one or more distinct APIs for
creating, accessing, managing, searching and replicating the data it holds.
RDBMS store and manage huge volume of data.
You can choose the right database for your application. Python Database API
supports a wide range of database servers:
46 | P a g e
1. MySQL 2. PostgreSQL 3. Microsoft SQL Server
4. Informix 5. Oracle 6. Sybase 7. SQLite
8. MongoDB 9.AnyBigData
What Can SQL do?
1. SQL can execute queries, retrieve data, insert, update and delete records.
2. SQL can create new databases tables, SP, views and set permissions
Most Important SQL Commands:
SELECT, UPDATE, DELETE, INSERT INTO, ALTER DB, Table CREATE TABLE, DROP
TABLE, INDEX..!!
Step1: Install PYTHON
Step2: Install MySQL (8.0 or later)
Step3: MySQL Driver
$python -m pip install mysql-connector
Test MySQL Connector
To test if the installation was successfull,
Example:
import mysql.connector
print(dir(mysql.connector))
Syntax:
mydb = mysql.connector.connect(host="localhost",
user="yourusername", password="yourpassword",database="YourDBName")
Syntax:
mydb = mysql.connector.connect(host="127.0.0.1",
user="yourusername", password="yourpassword",database="YourDBName")
Create Connection
Start by creating a connection to the database.
Use the username and password from your MySQL database:
47 | P a g e
import mysql.connector
mydb =
mysql.connector.connect(host="localhost",user="root",password="root")
print("MySQL-Server-ConnectedSuccessfully")
Python MySQL Create Database:
To create a database in MySQL, use the "CREATE DATABASE" statement:
Example:
import mysql.connector
mydb =
mysql.connector.connect(host="localhost",user="root",password="root")
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE STUDENTS")
print("DataBaseCreatedSuccessfully")
NOTE:
A cursor is a temporary work area created in the system memory when a SQL
statement is executed. A cursor contains information on a select statement
and the rows of data accessed by it.
Check if Database Exists
Check if a database exist by listing all databases, by using the "SHOW
DATABASES" statement:
Example:
import mysql.connector
mydb =
mysql.connector.connect(host="localhost",user="root",passwd="root")
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for data in mycursor:
print(data)
48 | P a g e
To use particular database:
mysql> use student
OR
mysql> connect student
Python MySQL Create Table
Creating a Table
To create a table in MySQL, use the "CREATE TABLE" statement.
Example:
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root",passwd="root",
database='student')
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE Students (name VARCHAR(255), address
VARCHAR(255))")
print("Table Created Successfully")
mysql> show tables;
mysql> desc student;
Check if Table Exists
You can check if a database exist by listing all tables in your database by using
the "SHOW TABLES" statement:
Example:
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root",passwd="root",
database='student')
mycursor = mydb.cursor()
mycursor.execute("SHOW TABLES")
49 | P a g e
for data in mycursor:
print(data)
Python MySQL Insert Into Table
To fill a table in MySQL, use the "INSERT INTO" statement.
Example:
import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="root",
database='student')
mycursor=mydb.cursor()
mycursor.execute("insert into students values(1,'SARA')")
print("DataInsertedSuccessfully")
NOTE:
The above script executed successfully but data not saved in the table, that
time we must 'commit' the table..!!
Example:
import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="root",
database='std')
mycursor=mydb.cursor()
mycursor.execute("insert into emp values(1,'SARA')")
mydb.commit()
print("DataInsertedSuccessfully")
Insert Data in Multiple Rows
50 | P a g e
To insert multiple rows into a table, use the executemany() method.
Example:
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root",passwd="root",
database='student')
mycursor = mydb.cursor()
sql = "INSERT INTO students (name, address) VALUES (%s, %s)"
val = [
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345'),
('Sandy', 'Ocean blvd 2'),
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
]
mycursor.executemany(sql, val)
mydb.commit()
print("Data Inserted Successfully")
Python MySQL Select From:
To select from a table in MySQL, use the "SELECT" statement:
51 | P a g e
Select all records from the "students" table, and display the result:
Example:
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root",passwd="root",
database='student')
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM students")
for data in mycursor:
print(data)
4/4/2020
STEP1: Create Project
$django-admin startproject djModelProject
$cd djModelProject
STEP2:Create Application
$django-admin startapp WebApp
STEP3:$py manage.py runserver
STEP4:Open Project with PyCharm or Any IDE(ATOM, Visual Studio Code,
Sublime, Brackets..)
STEP5: Do required settings, App configuration @ Installed Apps, Template
configuration @ TEMPLATES, Static Configuration @ End of the settings.py.
STEP6: Configure in Database..!!
If You are using SQLITE3 No configurations required..!!
STEP7: models.py:
from django.db import models
# Create your models here.
class Emp(models.Model):
EmpId=models.IntegerField()
52 | P a g e
EmpName=models.CharField(max_length=30)
EmpSal=models.IntegerField()
EmpAdd=models.CharField(max_length=30)
NOTE:
This model class will be converted into Database table. Django is responsible
for that.
The above Emp model would create a db table as follows:
CREATE TABLE WebApp_Emp(
"id" serial NOT NULL PRIMARY KEY,
"EmpId" varchar(30) NOT NULL,
"EmpName" varchar(30) NOT NULL,
"EmpSal" varchar(30) NOT NULL,
"EmpAdd" varchar(30) NOT NULL
);
53 | P a g e
NOTE:
In the migrations folder 0001_initial.py existed, It contains all migrations
related to DB.
NOTE:
1 Table contains an auto-created id field.
2 The name of the table is a combination of app name and model name.
Syntax:
AppName_ClassName
Example:
WebApp_Emp
A Model Class is combinations of
1 Table Name 2 Fields 3 Datatypes
Table Name:WebApp_Emp
Fields: EmpId, EmpName, EmpSal and EmpAdd. And one extra field: id
Datatypes: EmpId is of type Integer, EmpName is of type Char and max_length
is 40 characters...!!
How to view SQL Code of Migrations?
$py manage.py sqlmigrate WebApp 0001
BEGIN;
Create model Emp
CREATE TABLE "WebApp_Emp" ("id" integer NOT NULL PRIMARY KEY AUTOIN
CREMENT, "EmpId" integer NOT NULL, "EmpName" varchar(40) NOT NULL,
"EmpSal" real NOT NULL, "EmpAdd" varchar(40) NOT NULL);
COMMIT;
6/4/2020
How to generate SQL Tables? (migrate Command):
54 | P a g e
After generating sql code, we have to execute that sql code to create table in
database. migrate creating several tables internally security, authentication,
admin, sessions, contenttypes related.
$ python manage.py migrate
Apply all migrations: admin, auth, contenttypes, sessions, WebApp
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_ email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying sessions.0001_initial... OK
Applying WebApp.0001_initial... OK
NOTE:
Migrate is responsible to execute SQL code, so that tables will be created in the
database.
What is Admin Interface?
The Admin interface of a website is the control panel of your website/ project.
It is used by the administrators of the website to add, delete and edit the
content on the site.
What is Django Admin/Superuser?
55 | P a g e
Django Admin is the preloaded interface made to fulfill all the needs of the
developers. Its language is quite generalized rather than technical. The Django
Admin is a fully featured interface and you won’t need to write an Admin
interface for your project now.
Setting Up Django Admin Site:
$ python manage.py createsuperuser
Start the server and login to admin interface using the created credentials.
User Name:KSRAJU
Email:[email protected]
Password:********
Password(Again):********
Super User Created Successfully..!!
$ python manage.py runserver
Provide created username and password to login. It displays Django
administration, It is a Django Admin Dashboard. But we can't see any Emp
table here, do the following..!!
http://127.0.0.1:8000/admin
Register Model Inside Admin Interface: (admin.py)
Method-I:
from django.contrib import admin
from WebApp.models import Emp
admin.site.register(Emp)
Adding
Users:
Click add ==>Add few records==>finally Click on SAVE..!!
NOTE:
If you configure the above admin.py every record show as Object..!
Method-II:
56 | P a g e
from django.contrib import admin
from WebApp.models import Emp
# Register your models here.
class EmpAdmin(admin.ModelAdmin):
list_display = ['EmpId','EmpName','EmpSal','EmpAdd']
admin.site.register(Emp,EmpAdmin)
NOTE:
Afer implementing admin.py, refresh the url. It show the Created Table.
Goto admin.py add 'id' column in the list and refresh the Admin Page.
'id' field in Models:
1) In Django Every Table, generate a special column "id". It is a PK
2) It is auto increment field.
3) We can override the behavior of "id" field
4) In Django Every Field is "NOT NULL" by default
7/4/2020
Jinja2 is a full featured template engine for Python. It has full unicode support,
an optional integrated sandboxed execution environment, widely used and
BSD licensed.
Jinja Features
1 Jinja is Beautiful
2 Jinja is Powerful
3 Sandboxed execution mode
4 Template inheritance
5 High performance
6 Configurable Syntax
57 | P a g e
LIVE EXAMPLE ON TEMPLATE ENGINE:
How to get data from the database and send to TEMPLATE.
STEP1:
$django-admin startproject TemplateProject
STEP2:
$django-admin startapp WebApp
STEP3:
Configure App,templates,static in settings.py, create
templates==>MyApp==>Welcome.html
STEP4:
Create static ==> CSS ==> MyFile.css
STEP5:Welcome.html:
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Template Language</title>
<link rel="stylesheet" href="{% static 'css/MyFile.css'%}">
</head>
<body>
<h1>EMPLOYEES LIST IS...!!</h1>
{% if elist %}
<table border="1px">
<thead>
<th>EMPID</th>
58 | P a g e
<th>EMPNAME</th>
<th>EMPSAL</th>
<th>EMPADD</th>
</thead>
{% for emp in elist %}
<tr>
<td>{{emp.EmpId}}</td>
<td>{{emp.EmpName}}</td>
<td>{{emp.EmpSal}}</td>
<td>{{emp.EmpAdd}}</td>
</tr>
{% endfor %}
</table>
{% else %}
<h2>Sorry No Records Found..!!</h2>
{% endif %}
</body>
</html>
STEP6:models.py
from django.db import models
# Create your models here.
class Emp(models.Model):
EmpId=models.IntegerField()
EmpName=models.CharField(max_length=30)
EmpSal=models.IntegerField()
EmpAdd=models.CharField(max_length=30)
59 | P a g e
STEP7:
$py manage.py makemigrations
$py manage.py migrate
STEP8:Creating Super User to login to admin Interface:
$ python manage.py createsuperuser
User Name:KSRAJU
Email:[email protected]
Password:********
Password(Again):********
SuperUser Created Successfully..!!
$ python manage.py runserver
http://127.0.0.1:8000/admin
Provide created username and password to login. It displays Django
administration, It is a Django Admin Dashboard. But we can't see any Emp
table here, do the following..!!
Register Model Inside Admin Interface: (admin.py)
STEP9:admin.py
from django.contrib import admin
from WebApp.models import Emp
# Register your models here.
class EmpAdmin(admin.ModelAdmin):
list_display = ['EmpId','EmpName','EmpSal','EmpAdd']
admin.site.register(Emp,EmpAdmin)
NOTE:
Afer implementing admin.py, refresh the url. It show the Created Emp Table.
Adding
Records..:
60 | P a g e
Click add ==>Add few records==>Click on SAVE..!!
Go to browser for sqlite, execute query
select * from WebApp_Emp;
STEP10:MyFile.css
body{
background-image:url(https://image.shutterstock.com/image-vector/jungle-
zoo-themed-animal-background-450w-1018271374.jpg);
background-repeat:no-repeat;
background-size:cover;
}
table{
margin:auto;background:yellow;
}
h1{
color:red;text-align:center;font-family:tahoma;
}
STEP11:views.py:
from django.shortcuts import render
from WebApp.models import Emp
# Create your views here.
def EmpView(request):
EmpList=Emp.objects.all()
My_Dict={'elist':EmpList}
return render(request,'MyApp/Welcome.html',My_Dict)
STEP12: urls.py
from django.contrib import admin
from django.urls import path
61 | P a g e
from WebApp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('Jinja/',views.EmpView),
]
STEP13:
Send the requst to web server: http://127.0.0.1:8000/Jinja
8/4/2020
WORKING WITH DJANGO FORMS:
What are Forms?
Forms are a collection of HTML elements to take input from the user. The input
elements come inside <form></form> tags.
It is a class which is used to create an HTML form by using the Model. It is an
efficient way to create a form without writing HTML code. Django
automatically does it for us to reduce the application development time.
Example:
login, registration, enquiry, feedback forms..!!
Advantages of Django Forms:
1)We can develop forms with python code
2)We can generate HTML Form widgets
3)Validating data is simple and easy
4)Processing data into python data structures like list, set.!
62 | P a g e
$cd djFormsProject
STEP2:Create Application
$django-admin startapp WebApp
STEP3:$py manage.py runserver
STEP4:Open Project with PyCharm or Any IDE(ATOM, Visual Studio Code,
Sublime, Brackets..)
STEP5: Do required settings, App configuration @ Installed Apps, Template
configuration @ TEMPLATES, Static Configuration @ End of the settings.py.
STEP6: Create inside the WebApp: forms.py
from django import forms
class EmpForm(forms.Form):
Name=forms.CharField()
Job=forms.CharField()
Loc=forms.CharField()
Salary=forms.FloatField()
NOTE:
Name,Job,Loc and Salary are the field names which are available in html form
like labels.
STEP-7: views.py:
from django.shortcuts import render
from WebApp import forms
# Create your views here.
def EmpView(request):
form=forms.EmpForm()
return render(request,'MyApp/Welcome.html',{'form':form})
NOTE:
views.py file is responsible to send this form to the template html file
63 | P a g e
STEP-8: Welcome.html
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Forms</title>
<link rel="stylesheet" href="{% static 'css/MyFile.css'%}">
</head>
<body>
{{ form }}
</body>
</html>
NOTE:
Inside template file we have to use template tag to inject form {{form}}. It will
add only form fields.
STEP9:MyFile.css
body{
background-image:url(https://image.shutterstock.com/image-vector/jungle-
zoo-themed-animal-background-450w-1018271374.jpg);
background-repeat:no-repeat;
background-size:cover;
}
STEP-10:urls.py
from django.contrib import admin
from django.urls import path
from WebApp import views
64 | P a g e
urlpatterns = [
path('admin/', admin.site.urls),
path('djforms/',views.EmpView),
]
Step11:
Send the request to Web Server. http://127.0.0.1:8000/djforms
Day-16 10/4/2020
65
EXAMPLE:
LIVE EXAMPLE ON FORMS WITH BOOTSTRAP CONTROLS:
STEP1: Create Project
$django-admin startproject Forms_Project
$cd Forms_Project
STEP2:Create Application
$django-admin startapp WebApp
STEP3:$py manage.py runserver
STEP4:Open Project with PyCharm or Any IDE(ATOM, Visual Studio Code,
Sublime, Brackets..)
STEP5: Do required settings, App configuration @ Installed Apps, Template
configuration @ TEMPLATES, Static Configuration @ End of the settings.py.
STEP6: forms.py
from django import forms
class EmpForm(forms.Form):
Name=forms.CharField()
Job=forms.CharField()
Loc=forms.CharField()
Salary=forms.FloatField()
65 | P a g e
STEP7: views.py:
from django.shortcuts import render
from WebApp import forms
# Create your views here.
def EmpView(request):
form=forms.EmpForm()
MyDict={'form':form}
return render(request,'MyApp/Welcome.html',MyDict)
STEP8: Welcome.html:
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Django Forms..!!</title>
<link rel="stylesheet" href="Copy Bootstrap CDN Link">
<link href="{% static 'css/MyFile.css' %}" rel="stylesheet">
</head>
<body>
<h1>Employee Sample Form..!!</h1>
<div class="container" align="center">
<form method="post">
{{ form.as_p }}
<input type="submit" value="Employee" class="btn btn-success">
</form>
</div>
66 | P a g e
</body>
</html>
Step9:MyFile.css
body{
background-image:url(https://image.shutterstock.com/image-vector/jungle-
zoo-themed-animal-background-450w-1018271374.jpg);
background-repeat:no-repeat;
background-size:cover;
}
h1{
color:red;text-align:center;font-family:candara;
}
Step:10 urls.py
from django.contrib import admin
from django.urls import path
from WebApp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('djforms/',views.EmpView),
]
Step:11 :
Send the request to Web Server. http://127.0.0.1:8000/djforms/
NOTE:
If method='post' not declared it never shows any Forbidden Error.
NOTE:
If we submit this form we will get 403 status code response Forbidden (403)
CSRF verification failed. Request aborted.
67 | P a g e
1 CSRF (Cross Site Request Forgery) token missing or incorrect.
2 Every form should satisfy CSRF Verification, otherwise Django won't accept
our form.
3 It is meant for website security.
4 But we have to add csrf_token in our form @ Template.
Go To Welcome.html:
<body>
<h1>Employee Sample Form..!!</h1>
<div class="container" align="center">
<form method="post">
{{ form.as_p }}
{% csrf_token %}
</form>
</div>
</body>
NOTE:
If we add csrf_token then in the generate form the following hidded field will
be added,which makes our post request secure.
Inspect Element(F12) & Observe the following:
<input type='hidden' name='csrfmiddlewaretoken'
value='1ZqIJJqTLMVa6RFAyPJh7pwzyFmdiHzytLxJIDzAkKULJz4qHcetLoKEsRLwy
z4h'/>
68 | P a g e
STEP2:Create Application
$django-admin startapp WebApp
STEP6: forms.py
from django import forms
class EmpForm(forms.Form):
Name=forms.CharField()
Salary=forms.IntegerField()
STEP7: views.py:
from django.shortcuts import render
from WebApp import forms
# Create your views here.
def EmpView(request):
form=forms.EmpForm()
if request.method=='POST':
form=forms.EmpForm(request.POST)
if form.is_valid():
69 | P a g e
print("Validations are Success Folks....!!")
print(form.cleaned_data['Name'])
print(form.cleaned_data['Salary'])
return render(request,'MyApp/Welcome.html',{'form':form})
STEP8: Welcome.html:
<!DOCTYPE html>
{%load static%}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Forms with Bootstrap Framework..!!</title>
<link rel="stylesheet" href="Copy CDN Link">
<link href="{% static 'css/MyFile.css'%}" rel="stylesheet">
</head>
<body>
<h2>Emp Registration Form..!!</h2>
<div class="container" align="center">
<form method="post">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" value="NewEmp" class="btn btn-success">
</form>
</div>
</body>
</html>
70 | P a g e
STEP9:MyFile.css
h2{
text-align:center;
}
body{
background-image:url(https://image.shutterstock.com/image-
vector/christmas-greeting-card-calligraphic-season-450w-1192564498.jpg);
background-repeat:no-repeat;
background-size:cover;
color:red;
}
h1{
color:purple;font-family:tahoma;font-size:30px;
text-align:center;
}
STEP:10 urls.py
from django.contrib import admin
from django.urls import path
from WebApp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('Regis/',views.EmpView),
]
STEP11:
71 | P a g e
Send the request to the django web server: http://127.0.0.1:8000/Regis/
NOTE:
If you click the button all entered details displayed @ command prompt..!!
Step1:Thanks.html
<!DOCTYPE html>
{%load static%}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Thanks for Click Me...!!</title>
<bootstrap>
<link href="{% static 'css/MyFile.css'%}" rel="stylesheet">
</head>
<body>
<h1>Hey! Thank You for Submit the Form...!!</h1>
<h1>Good Bye....!!</h1>
</body>
</html>
Step2: views.py:
from django.shortcuts import render
from WebApp import forms
72 | P a g e
from django.http import HttpResponseRedirect
# Create your views here.
def EmpView(request):
if request.method=='POST':
form=forms.EmpForm(request.POST)
if form.is_valid():
print("Welcome to Validations")
print(form.cleaned_data['Name'])
print(form.cleaned_data['Salary'])
return HttpResponseRedirect('/Thanks')
else:
form = forms.EmpForm()
return render(request,'MyApp/Welcome.html', {'form': form})
def ThankView(request):
return render(request,'MyApp/Thanks.html')
Step3:urls.py:
from django.contrib import admin
from django.urls import path
from WebApp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('Regis/',views.EmpView),
path('Thanks/',views.ThankView),
73 | P a g e
]
NOTE:
Usage of built in validators is very easy when compared with clean methods.
NOTE:
Validation are successfully run if form method="POST"
STEP1:
$django-admin startproject djformsBuiltinValidate
$cd djformsBuiltinValidate
$django-admin startapp WebApp
STEP2:
74 | P a g e
Do required settings in settings.py file, like templates, static, images ...!!
STEP3:Register.html
<!DOCTYPE html>
{%load static%}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>djForms with Builtin Validations..!!</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.c
ss" integrity="sha384-
BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4
u" crossorigin="anonymous">
<link href="{% static 'css/MyFile.css'%}" rel="stylesheet">
</head>
<body>
<h2>Emp Registration Form..!!</h2>
<div class="container" align="center">
<form method="post">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" value="NewEmp" class="btn btn-success">
</form>
</div>
</body>
</html>
75 | P a g e
STEP4:Thanks.html
<!DOCTYPE html>
{%load staticfiles%}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Thank for Click Me...!!</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.c
ss" integrity="sha384-
BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4
u" crossorigin="anonymous">
<link href="{% static 'css/MyFile.css'%}" rel="stylesheet">
</head>
<body>
<h1>Hello Thanks for Validations...!</h1>
<h1>Good Bye....!!</h1>
</body>
</html>
STEP5:views.py
from django.shortcuts import render
from WebApp import forms
from django.http import HttpResponseRedirect
76 | P a g e
def ThankView(request):
return rder(request,'MyApp/Thanks.html')
def EmpView(request):
if request.method=='POST':
form=forms.EmpForm(request.POST)
if form.is_valid():
print("Welcome to Validations")
print(form.cleaned_data['Name'])
print(form.cleaned_data['Salary'])
print(form.cleaned_data['Opinion'])
return HttpResponseRedirect('/Bye')
else:
form = forms.EmpForm()
return render(request,'MyApp/Register.html', {'form': form})
STEP6: forms.py:
from django import forms
from django.core import validators
#Customized Forms
class EmpForm(forms.Form):
Name=forms.CharField()
Salary=forms.IntegerField()
Opinion=forms.CharField(widget=forms.Textarea,validators=[validators.MaxLe
ngthValidator(40),validators.MinLengthValidator(10)])
77 | P a g e
STEP7:MyFile.css
h2{
text-align:center;
}
body{
background-image:url(https://image.shutterstock.com/image-
vector/christmas-greeting-card-calligraphic-season-450w-1192564498.jpg);
background-repeat:no-repeat;
background-size:cover;
color:red;
}
h1{
color:purple;font-family:tahoma;font-size:30px;
text-align:center;
}
STEP8:urls.py
from django.contrib import admin
from django.urls import path
from WebApp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('validate/',views.EmpView),
path('Bye/', views.ThankView),
]
78 | P a g e