0% found this document useful (0 votes)
165 views243 pages

Django Ppts

Uploaded by

mishravaibhav570
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
165 views243 pages

Django Ppts

Uploaded by

mishravaibhav570
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 243

Unit I Content

• Collections-Container datatypes,
• Tkinter-GUI applications,
• Requests-HTTP requests,
• BeautifulSoup4-web scraping,
• Scrapy, Zappa, Dash, CherryPy, TurboGears,
• Flask, Web2Py,
• Bottle, Falcon, CubicWeb, Quixote, Pyramid.

9/13/23 Priya Singh Python web development with Django Unit I 26


Counter container
A Counter is a container that keeps track of how many times equivalent
values are added. It can be used to implement the same algorithms for
which bag or multiset data structures are commonly used in other
languages.
Initializing:
Counter supports three forms of initialization. Its constructor can be called
with a sequence of items, a dictionary containing keys and counts, or using
keyword arguments mapping string names to counts.
import collections
print collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
print collections.Counter({'a':2, 'b':3, 'c':1})
print collections.Counter(a=2, b=3, c=1)
The results of all three forms of initialization are the same.
9/13/23
Priya Singh Python web development with Django Unit I
29
Defaultdict

The standard dictionary includes the method setdefault() for retrieving a


value and establishing a default if the
value does not exist. By contrast, defaultdict lets the caller specify the
default up front when the container initialized.
import collections
def default_factory():
return 'default value'
d = collections.defaultdict(default_factory, foo='bar')
print 'd:', d
print 'foo =>', d['foo']
print 'bar =>', d['bar']
This works well as long as it is appropriate for all keys to have the same
default.
9/13/23
Priya Singh Python web development with Django Unit I
30
Deque
A double-ended queue, or deque, supports adding and removing
elements from either end. The more commonly used stacks and queues
are degenerate forms of deques, where the inputs and outputs are
restricted to a single end.
import collections
d = collections.deque('abcdefg')
print 'Deque:', d
print 'Length:', len(d)
print 'Left end:', d[0]
print 'Right end:', d[-1]
d.remove('c')print 'remove(c):', d
9/13/23 Priya Singh Python web development with Django Unit I 31
Deque

Since deques are a type of sequence container, they support some of


the same operations that lists support, such as examining the contents
with __getitem__(), determining length, and removing elements from
the middle by matching identity.
$ python collections_deque.py
Deque: deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
Length: 7
Left end: a
Right end: g
remove(c): deque(['a', 'b', 'd', 'e', 'f', 'g'])

9/13/23 Priya Singh Python web development with Django Unit I 32


Ordered Dict
An OrderedDict is a dictionary subclass that remembers the order in
which its contents are added.
import collections
print 'Regular dictionary:‘
A regular dict does not track the insertion order, and iterating over it
produces the values in an arbitrary order. In an OrderedDict, by
contrast, the order the items are inserted is remembered and used
when creating an iterator.
$ python collections_ordereddict_iter.py
Regular dictionary:a Ac Cb Be Ed D
OrderedDict:a Ab Bc Cd De E

9/13/23 Priya Singh Python web development with Django Unit I 33


OrderedDict(continues….)

A regular dict does not track the insertion order, and


iterating over it produces the values in an arbitrary order.
In an OrderedDict, by contrast, the order the items are
inserted is remembered and used when creating an
iterator.
$ python collections_ordereddict_iter.py
Regular dictionary:
aA cC bB eE dD
OrderedDict: a A b B cC dD eE

9/13/23 Priya Singh Python web development with Django Unit I 34


Python - GUI Programming (Tkinter)
Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with
Python. We would look this option in this chapter.
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with
Tkinter provides a fast and easy way to create GUI applications. Tkinter provides
a powerful object-oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is
perform the following steps −
Import the Tkinter module.
Create the GUI application main window.
Add one or more of the above-mentioned widgets to the GUI application.
Enter the main event loop to take action against each event triggered by user.
9/13/23 Priya Singh Python web development with Django Unit I 35
Python - GUI Programming (Tkinter)(continue….)
Example
#!/usr/bin/pythonimport Tkintertop = Tkinter.Tk()# Code to add
widgets will go here...top.mainloop()
This would create a following window –

commonly called widgets.


There are currently 15 types of widgets in Tkinter. We present these
widgets as well as a brief description in the following table −
Sr.No. Operator & Description
1 Button
The Button widget is used to display buttons in your application.
2 Canvas
The Canvas widget is used to draw shapes, such as lines, ovals,
polygons and rectangles, in your application.

9/13/23 Priya Singh Python web development with Django Unit I 36


Python - GUI Programming (Tkinter)(continue….)
Checkbutton
3 The Checkbutton widget is used to display a number of options as checkboxes. The user
can select multiple options at a time.
Entry -----The Entry widget is used to display a single-line text field for accepting values
4
from a user.

5 Frame ----The Frame widget is used as a container widget to organize other widgets.

Label
6 The Label widget is used to provide a single-line caption for other widgets. It can also
contain images.

7 Listbox --- The Listbox widget is used to provide a list of options to a user.

9/13/23 Priya Singh Python web development with Django Unit I 37


Python - GUI Programming (Tkinter)(continue….)

Geometry Management

All Tkinter widgets have access to specific geometry management methods,


which have the purpose of organizing widgets throughout the parent widget area.
Tkinter exposes the following geometry manager classes: pack, grid, and place.
•The pack() Method − This geometry manager organizes widgets in blocks before
placing them in the parent widget.
•The grid() Method − This geometry manager organizes widgets in a table-like
structure in the parent widget.
•The place() Method − This geometry manager organizes widgets by placing them
in a specific position in the parent widget.

9/13/23 Priya Singh Python web development with Django Unit I 38


HTTP - Requests
GET and POST requests using Python
This post discusses two HTTP (Hypertext Transfer Protocol) request methods GET and
POST requests in Python and their implementation in python.
What is HTTP
HTTP is a set of protocols designed to enable communication between clients and
servers. It works as a request-response protocol between a client and server.
A web browser may be the client, and an application on a computer that hosts a
website may be the server.
So, to request a response from the server, there are mainly two methods:
1.GET : to request data from the server.
2.POST : to submit data to be processed to the server.

9/13/23 Priya Singh Python web development with Django Unit I 39


HTTP – Requests(continue…)
Here is a simple diagram which explains the basic concept of GET and POST methods.

9/13/23 Priya Singh Python web development with Django Unit I 40


HTTP – Requests(continue…)
Now, to make HTTP requests in python, we can use several HTTP libraries like:
Httplib urllib requests

The most elegant and simplest of above listed libraries is Requests. We will be using requests
library in this article. To download and install Requests library, use following command:
pip install requests

Here are some important points to ponder upon:


When the method is GET, all form data is encoded into the URL, appended to the action URL as
query string parameters. With POST, form data appears within the message body of the HTTP
request.
In GET method, the parameter data is limited to what we can stuff into the request line (URL).
Safest to use less than 2K of parameters, some servers handle up to 64K.No such problem in
POST method since we send data in message body of the HTTP request, not the URL.
9/13/23 Priya Singh Python web development with Django Unit I 41
HTTP – Requests(continue…)

•Only ASCII characters are allowed for data to be sent in GET


method.There is no such restriction in POST method.
•GET is less secure compared to POST because data sent is part of the
URL. So, GET method should not be used when sending passwords or
other sensitive information.

Beautiful Soup 4-web scraping


Beautiful Soup is a library that makes it easy to scrape information
from web pages. It sits atop an HTML or XML parser, providing
Pythonic idioms for iterating, searching, and modifying the parse tree.

9/13/23 Priya Singh Python web development with Django Unit I 42


Beautiful Soup 4-web scraping

Scrapy is a Python framework for large scale web scraping. It gives you all the tools
you need to efficiently extract data from websites, process them as you want, and
store them in your preferred structure and format.
As diverse the internet is, there is no “one size fits all” approach in extracting data
from websites. Many a time ad hoc approaches are taken and if you start writing
code for every little task you perform, you will eventually end up creating your own
scraping framework. Scrapy is that framework.
With Scrapy you don’t need to reinvent the wheel.

2. Write your first Web Scraping code with Scrapy


We will first quickly take a look at how to setup your system for web scraping and
then see how we can build a simple web scraping system for extracting data from
Reddit website.

9/13/23 Priya Singh Python web development with Django Unit I 43


Zappa
Zappa is a way to deploy serverless web apps on AWS Lambda.
Zappa is a very powerful open source python project which lets you build, deploy
and update your WSGI app hosted on AWS Lambda + API Gateway easily.
Zappa is a Python package that bundles up web apps written in Flask or Django and
deploys them to AWS (Amazon Web Services) Lambda.
Lambda is Amazon's function as a service (FaaS) platorm. Why is Zappa so great?
Because instead of deploying your Flask or Django web app on a cloud server, like an
AWS EC2 instance or a Digital Ocean Droplet, you can deploy your app serverless as an
AWS Lambda function.

This isn't really "serverless" (servers run AWS Lambda), but with an AWS Lambda
function, you don't have to spin up servers, install packages, make sure security
patches are up to date, and most of all: you don't have to pay for server time that
isn't used.
A cloud server has to run all the time, whether or not someone visits your website. But
an AWS Lambda function only runs when requested.

9/13/23 Priya Singh Python web development with Django Unit I 44


Install Zappa and Flask

• Before we can deploy our web app on AWS Lambda with Zappa, first
we need to install Zappa and a web framework to build our web app
with. In this project, we are going to build a Flask app, so Flask needs
to be installed too. You can install both of these packages with pip, the
Python package manager.
• Using a terminal, create a project directory called zappa_app and cd
into it. Create a virtual environment, activate it, and install Zappa and
Flask.
• mkdir zappa_appcd zappa_apppython -m venv venvsource
venv/bin/activate# on windows: venv\Scripts\activatepip install
flaskpip install zappa You can verify the installation by calling two help
commands at the terminal.
• flask --helpzappa --help

9/13/23 Priya Singh Python web development with Django Unit I 45


A Simple Flask App

Next, we'll build a simple web app with Flask. This web app is super small and basic,
but it will give you an idea of how Zappa and AWS Lambda works.
Create a file called app.py in the main project directory zappa_app we created
earlier. Inside app.py, paste the following code. This super simple Flask app creates
one webpage that displays the text Yeah, that is Zappa! Zappa! Zap! Zap!. You can
modify the text between the <h1> .... </h1> tags to include any message you want.
Copy the code below into app.py.
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return '<h1>Yeah, that is Zappa! Zappa! Zap! Zap!</h1>' # We only need this for
local development.if __name__ == '__main__': app.run()
9/13/23 Priya Singh Python web development with Django Unit I 46
Zappa (continue….)

9/13/23 Priya Singh Python web development with Django Unit I 47


Dash Framework
§Dash is an open-source Python framework used for building analytical web applications. It is a
powerful library that simplifies the development of data-driven applications. It’s especially
useful for Python data scientists who aren’t very familiar with web development. Users can
create amazing dashboards in their browser using dash.
§Built on top of Plotly.js, React, and Flask, Dash ties modern UI elements like dropdowns, sliders
and graphs directly to your analytical python code.
§Dash apps consist of a Flask server that communicates with front-end React components using
JSON packets over HTTP requests.
§Dash applications are written purely in python, so NO HTML or JavaScript is necessary.

Dash Setup
If Dash is not already installed in your terminal, then install the below mentioned Dash libraries.
As these libraries are under active development, install and upgrade then frequently. Python 2
and 3 are also supported.
pip install dash==0.23.1 # The core dash backend
pip install dash-renderer==0.13.0 # The dash front-end

9/13/23 Priya Singh Python web development with Django Unit I 48


Dash Setup(continue….)

Dash or App Layout


Dash apps are composed of two parts. The first part is the “layout” of the app
which basically describes how the application looks like. The second part
describes the interactivity of the application.
Core Components
We can build the layout with the dash_html_components and the
dash_core_components library. Dash provides python classes for all the visual
components of the application. We can also customize our own components with
JavaScript and React.js.
import dash_core_components as dcc
import dash_html_components as html
The dash_html_components is for all HTML tags where the
dash_core_components is for interactivity built with React.js.

9/13/23 Priya Singh Python web development with Django Unit I 49


Dash or App Layout(continue…)

Writing Simple Dash app


We will learn how to write a simple example on dash using above mentioned library
in a file dashApp.py.
# -*- coding: utf-8 -*-import dashimport dash_core_components as dccimport
dash_html_components as html app = dash.Dash()app.layout = html.Div(children=[
html.H1(children='Hello Dash'), html.Div(children='''Dash Framework: A web
application framework for Python.'''), dcc.Graph( id='example-graph',
figure={ 'data': [ {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Delhi'},
{'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Mumbai'}, ], 'layout': {
'title': 'Dash Data Visualization' } } )]) if __name__ == '__main__':
app.run_server(debug=True)

9/13/23 Priya Singh Python web development with Django Unit I 50


Dash or App Layout(continue…)
Writing Simple Dash app
We will learn how to write a simple example on dash using above mentioned library in a file
dashApp.py
-import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children='''Dash
Framework: A web application framework for Python.'''), dcc.Graph( id='example-
graph',
figure={ 'data': [ {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Delhi'}, {'x':
[1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Mumbai'}, ], 'layout': { 'title': 'Dash
Data Visualization' } } )])
if __name__ == '__main__':

9/13/23 Priya Singh Python web development with Django Unit I 51


Running the Dash app
Note the following points while running the Dash app.
(MyDjangoEnv) C:\Users\rajesh\Desktop\MyDjango\dash>python dashApp1.py

•Serving Flask app "dashApp1" (lazy loading)


•Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
•Debug mode: on
•Restarting with stat
•Debugger is active!
•Debugger PIN: 130-303-947
•Running on http://127.0.0.1:8050/ (Press CTRL+C to quit)

9/13/23 Priya Singh Python web development with Django Unit I 52


Running the Dash app

9/13/23 Priya Singh Python web development with Django Unit I 53


Running the Dash app
• In above program, few important points to be noted are as follows −
• The app layout is composed of a tree of “components” like html.Div and
dcc.Graph.
• The dash_html_components library has a component for every HTML tag. The
html.H1 (children = ‘Hello Dash’) component generates a <h1> Hello Dash
</h1> HTML element in your application.
• Not all components are pure HTML. The dash_core_components describe
higher-level components that are interactive and are generated with
JavaScript, HTML, and CSS through the React.js library.
• Each component is described entirely through keyword attributes. Dash is
declarative: you will primarily describe your application through these
attributes.

9/13/23 Priya Singh Python web development with Django


54
Unit I
CherryPy
• CherryPy allows developers to build web applications in much the same way
they would build any other object-oriented Python program.

• This results in smaller source code developed in less time. It is being used in
many production websites.
• CherryPy is a web framework of Python which provides a friendly interface to
the HTTP protocol for Python developers.
• It is also called a web application library.

• CherryPy uses Python’s strengths as a dynamic language to model and bind


HTTP protocol into an API.

• It is one of the oldest web frameworks for Python, which provides clean
interface and reliable platform.
9/13/23 Priya Singh Python web development with Django Unit I 55
CherryPy (continue….)

Strengths of CherryPy
The following features of CherryPy are considered as its strengths −
Simplicity
Developing a project in CherryPy is a simple task with few lines of code developed as per the
conventions and indentations of Python.
CherryPy is also very modular. The primary components are well managed with correct logic
concept and parent classes are expandable to child classes.
Power
CherryPy leverages all the power of Python. It also provides tools and plugins, which are
powerful extension points needed to develop world-class applications.
Open-source
CherryPy is an open-source Python Web Framework (licensed under the open-source BSD
license), which means this framework can be used commercially at ZERO cost.

9/13/23 Priya Singh Python web development with Django Unit I 56


CherryPy (continue….)

Community Help
It has a devoted community which provides complete support with various types of
questions and answers. The community tries to give complete assistance to the
developers starting from the beginner level to the advanced level.
Deployment
There are cost effective ways to deploy the application. CherryPy includes its own
production-ready HTTP server to host your application. CherryPy can also be
deployed on any WSGI-compliant gateway.
CherryPy comes in packages like most open-source projects, which can be
downloaded and installed in various ways which are mentioned as follows −
•Using a Tarball
•Using easy_install
•Using Subversion

9/13/23 57
Priya Singh Python web development with Django Unit I
Turbo Gears
TurboGears is a Python web application framework, which consists of many
modules. It is designed around the MVC architecture that are similar to Ruby on
Rails or Struts. TurboGears are designed to make rapid web application
development in Python easier and more supportable.
TurboGears is a web application framework written in Python.
TurboGears follows the Model-View-Controller paradigm as do most modern web
frameworks like Rails, Django, Struts, etc. This is an elementary tutorial that covers
all the basics of TurboGears.
TurboGears is a web application framework written in Python. Originally created by
Kevin Dangoor in 2005, its latest version TurboGears (ver 2.3.7) is managed by a
group of developers led by Mark Ramm and Florent Aide.
TurboGears follows the Model-View-Controller paradigm as do most modern web
frameworks like Rails, Django, Struts, etc.

9/13/23 Priya Singh Python web development with Django Unit I 58


Turbo Gears (continue….)
Follow the above mentioned command to serve a pre-built example project. Open
http://localhost:8080 in browser. This readymade sample application gives a brief
introduction about Turbo Gears framework itself.

9/13/23 Priya Singh Python web development with Django Unit I 59


Flask

• Flask is a web application framework written in Python.


• Armin Ronacher, who leads an international group of Python enthusiasts
named Pocco, develops it.
• Flask is based on Werkzeug WSGI toolkit and Jinja2 template engine. Both are
Pocco projects.
• Flask is often referred to as a micro framework.
• It aims to keep the core of an application simple yet extensible.
• Flask does not have built-in abstraction layer for database handling, nor does it
have form a validation support.
• Instead, Flask supports the extensions to add such functionality to the
application.
• Importing flask module in the project is mandatory. An object of Flask class is
our WSGI application

9/13/23 Priya Singh Python web development with Django Unit I 60


Flask(continue….)
.Flask constructor takes the name of current module (__name__) as argument.
The route() function of the Flask class is a decorator, which tells the application which
URL should call the associated function.
app.route(rule, options)
•The rule parameter represents URL binding with the function.
•The options is a list of parameters to be forwarded to the underlying Rule object.
In the above example, ‘/’ URL is bound with hello_world() function. Hence, when the
home page of web server is opened in browser, the output of this function will be
rendered.
Finally the run() method of Flask class runs the application on the local development
server.
app.run(host, port, debug, options)

9/13/23 Priya Singh Python web development with Django Unit I 61


Flask(continue….)
Debug mode
• A Flask application is started by calling the run() method.
• However, while the application is under development, it should be restarted
manually for each change in the code. To avoid this inconvenience, enable debug
support.
• The server will then reload itself if the code changes. It will also provide a useful
debugger to track the errors if any, in the application.
• Modern web frameworks use the routing technique to help a user remember
application URLs. It is useful to access the desired page directly without having to
navigate from the home page.
• The route() decorator in Flask is used to bind URL to a function. For example −
• @app.route(‘/hello’)def hello_world():
• return ‘hello world’

9/13/23 Priya Singh Python web development with Django Unit I 62


Flask(continue….)

• Here, URL ‘/hello’ rule is bound to the hello_world() function.

• As a result, if a user visits http://localhost:5000/hello URL, the output of


the hello_world() function will be rendered in the browser.

• The add_url_rule() function of an application object is also available to bind


a URL with a function as in the above example, route() is used.

• A decorator’s purpose is also served by the following representation −


• def hello_world():
• return ‘hello world’
• app.add_url_rule(‘/’, ‘hello’, hello_world)

9/13/23 Priya Singh Python web development with Django Unit I 63


Web2py

• web2py is defined as a free, open-source web framework for agile development


which involves database-driven web applications. It is written and
programmable in Python. It is a full-stack framework and consists of all the
necessary components a developer needs to build fully functional web
applications.
• web2py is defined as a free, open-source web framework for agile development
which involves database-driven web applications; it is written in Python and
programmable in Python. It is a full-stack framework; it consists of all the
necessary components, a developer needs to build a fully functional web
application.
• web2py framework follows the Model-View-Controller pattern of running web
applications unlike traditional patterns.

9/13/23 Priya Singh Python web development with Django Unit I 64


Web2py (continue…)

web2py has an in-built feature to manage cookies and sessions. After


committing a transaction (in terms of SQL), the session is also stored
simultaneously.
web2py has the capacity of running the tasks in scheduled intervals after
the completion of certain actions. This can be achieved with CRON.

Priya Singh Python web development with Django


9/13/23 65
Unit I
Bottle

• Bottle is a fast, simple and lightweight WSGI micro web-framework for


Python. It is distributed as a single file module. There are no dependencies
other than the Python Standard Library.
• The Web Server Gateway Interface (WSGI) is a simple calling convention for
web servers to forward requests to web applications or frameworks written in
the Python programming language.
• Bottle installation
• $ sudo pip3 install bottle
• We use the pip3 tool to install Bottle.

Priya Singh Python web development with Django


9/13/23 66
Unit I
Falcon
• Falcon is a WSGI-compliant web framework designed to build RESTful
APIs without requiring external code library dependencies.
• Falcon resources
• Building Very Fast App Backends with Falcon Web Framework on PyPy
provides a walkthrough of a web API in Falcon that runs with PyPy and
Nginx.
• Asynchronous Tasks with Falcon and Celery shows how to configure
Celery with the framework.
• The official Falcon tutorial has a meaty guide for building and deploying
your first Falcon web application.
• Building Scalable RESTful APIs with Falcon and PyPy shows a to-do list
example with Falcon running on PyPy.

Priya Singh Python web development with Django


9/13/23 67
Unit I
Cubic Web
• CubicWeb is an open-source Python Web framework . It promotes reusability through
the usage of components (called cubes).
• CubicWeb is well-defined Python semantic web application framework that focuses on
quality, reusability and efficiency of the development solution.
• CubicWeb stands out among other Python web frameworks and is not easy to learn. It
positions itself as semantic web development framework and gives developers
opportunity to build web applications by following the well known object-oriented
design principles and reusing components called cubes.
• Cube is the core concept of the CubicWeb. Basically it is a minimal web application - a
software component that consists of three main parts: data model (schema), the logic
(entities) needed to manipulate that data, and user interface (views) that displays the
data.

Priya Singh Python web development with Django


9/13/23 68
Unit I
Cubic Web(continue…)
How CubicWeb works
• This development tool is written in Python and includes a web engine and a data
server. The web engine replies to http requests and provides a CRUD user interface
based on the data model of the instance. The data server publishes data gathered
from data repositories. Although app construction is data-driven, CubicWeb is not just
a database Web-client construction set.

• CubicWeb contains data repository that enables access to one or more data sources
such as SQL databases, LDAP repositories, filesystems, Google App Engine’s DataStore,
and even other CubicWeb instance repositories. A data repository can be configured
to either be accessed remotely using Pyro (Python Remote Objects) or act as a
standalone server, that in turn can be accessed either via a standalone web engine or
directly. Usually the web engine and the repository are run in the same process.

Priya Singh Python web development with Django


9/13/23 69
Unit I
Quixote
• Quixote is a framework for writing Web-based applications using Python. Its
goals are flexibility and high-performance, in that order. Quixote applications
tend to be structured like traditional applications. The logic for formatting web
pages consists of Python classes and functions. Separation of presentation logic
and "back-end" logic is not enforced by Quixote. Instead, you are encouraged to
use traditional techniques. For example, a solution is to put presentation logic in
its own sub-package.
• There are three major versions of Quixote, version 1, 2 and 3. Versions 1 and 2
are similar to each other but incompatible. Version 1 is no longer actively
maintained. Version 3 of Quixote requires Python 3 but is otherwise similar to
Quixote 2. Versions 2 and 3 of Quixote are actively maintained and are used by
numerous public sites.

Priya Singh Python web development with Django


9/13/23 70
Unit I
Quixote(continue….)

• Download
• The latest stable version of Quixote (Python 3 only) is version 3.5 (3.4 sig),
released 2021-06-12.
• The version of the 2.x series (Python 2 compatible) is version 2.9.1 (2.9.1 sig),
released 2016-04-18.
• The latest version of the 1.x series is Quixote is version 1.3, released 2008-
08-21.
• The latest test version of Quixote is version 3.6a2 (3.6a2 sig), released 2021-
12-20

Priya Singh Python web development with Django


9/13/23 71
Unit I
Pyramid
• Pyramid makes it easy to write web applications. You can start small with this
"hello world" minimal request/response web app.

• This may take you far, especially while learning. As your application grows,
Pyramid offers many features that make writing complex software take less
effort.

• Pyramid works in all supported versions of Python.

• Pyramid is a general, open source, web application development framework


built in python. It allows python developer to create web applications with ease.

Priya Singh Python web development with Django


9/13/23 72
Unit I
Pyramid(continue….)
• Installing, starting up and configuring
• As described, “the start small, finish big, stay finished framework”, Pyramid is
much like Flask which takes very little effort to install and run. In fact, you’ll
recognize that some of the patterns are similar to Flask once you start building
this application.
• Following are the steps to create pyramid framework environment −
• First, create a project directory. Here, we have created a directory named
pyramidProject (you can choose any name you want).
• Next, create a virtual environment where you will install all the project specific
dependencies. Here, we created a virtual environment folder named
pyramidEnv where Pyramid is installed.
• Then, go to the directory, pyramidEnv and install the pyramid with pip install
pyramid.

Priya Singh Python web development with Django


9/13/23 73
Unit I
Daily Quiz

1. Discuss collection container datatypes.


2. What is the role of frameworks in python.
3. Discuss any three frameworks.
4. Discuss about Turbogear.
5. Discuss implementation rule of Falcon.
6. Discuss the Zappa framework.
7. Discuss the role of Dash.
8. Discuss the application area of cherryPy.
9. Discuss about the Request Http methods in Python.
10. Discuss about Flask application.

Priya Singh Python web development with Django Unit I


9/13/23 74
Weekly Assignment

1. What are the most important uses of Django.


2. What are the disadvantages of Django?
3. What are the different data types used in Django.
4. What are the salient features of Django.
5. What are some of the technical features that Django includes

9/13/23 Priya Singh Python web development with Django Unit I 75


Topic Link ( YouTube & NPTEL Video Links)

YouTube /other Video Links


• https://youtu.be/eoPsX7MKfe8?list=PLIdgECt554OVFKXRpo_kuI0XpUQKk0ycO

• https://youtu.be/tA42nHmmEKw?list=PLh2mXjKcTPSACrQxPM2_1Ojus5HX88ht7

• https://youtu.be/8ndsDXohLMQ?list=PLDsnL5pk7-N_9oy2RN4A65Z-PEnvtc7rf

• https://youtu.be/QXeEoD0pB3E?list=PLsyeobzWxl7poL9JTVyndKe62ieoN-MZ3

• https://youtu.be/9MmC_uGjBsM?list=PL3pGy4HtqwD02GVgM96-V0sq4_DSinqvf

9/13/23 Priya Singh Python web development with Django Unit I 76


MCQ s
1. What is a Django App? 2. Django was introduced by
ADjango app is an extended package with base package
is Django A. Adrian Holovaty
B. Django app is a python package with its own B. Bill Gates
components. C. Rasmus Lerdorf
C. Both 1 & 2 Option D. Tim Berners-Lee
D. All of the above
3. What are Migrations in Django
A. They are files saved in migrations directory.
B. They are created when you run make migrations
command.
C. Migrations are files where Django stores changes to
your models.
D. All of the above
4. Which architectural pattern does django follow
APHP
B. MVT
C. HTML Priya Singh Python web development with Django Unit I
9/13/23 77
D. None of the above
MCQ s

which of these is not a valid backend for caching in django


A. Django.core.cache.backends.sys.memory
B. django.core.cache.backends.db.DatabaseCache
C. django.core.cache.backends.locmem.LocMemCache
D. None of the above
5. Which architectural pattern does django follow
A.PHP
B. MVT
C. HTML
D. None of the above

Priya Singh Python web development with Django


9/13/23 78
Unit I
MCQ s
6. Python is a : 7. Python is Case Sensitive when dealing with
§Development environment Identifiers?
§Set of editing tools §Yes
§Programming Language §No
§Sometimes Only
§None Of the Above

8. What is the OUTPUT of the following Statement? 9. What is the OUTPUT when the following
print 0xA + 0xB + 0xC : Statement is executed?
§0xA0xB0xC “abc”+”xyz”
§33 §abc
§ABC §abcxyz
§000XXXABC §abcz
§abcxy

10.what is the type of a? a={1,2:3} list


set
dict Priya Singh Python web development with Django Unit I
9/13/23 79
syntax error
Glossary Questions
Top 10 design pattern interview questions

1. Explain Django Architecture?


2. Explain the Django project directory structure?
3. What are models in Django?
4. What are templates in Django or Django template language?
5. What are views in Django?
6. What is Django ORM?
7. What is Django Rest Framework(DRF)?
8. What is the difference between a project and an app in Django?
9. What are different model inheritance styles in the Django?
10.What are Django Signals?
9/13/23 Priya Singh Python web development with Django Unit I 80
Expected Questions for University Exam
Top 10 design pattern interview questions

1. Explain Django Architecture?


2. Explain the Django project directory structure?
3. What are models in Django?
4. What are templates in Django or Django template language?
5. What are views in Django?
6. What is Django ORM?
7. What is Django Rest Framework(DRF)?
8. What is the difference between a project and an app in Django?
9. What are different model inheritance styles in the Django?
10.What are Django Signals?
9/13/23 Priya Singh Python web development with Django Unit I 81
Understanding Django environment(continue…)

Step 2 - Installing Django


Installing Django is very easy, but the steps required for its installation depends on your operating system. Since Python
is a platform-independent language, Django has one package that works everywhere regardless of your operating
system.
You can download the latest version of Django from the link http://www.djangoproject.com/download.
You can test your installation by running this command −
$ django-admin.py --version
If you see the current version of Django printed on the screen, then everything is set.
Note − For some version of Django it will be django-admin the ".py" is removed.

Priya Singh Python web development with Django Unit II


9/11/2023 28
Understanding Django environment(continue…)

Windows Installation
We assume you have your Django archive and python installed on your computer.
First, PATH verification.
On some version of windows (windows 7) you might need to make sure the Path system variable has the path
the following
C:\Python34\;C:\Python34\Lib\site-packages\django\bin\ in it, of course depending on your Python version.
Then, extract and install Django.
c:\>cd c:\Django-x.xx
Next, install Django by running the following command for which you will need administrative privileges in
windows shell "cmd" −
c:\Django-x.xx>python setup.py install

Priya Singh Python web development with Django Unit II


9/11/2023 29
Understanding Django environment(continue…)

To test your installation, open a command prompt and type the following command −
c:\>python -c "import django; print(django.get_version())"
If you see the current version of Django printed on screen, then everything is set.
OR
Launch a "cmd" prompt and type python then −
c:\> python >>> import django >>> django.VERSION
Step 3 – Database Setup
Django supports several major database engines and you can set up any of them based on your comfort.
MySQL (http://www.mysql.com/)
PostgreSQL (http://www.postgresql.org/)
SQLite 3 (http://www.sqlite.org/)
Oracle (http://www.oracle.com/)
MongoDb (https://django-mongodb-engine.readthedocs.org)
GoogleAppEngine Datastore (https://cloud.google.com/appengine/articles/django-nonrel

Priya Singh Python web development with Django Unit II


9/11/2023 30
Understanding Django environment(continue…)

Step 4 – Web Server


Django comes with a lightweight web server for developing and testing applications. This server is pre-configured to work with
Django, and more importantly, it restarts whenever you modify the code.
However, Django does support Apache and other popular web servers such as Lighttpd.
Django - Creating a Project
Now that we have installed Django, let's start using it. In Django, every web app you want to create is called a project; and a
project is a sum of applications. An application is a set of code files relying on the MVT pattern. As example let's say we want to
build a website, the website is our project and, the forum, news, contact engine are applications. This structure makes it ea sier
to move an application between projects since every application is independent.
Create a Project
Whether you are on Windows or Linux, just get a terminal or a cmd prompt and navigate to the place you want your project to
be created, then use this code −
$ django-admin startproject myproject

9/11/2023 Priya Singh Python web development with Django Unit II 31


Understanding Django environment(continue…)

This will create a "myproject" folder with the following structure −


myproject/
manage.py
myproject/
__init__.py settings.py
urls.py
wsgi.py
The Project Structure
The “myproject” folder is just your project container, it actually contains two elements −
manage.py − This file is kind of your project local django-admin for interacting with your project via command line (start the
development server, sync db...). To get a full list of command accessible via manage.py you can use the code −
$ python manage.py help
The “myproject” subfolder − This folder is the actual python package of your project. It contains four files −
__init__.py − Just for python, treat this folder as package.
settings.py − As the name indicates, your project settings.
urls.py − All links of your project and the function to call. A kind of ToC of your project.
wsgi.py − If you need to deploy your project over WSGI.

9/11/2023 Priya Singh Python web development with Django Unit II 32


Understanding Django environment(continue…)

Setting Up Your Project


Your project is set up in the subfolder myproject/settings.py. Following are some important options you might need
to set −
DEBUG = True This option lets you set if your project is in debug mode or not. Debug mode lets you get more
information about your project's error. Never set it to ‘True’ for a live project. However, this has to be set to ‘True’ if
you want the Django light server to serve static files. Do it only in the development mode.
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'database.sql', 'USER': '', 'PASSWORD': '',
'HOST': '', 'PORT': '', } } Database is set in the ‘Database’ dictionary. The example above is for SQLite engine. As
stated earlier, Django also supports −
MySQL (django.db.backends.mysql)
PostGreSQL (django.db.backends.postgresql_psycopg2)
Oracle (django.db.backends.oracle) and NoSQL DB
MongoDB (django_mongodb_engine)

9/11/2023 Priya Singh Python web development with Django Unit II 33


Understanding Django environment(continue…)

Before setting any new engine, make sure you have the correct db driver installed.
You can also set others options like: TIME_ZONE, LANGUAGE_CODE, TEMPLATE…
Now that your project is created and configured make sure it's working −
$ python manage.py runserver
You will get something like the following on running the above code −
Validating models... 0 errors found September 03, 2015 - 11:41:50 Django version 1.6.11, using
settings 'myproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server
with CONTROL-C.

9/11/2023 Priya Singh Python web development with Django Unit II 34


Features of Django

➢Rapid Development: Django was designed with the intention to make a framework which takes less time to build web
application. The project implementation phase is a very time taken but Django creates it rapidly.
➢Secure: Django takes security seriously and helps developers to avoid many common security mistakes, such as SQL
injection, cross-site scripting, cross-site request forgery etc. Its user authentication system provides a secure way to manage
user accounts and passwords.
➢Scalable: Django is scalable in nature and has ability to quickly and flexibly switch from small to large scale application
project.
➢Fully loaded: Django includes various helping task modules and libraries which can be used to handle common Web
development tasks. Django takes care of user authentication, content administration, site maps, RSS feeds etc.
➢Versatile: Django is versatile in nature which allows it to build applications for different-different domains. Now a days,
Companies are using Django to build various types of applications like: content management systems, social networks sites or
scientific computing platforms etc.

9/11/2023 Priya Singh Python web development with Django Unit II 35


Features of Django

➢Open Source:Django is an open source web application framework. It is publicly available without cost. It can be
downloaded with source code from the public repository. Open source reduces the total cost of the application
development.
➢Vast and Supported Community:Django is an one of the most popular web framework. It has widely supportive
community and channels to share and connect.

9/11/2023 Priya Singh Python web development with Django Unit II 36


Django Architecture

▪Every website has three main code sections: input logic, business logic, and user interface
logic. The code has certain functions to perform, the input data is the dataset and how it is
stored in the database. It is just a matter of delivering the input to the database in the
desired format. The Business Logic is what controls the output of the server in HTML or
another format. The HTML and CSS are the pages that it is written for.
▪MVC has a model, view, and controller. The Model is the information that your website/
application will be working with. The View is the presentation of the Model on your
website/application. Finally, the Controller is the code that connects the View and Model
together. In most cases, the Controller is the place where you will be writing your code.

9/11/2023 Priya Singh Python web development with Django Unit II 37


Django Architecture(continue…)

Model
The model is responsible for handling all data-related tasks. It can be a table in a database, a JSON file, or anything else. The
model takes the data from where it is stored and then processes it before sending it to the view. If the model needs to be
changed, it is done in a single place. In a web-based application, the model is the place where data is transformed from one
format to another.
View
The View component in the Django architecture is used to display the data from the Model component. It can also be used to
collect data from the user and send it to the Model as a form input. In this way, the View component contains the UI logic.
Examples of UI logic can be found in JavaScript code for animations, visualizations, and other interactive elements.

9/11/2023 Priya Singh Python web development with Django Unit II 38


Django Architecture(continue…)

Controller
▪Since the controller decides which view to display, it has the power to manipulate the view’s model. In this way, it can
apply any logic and rules to the view’s model. The controller also determines how to display the view and how to respond
to user input. It can manipulate the view’s model for this purpose as well. Since the view’s model is an abstraction of the
data model, the controller can manipulate the view’s model in any way it wants. It can also choose not to manipulate the
model, but rather display the data as it is. This is useful in cases where the model’s data is sensitive and must be
displayed exactly as it is. We can say that the controller is the one that decides when and what needs to be displayed.
Controllers are very helpful in keeping our code DRY, maintainable, and scalable. We can also have more than one
controller in a single application.
▪Django MTV Pattern
The web browser requests the page. When the page is received, the data is displayed in the placeholders on the page.
The response is then sent back to the client, ending the session and blocking further requests for a few moments. The
next time the client browses to the same URL, the application will be ready and a new session will start. This is how
traditional web applications work. Traditional web applications are hard to change. If the business requirements change,
the application is usually too big to change. If the marketing requirements change, the application is usually too big to
change.
Separate files are used to handle each of these steps in a Django web application.

9/11/2023 Priya Singh Python web development with Django Unit II 39


Django Architecture(continue…)

URLs: View functions can be used to handle HTTP requests in a more efficient manner by processing each
resource individually. URLs, on the other hand, can be processed collectively via a single function. View
functions may handle each resource individually by processing URLs individually. View functions may also
receive data from a URL mapper that matches certain literal strings or characters in a URL and passes them on
as data.
View: A view can be based on a database, an application, or any other source of information, and it is typically
separate from the code that receives and responds to HTTP requests. When you send an HTTP request to an
application, the code that handles that request might be on the same physical machine as the application
code. This might not be the case for a high volume of requests. For example, a web application that runs on a
cloud infrastructure might have a single virtual host running on a single physical machine. In this case, the
code that handles requests might not be on the same physical machine as the code that receives the requests.
Models: Data structure and database application methodologies are defined by a model.
Templates: An HTML template text file defines the structure or layout of a file (for example, an HTML page)
with placeholder text representing actual content. A model can be used to dynamically populate an HTML
page with data from a view, producing a view. A template may be used to define the structure of any kind of
file, not just HTML.

9/11/2023 Priya Singh Python web development with Django Unit I 40


Benefits of Django Architecture

The Django framework utilizes this architecture and does not require complex code to communicate between all three of
these components. That is why Django is becoming popular.
Rapid Development: It’s also one of Django’s advantages that multiple developers can work on different aspects of the same
application simultaneously. In fact, Django’s architecture, which separates components, makes it simple for multiple
developers to work on different aspects of the same application simultaneously.
Loosely Coupled: Every part of Django’s architecture must be present in order to maintain a high level of website security.
Because the model file will now be stored only on our server rather than on the webpage.
Ease of Modification: The significance of this element of Django architecture is that we don’t have to modify other
components if there are alterations in different components. The advantage of using Django is that it gives us much more
flexibility in designing our website than other frameworks.
Conclusion
Django is a popular Content Management System (CMS) and web framework that uses Python to build web applications.
Django provides a flexible, scalable architecture that makes it easy to build maintainable and secure applications.

9/11/2023 Priya Singh Python web development with Django Unit II 41


Django - Creating Views

A view function, or “view” for short, is simply a Python function that takes a web request and returns a web
response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML
document, or an image, etc. Example: You use view to create web pages, note that you need to associate a view
to a URL to see it as a web page.
In Django, views have to be created in the app views.py file.
Simple View
We will create a simple view in myapp to say "welcome to my app!"
See the following view −
from django.http import HttpResponse
def hello(request):
text = """<h1>welcome to my app !</h1>"""
return HttpResponse(text)

9/11/2023 Priya Singh Python web development with Django Unit II 42


Django - Creating Views

In this view, we use Http Response to render the HTML


Django supports the MVT pattern so to make the precedent view, Django - MVT like, we will need −
A template: myapp/templates/hello.html
And now our view will look like −
from django.shortcuts import render def hello(request): return render(request, "myapp/template/hello.html", {})
Views can also accept parameters −
from django.http import HttpResponse
def hello(request, number):
text = "<h1>welcome to my app number %s!</h1>"% number
return HttpResponse(text)
When linked to a URL, the page will display the number passed as a parameter.

9/11/2023 Priya Singh Python web development with Django Unit II 43


Django - URL Mapping

Django has his own way for URL mapping and it's done by editing your project url.py file (myproject/url.py).
The url.py file looks like −
from django.conf.urls import patterns, include, url
from django.contrib import
admin admin.autodiscover()
urlpatterns = patterns('', #Examples
#url(r'^$', 'myproject.view.home', name = 'home'),
#url(r'^blog/', include('blog.urls')),
url(r'^admin', include(admin.site.urls)), )
When a user makes a request for a page on your web app, Django controller takes over to look for the
corresponding view via the url.py file, and then return the HTML response or a 404 not found error, if not
found. In url.py, the most important thing is the "urlpatterns" tuple. It’s where you define the mapping
between URLs and views. A mapping is a tuple in URL patterns like −
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover()
urlpatterns = patterns('', #Examples #url(r'^$', 'myproject.view.home', name = 'home'), #url(r'^blog/',
include('blog.urls')), url(r'^admin', include(admin.site.urls)), url(r'^hello/', 'myapp.views.hello', name = 'hello'), )

9/11/2023 Priya Singh Python web development with Django Unit II 44


Django - URL Mapping(continue…)

• When a user makes a request for a page on your web app, Django controller takes over to look for the
corresponding view via the url.py file, and then return the HTML response or a 404 not found error, if
not found. In url.py, the most important thing is the "urlpatterns" tuple. It’s where you define the
mapping between URLs and views. A mapping is a tuple in URL patterns like −
• from django.conf.urls import patterns, include, url from django.contrib import admin
admin.autodiscover() urlpatterns = patterns('', #Examples #url(r'^$', 'myproject.view.home', name =
'home'), #url(r'^blog/', include('blog.urls')), url(r'^admin', include(admin.site.urls)), url(r'^hello/',
'myapp.views.hello', name = 'hello'), )
• The marked line maps the URL "/home" to the hello view created in myapp/view.py file. As you can
see above a mapping is composed of three elements −
• The pattern − A regexp matching the URL you want to be resolved and map. Everything that can work
with the python 're' module is eligible for the pattern (useful when you want to pass parameters via
url).
• The python path to the view − Same as when you are importing a module.
• The name − In order to perform URL reversing, you’ll need to use named URL patterns as done in the
examples above. Once done, just start the server to access your view via :http://127.0.0.1/hello

9/11/2023 Priya Singh Python web development with Django Unit II 45


Django Templates

Django provides a convenient way to generate dynamic HTML pages by using its template
system.A template consists of static parts of the desired HTML output as well as some
special syntax describing how dynamic content will be inserted.
Why Django Template
In HTML file, we can't write python code because the code is only interpreted by python
interpreter not the browser. We know that HTML is a static markup language, while Python
is a dynamic programming language.
Django template engine is used to separate the design from the python code and allows us
to build dynamic web pages.
Django Template Configuration
To configure the template system, we have to provide some entries in settings.py file.

9/11/2023 Priya Singh Python web development with Django Unit II 46


Django Templates(continue…)

9/11/2023 Priya Singh Python web development with Django Unit II 47


Django Templates(continue…)

9/11/2023 Priya Singh Python web development with Django Unit I 48


Django Templates(continue…)

Loading Template
To load the template, call get_template() method as we did below and pass template name
rom django.shortcuts
import render
#importing loading from django template from django.template import loader
# Create your views here.
from django.http import HttpResponse
def index(request): template = loader.get_template('index.html')
# getting our template return HttpResponse(template.render())
# rendering the template in HttpResponse

9/11/2023 Priya Singh Python web development with Django Unit II 49


Template Inheritance in Django

Including templates using include tag #


The include tag allows us to include the contents of a template inside another template. Here is the syntax of
the include tag:
{% include template_name %}
The template_name could be a string or a variable.
Let's take an example:
Create a new file named nav.html for the blog app in the directory blog/templates/blog and add the following
code to it:
TGDB/django_project/blog/templates/blog/nav.html
<nav>
<a href="#">Home
</a> <a href="#">blog</a>
<a href="#">Contact</a>
<a href="#">Career</a>
</nav>

9/11/2023 Priya Singh Python web development with Django Unit II 50


Template Inheritance in Django(continue….)

So far we have been creating very simple templates but in the real world, this is rarely the case. To give a common look and
feel across all the pages of a website some HTML code is repeated. Typically header, navigation, footer, and sidebar remains
the same throughout the site. The problem arises when we want to modify some part of the page. To better understand
the issue, let's take an example.
Suppose we have two pages namely home.html and contact.html
extends – Django template Tags Explanation
Illustration of How to use extends tag in Django templates using an Example
# import Http Response from django
from django.shortcuts import render

# create a function
def geeks_view(request):

# return response
return render(request, "extendedgeeks.html“)

9/11/2023 Priya Singh Python web development with Django Unit II 51


Django Models

▪A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. In short,
Django Models is the SQL of Database one uses with Django. SQL (Structured Query Language) is complex and involves
a lot of different queries for creating, deleting, updating or any other stuff related to database. Django models simplify
the tasks and organize tables into models. Generally, each model maps to a single database table.
▪Django models provide simplicity, consistency, version control and advanced metadata handling. Basics of a model
include –
▪Each model is a Python class that subclasses django.db.models.Model.

▪Each attribute of the model represents a database field.

▪With all of this, Django gives you an automatically-generated database-access API; see Making queries.

9/11/2023 Priya Singh Python web development with Django Unit II 52


Django Models(continue….)

Example –
from django.db import models

# Create your models here.


class GeeksModel(models.Model):
title = models.CharField(max_length = 200)
description = models.TextField()
Django maps the fields defined in Django models into table fields of the database as shown
below.

9/11/2023 Priya Singh Python web development with Django Unit II 53


Django Models(continue….)

• Using Django Models


• To use Django Models, one needs to have a project and an app working in it. After you start an app you
can create models in app/models.py.
• Creating a Model
• Syntax

• from django.db
• import models
• class ModelName(models.Model):
• field_name = models.Field(**options)
• To create a model, in geeks/models.py Enter the code

9/11/2023 Priya Singh Python web development with Django


54
Unit II
Django Models(continue….)

To create a model, in geeks/models.py Enter the code


# import the standard Django Model
# from built-in library
from django.db import models

# declare a new model with a name "GeeksModel"


class GeeksModel(models.Model):
# fields of the model
title = models.CharField(max_length = 200)
description = models.TextField()
last_modified = models.DateTimeField(auto_now_add = True)
img = models.ImageField(upload_to = "images/")

# renames the instances of the model


# with their title name
def __str__(self):
return self.title

9/11/2023 Priya Singh Python web development with Django Unit I 55


Django Models(continue….)

whenever we create a Model, Delete a Model, or update anything in any of models.py of our project. We need to run
two commands makemigrations and migrate. makemigrations basically generates the SQL commands for preinstalled
apps (which can be viewed in installed apps in settings.py) and your newly created app’s model which you add in
installed apps whereas migrate executes those SQL commands in the database file.
So when we run
Python manage.py makemigrations
SQL Query to create above Model as a Table is created and
Python manage.py migrate
creates the table in the database.
Now we have created a model we can perform various operations such as creating a Row for the table or in terms of Django
Creating an instance of Model.

9/11/2023 Priya Singh Python web development with Django Unit II 56


Django Models(continue….)

Django Model Fields


The fields defined inside the Model class are the columns name of the mapped table. The fields name should not
be python reserve words like clean, save or delete etc.
Django provides various built-in fields types.

9/11/2023 57
Priya Singh Python web development with Django Unit II
Django Models(continue….)

9/11/2023 Priya Singh Python web development with Django Unit II 58


Django Models(continue….)

9/11/2023 Priya Singh Python web development with Django Unit II 59


Django Models(continue….)

9/11/2023 Priya Singh Python web development with Django Unit II 60


Django with Bootstrap

Bootstrap is a framework which is used to create user interface in web applications. It provides css, js and other tools that
help to create required interface.
In Django, we can use bootstrap to create more user friendly applications.
To implement bootstrap, we need to follow the following steps.
Download the Bootstrap
Visit the official site https://getbootstrap.com to download the bootstrap at local machine. It is a zip file, extract it and see it
contains the two folder.

9/11/2023 Priya Singh Python web development with Django Unit I 61


Django with Bootstrap

Create a Directory
Create a directory with the name static inside the created app and place the css and jss folders inside it.
Create a Template
First create a templates folder inside the app then create a index.htm file to implement (link) the bootstrap css and js files.
Load the Boostrap
load the bootstrap files resides into the static folder. Use the following code.
{% load staticfiles %}
And link the files by providing the file location (source). See the index.html file.

9/11/2023 Priya Singh Python web development with Django Unit II 62


Django with Bootstrap

In this template, we have link two files one is bootstrap.min.css and second is bootstrap.min.js. Lets see how to use
them in application.
Suppose, if we don't use bootstrap, our html login for looks like this:

9/11/2023 Priya Singh Python web development with Django Unit II 63


Django with Bootstrap

9/11/2023 Priya Singh Python web development with Django Unit II 64


Django with Bootstrap

After loading bootstrap files. Our code look like this:


// index.html

Priya Singh Python web development with Django


9/11/2023 65
Unit II
Django with Bootstrap

Priya Singh Python web development with Django


9/11/2023 66
Unit II
Daily Quiz

1. What is the role of frameworks in python.


2. Discuss any three frameworks.
3. Discuss about Turbogear.
4. Discuss implementation rule of Falcon.
5. Discuss the Zappa framework.
6. Discuss the role of Dash.
7. Discuss the application area of cherryPy.
8. Discuss about the Request Http methods in Python.
9. Discuss about Flask application.

Priya Singh Python web development with Django Unit II


9/11/2023 67
Weekly Assignment

1. What are the most important uses of Django.


2. What are the disadvantages of Django?
3. What are the different data types used in Django.
4. What are the salient features of Django.
5. What are some of the technical features that Django includes

9/11/2023 Priya Singh Python web development with Django Unit II 68


Topic Link ( YouTube & NPTEL Video Links)

YouTube /other Video Links


• https://youtu.be/eoPsX7MKfe8?list=PLIdgECt554OVFKXRpo_kuI0XpUQKk0ycO

• https://youtu.be/tA42nHmmEKw?list=PLh2mXjKcTPSACrQxPM2_1Ojus5HX88ht7

• https://youtu.be/8ndsDXohLMQ?list=PLDsnL5pk7-N_9oy2RN4A65Z-PEnvtc7rf

• https://youtu.be/QXeEoD0pB3E?list=PLsyeobzWxl7poL9JTVyndKe62ieoN-MZ3

• https://youtu.be/9MmC_uGjBsM?list=PL3pGy4HtqwD02GVgM96-V0sq4_DSinqvf

9/11/2023 Priya Singh Python web development with Django Unit II 69


MCQ s
1. What is a Django App? 2. Django was introduced by
ADjango app is an extended package with base package
is Django A. Adrian Holovaty
B. Django app is a python package with its own B. Bill Gates
components. C. Rasmus Lerdorf
C. Both 1 & 2 Option D. Tim Berners-Lee
D. All of the above
3. What are Migrations in Django
A. They are files saved in migrations directory.
B. They are created when you run make migrations
command.
C. Migrations are files where Django stores changes to
your models.
D. All of the above
4. Which architectural pattern does django follow
APHP
B. MVT
C. HTML Priya Singh Python web development with Django Unit II
9/11/2023 70
D. None of the above
MCQ s

which of these is not a valid backend for caching in django


A. Django.core.cache.backends.sys.memory
B. django.core.cache.backends.db.DatabaseCache
C. django.core.cache.backends.locmem.LocMemCache
D. None of the above
5. Which architectural pattern does django follow
A.PHP
B. MVT
C. HTML
D. None of the above

Priya Singh Python web development with Django


9/11/2023 71
Unit II
MCQ s
6. Python is a : 7. Python is Case Sensitive when dealing with
▪Development environment Identifiers?
▪Set of editing tools ▪Yes
▪Programming Language ▪No
▪Sometimes Only
▪None Of the Above

8. What is the OUTPUT of the following Statement? 9. What is the OUTPUT when the following
print 0xA + 0xB + 0xC : Statement is executed?
▪0xA0xB0xC “abc”+”xyz”
▪33 ▪abc
▪ABC ▪abcxyz
▪000XXXABC ▪abcz
▪abcxy

10.what is the type of a? a={1,2:3} list


set
dict Priya Singh Python web development with Django Unit II
9/11/2023 72
syntax error
Glossary Questions
Top 10 design pattern interview questions

1. Explain Django Architecture?


2. Explain the Django project directory structure?
3. What are models in Django?
4. What are templates in Django or Django template language?
5. What are views in Django?
6. What is Django ORM?
7. What is Django Rest Framework(DRF)?
8. What is the difference between a project and an app in Django?
9. What are different model inheritance styles in the Django?
10.What are Django Signals?
9/11/2023 Priya Singh Python web development with Django Unit II 73
Expected Questions for University Exam
Top 10 design pattern interview questions

1. Explain Django Architecture?


2. Explain the Django project directory structure?
3. What are models in Django?
4. What are templates in Django or Django template language?
5. What are views in Django?
6. What is Django ORM?
7. What is Django Rest Framework(DRF)?
8. What is the difference between a project and an app in Django?
9. What are different model inheritance styles in the Django?
10.What are Django Signals?
9/11/2023 Priya Singh Python web development with Django Unit I 74
Django authentication system
• The Django authentication system handles both authentication and
authorization. Briefly, authentication verifies a user is who they claim
to be, and authorization determines what an authenticated user is
allowed to do.
The auth system consists of:
• Users
• Permissions: Binary (yes/no) flags designating whether a user may
perform a certain task.
• Groups: A generic way of applying labels and permissions to more
than one user.
• A configurable password hashing system
• Forms and view tools for logging in users, or restricting content
• A pluggable backend system
Priya Singh Python web development with
9/11/2023 29
Django Unit III
Introduction to Django Authentication System
➢ For most websites, the basic entity of authentication is a user. A user is
identified by some unique string, which is almost always an email address
or username.

➢ To prove someone is who they say they are, they must provide a password
when creating an account, and again at any time they want to
authenticate themselves. This should be familiar: you go through this kind
of workflow any time you sign up for a service like Twitter or Netflix.

➢ Django provides a User model for creating and managing users. Django
users have a username and password, but can also optionally have an
email address and a first and last name:
9/11/2023 Priya Singh Python web development with Django Unit III 30
Introduction to Django Authentication System

9/11/2023 Priya Singh Python web development with Django Unit III 31
Authentication support is bundled as a Django contrib module in django.contrib.auth. By
default, the required configuration is already included in the settings.py generated
by django-admin startproject, these consist of two items listed in
your INSTALLED_APPS setting:
1.'django.contrib.auth' contains the core of the authentication framework, and its default
models.
2.'django.contrib.contenttypes' is the Django content type system, which allows
permissions to be associated with models you create.

and these items in your MIDDLEWARE setting:


1.SessionMiddleware manages sessions across requests.
2.AuthenticationMiddleware associates users with requests using sessions.
With these settings in place, running the command manage.py migrate creates the necessary
database tables for auth related models and permissions for any models defined in your installed
apps.

Priya Singh Python web development with


9/11/2023 32
Django Unit III
Introduction to Django Authentication System

➢ Django provides a level of security when it comes to passwords. It has a


built-in set of password validators, some of which are enabled by default
in new projects. You can write your own validators to enforce any
password rules you might need, but choose wisely.

➢ In addition to password validation, Django safely stores password


information by default. Django salts and hashes passwords before storing
them when a user is created, so their plaintext password is no longer
available outside the context of the initial registration request or when
they log in.

9/11/2023 Priya Singh Python web development with Django Unit III 33
Introduction to Django Authentication System
➢ Django can authenticate a user by checking a supplied set of credentials
against the existing set of registered users. If a user matches, Django
will return that user object. Otherwise, it will return None.

➢ From django.contrib.auth import authenticate


user = authenticate(
username='rafaela',
password='$uper$ecretpassword'
)
➢ Django has a vast feature set for authenticating users and interacting
with user objects to get things done.
9/11/2023 Priya Singh Python web development with Django Unit III 34
Security Problem & Solution with Django
➢ Django is widely lauded for its ease-of-use and pragmatic design, but like
all software it is susceptible to its own share of critical vulnerabilities.
Django's open source popularity means that default attack vectors are
also widely known.

➢ The application layer is increasingly targeted by hackers for penetration,


and running full stack Python is no more/less vulnerable than any of the
other application stacks. In fact, BitBucket , dpaste, and Mozilla Support
are all employing Python/Django for their mission-critical web offerings,
so have no fear—effective vulnerability management and visibility into
existing Django security gaps can go a long way towards hardening your
Django-based web app against attacks.
9/11/2023 Priya Singh Python web development with Django Unit III 35
Security Problem & Solution with Django

Django’s Top 10 Vulnerabilities

10. Session Modification (CVE-2011-4136)

❑ Versions 1.2.7 and 1.3.x before 1.3.1

❑ When session details are stored in the cache, root namespacing is used
for both session identifiers and application-data keys. This can allow
remote attackers to modify a session by triggering use of a key that is
equal to that session's identifier.

9/11/2023 Priya Singh Python web development with Django Unit III 36
Security Problem & Solution with Django
Django’s Top 10 Vulnerabilities

9. Session Hijacking (CVE-2014-0482)

❑ ‍Versions‍ 1.4.14, 1.5.x before 1.5.9, 1.6.x before 1.6.6, and 1.7 .

❑ Session hijacking involves an attacker gaining unauthorized access to a


system‍using‍another‍user’s‍session‍data.‍

❑ In this case, when using contrib.auth.backends.RemoteUserBackend,


remote authenticated users can hijack web sessions via vectors related to
the REMOTE_USER header.
9/11/2023 Priya Singh Python web development with Django Unit III 37
Security Problem & Solution with Django
Django’s Top 10 Vulnerabilities

8. Cache Poisoning (CVE-2014-1418)

❑ Versions 1.4 before 1.4.13, 1.5 before 1.5.8, 1.6 before 1.6.5

❑ Cache poisoning occurs when incorrect data is inserted into a DNS resolver
‘s‍cache,‍causing‍the‍nameserver to provide an incorrect IP address or
destination. These versions of Django do not not properly include the:
1. Vary: Cookie
2. Cache-Control header in response
❑ This can allow remote attackers to obtain sensitive information or poison
the cache via a request from certain
Priya Singh
browsers.
Python web development with Django Unit III
9/11/2023 38
Security Problem & Solution with Django

Django’s Top 10 Vulnerabilities

7. Arbitrary URLs Generation (CVE-2012-4520)

❑ ‍Versions‍1.3.x before 1.3.4 and 1.4.x before 1.4.2

❑ In these versions, the django.http.HttpRequest.get_host function allows


remote attackers to generate and display arbitrary URLs via crafted
username and password Host header values.

9/11/2023 Priya Singh Python web development with Django Unit III 39
Security Problem & Solution with Django
Django’s Top 10 Vulnerabilities

6. CSRF: Unauthenticated Forged Requests (CVE-2011-4140)

❑ V
‍ ersions‍through‍1.2.7 and 1.3.x through 1.3.1
❑ CSRF is short for Cross Site Request Forgery, an attack that utilizes the
user’s‍web‍browser‍to‍perform‍an‍unwanted‍action‍on‍another‍website‍in‍
which the user is currently signed in. The CSRF protection mechanism in
these versions of Django do not properly handle web-server configurations
supporting arbitrary HTTP Host headers, allowing remote attackers to
trigger unauthenticated forged requests via vectors involving a DNS
CNAME record and a web page containing JavaScript code.
9/11/2023 Priya Singh Python web development with Django Unit III 40
Security Problem & Solution with Django

Django’s Top 10 Vulnerabilities

5. CSRF Via Forged AJAX Requests (CVE-2011-0696)

❑ ‍Versions‍1.1.x before 1.1.4 and 1.2.x before 1.2.5

❑ These versions of Django do not properly validate HTTP requests that


contain an X-Requested-With header, making it trivial for remote attackers
to carry out cross-site request forgery (CSRF) attacks via forged AJAX
requests that leverage a "combination of browser plugins and redirects," a
related issue to CVE-2011-0447.

9/11/2023 Priya Singh Python web development with Django Unit III 41
Security Problem & Solution with Django
Django’s Top 10 Vulnerabilities

4. Directory Traversal (CVE-2011-0698)


❑ ‍Versions‍1.1.x before 1.1.4 and 1.2.x before 1.2.5 on Windows

❑ In these versions of Django, remote attackers are able to read or execute files via a /
(slash) character in a key in a session cookie, related to session replays.
3. DoS: Via Unspecified Vectors (CVE-2015-5145)
❑ ‍Versions‍1.8.x before 1.8.3

❑ DoS is short for Denial of Service, and occurs when an attacker brings down a
network/website by flooding it with data packets. The validators.URLValidator in these
versions of Django allow remote attackers to cause a denial of service (CPU
consumption) via unspecified vectors.
9/11/2023 Priya Singh Python web development with Django Unit III 42
Security Problem & Solution with Django

Django’s Top 10 Vulnerabilities

2. DoS : Via Multiple Requests With Unique Session Keys (CVE-2015-5143)

❑ V
‍ ersions‍before‍1.4.21, 1.5.x through 1.6.x, 1.7.x before 1.7.9, and 1.8.x
before 1.8.3

❑ The session backends in Django allows remote attackers to cause a denial


of service (session store consumption) via multiple requests with unique
session keys.

9/11/2023 Priya Singh Python web development with Django Unit III 43
Security Problem & Solution with Django
Django’s Top 10 Vulnerabilities

1. Type Conversion Vulnerability (CVE-2014-0474)


❑ ‍Versions‍before‍1.4.11, 1.5.x before 1.5.6, 1.6.x before 1.6.3, and 1.7.x
before 1.7 beta

❑ In these versions of Django, the following field classes do not properly


perform type conversion :
1. FilePathField
2. GenericIPAddressField
3. IPAddressField
❑ This gives remote attackers access to unspecified impact and vectors
related to MySQL.
9/11/2023 Priya Singh Python web development with Django Unit III 44
Security Problem & Solution with Django

Remediation of Django
➢ To fix the above vulnerabilities, you'll need to update the current working
version of your Django framework in all your environments. And while Django
is backwards compatible, it is nonetheless crucial that you identify any
components in your web app that might be impacted by patching/updating.

➢ UpGuard provides a way for you to do this easily and automatically with a
few mouse clicks. Our powerful policy engine can validate secure
configurations for all environments, infrastructures, and application stacks. In
this case, a simple Django security policy can be run to check for any of the
above vulnerabilities—as well as new vulnerabilities not yet added to policy.
Our OVAL-backed vulnerability detection and monitoring suite ensures that
all your Django components are free for vulnerabilities and security gaps.
9/11/2023 Priya Singh Python web development with Django Unit III 45
Creating Registration Form using Django
Create Sign Up Form

First of all, create a URL for your signup page by adding a new path to the urlpatterns list in urls.py.

from . import views


from django.conf.urls import url, include
from django.urls import path

urlpatterns = [
url(r'^$', views.index, name='home'),
path('signup/', views.signup, name='signup'), # newly added
]

9/11/2023 Priya Singh Python web development with Django Unit III 46
Creating Registration Form using Django
Create forms.py file if it is not present and add the following class for the sign-up form.
For creating sign up form, we can use the Django UserCreationForm.

django.contrib.auth.models import User


from django.contrib.auth.forms import UserCreationForm

class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'password1', 'password2', )

Create a view to process the signup data and save that data into the database. You can simply
use below function definition in your views.py file.

9/11/2023 Priya Singh Python web development with Django Unit III 47
Creating Registration Form using Django
from .forms import SignUpForm

def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db()
# load the profile instance created by the signal
user.save()
raw_password = form.cleaned_data.get('password1')

# login user after signing up


user = authenticate(username=user.username, password=raw_password)
login(request, user)

# redirect user to home page


return redirect('home')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})

9/11/2023 Priya Singh Python web development with Django Unit III 48
Creating Registration Form using Django
Create a sign-up HTML page in your template directory.
{% extends 'base.html' %}
<h2>Sign up</h2>
<form method="post">
{% csrf_token %}
{% for field in form %}
<p>
{{ field.label_tag }}<br>
{{ field }}
{% if field.help_text %}
<small style="color: grey">{{ field.help_text }}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit">Sign up</button>
</form>
{% endblock %}

9/11/2023 Priya Singh Python web development with Django Unit III 49
Creating Registration Form using Django

Run your Django project locally. Open the below URL in your browser.

http://127.0.0.1:8000/signup/

This is what the signup form will look like.

9/11/2023 Priya Singh Python web development with Django Unit III 50
Adding Email ,Configuring email & Sending emails with Django

Django Mail Setup

➢ Sending email using Django is pretty easy and require less configuration. In
this lecture, we will send email to provided email.
➢ For this purpose, we will use Google's SMTP and a Gmail account to set
sender.
➢ Django provides built-in mail library django.core.mail to send email.
➢ Before sending email, we need to make some changes in Gmail account
because for security reasons Google does not allow direct access (login) by
any application. So, login to the Gmail account and follow the urls. It will
redirect to the Gmail account settings where we need to allow less secure
apps but toggle the button. See the below screenshot.
9/11/2023 Priya Singh Python web development with Django Unit III 51
Adding Email ,Configuring email & Sending emails with Django

9/11/2023 Priya Singh Python web development with Django Unit III 52
Adding Email ,Configuring email & Sending emails with Django

9/11/2023 Priya Singh Python web development with Django Unit III 53
Adding Email ,Configuring email & Sending emails with Django

9/11/2023 Priya Singh Python web development with Django Unit III 54
Adding Email ,Configuring email & Sending emails with Django

9/11/2023 Priya Singh Python web development with Django Unit III 55
Adding Email ,Configuring email & Sending emails with Django

9/11/2023 Priya Singh Python web development with Django Unit III 56
Adding Grid Layout On Registration Page

9/11/2023 Priya Singh Python web development with Django Unit III 57
Adding Grid Layout On Registration Page
Bootstrap Container
▪ A Container is the outermost component the Bootstrap framework knows of. Here
the designer can specify the breakpoints of a web page. By default, Bootstrap
offers‍4‍breakpoints:‍“large”,‍“medium”,‍“small”‍and‍“tiny”.‍These‍determine‍for‍
which kind of screen widths, the grid system may switch the layout.

▪ The editor window for a Container element offers the possibility to deactivate
certain breakpoints. While this might make sense under certain conditions, it is
safe to always keep all four breakpoints active, since this gives the designer of the
web page the maximum flexibility.

9/11/2023 Priya Singh Python web development with Django Unit III 58
Adding Grid Layout On Registration Page
Small devices exclusively :-

9/11/2023 Priya Singh Python web development with Django Unit III 59
Adding Page Restrictions
➢ Creating a website is fun, but a login restrictor in your website will make it look more
secure. Django REST Framework is a robust and flexible toolkit for building Web APIs.
The Django login required decorator provide the feature to restrict the access
➢ We have often visited websites in which we need to log in first before accessing or
visiting other pages. In other words, restricting access.

9/11/2023 Priya Singh Python web development with Django Unit III 60
Adding Page Restrictions

➢ We also came across some of our projects where we need to do the same
but wonder how? So yes you came to the right place, but before moving
ahead‍let’s‍first‍sneak‍peek‍about‍the‍login‍decorator‍in‍Django‍Rest‍
Framework. login_required() decorator does the following things:-
➢ Execute normally the view if the user is logged in.
➢ Redirect the user to the login_url path if the user is not logged in.
➢ Syntax:-

➢ @login_required(login_url=”html‍page”)

➢ In this lecture , we will understand how to restrict access with the Django
login required decorator function? Where to use it? And all about it.

9/11/2023 Priya Singh Python web development with Django Unit III 61
Why Decorators?

Django provides several decorators that can be applied to views to support various HTTP
features.
Decorators are an easy way to clean up your code and separate the view
authentication process from the view functionality. Django has several useful built-
in decorators such as @login_required, @permission_required for user
permissions and @require_http_methods for restricting request methods
(GET|POST).

Priya Singh Python web development with


9/11/2023 62
Django Unit III
Login Functionality Test and Logout

➢ Exaplaining Django Login and Logout. Django is a High-Level Web Framework and it has
lots of built-in features. We can use those built-in functions for our common use of Web
Application. Some of the functions are Permission and User Control, Signals, Templates,
Django ORM, Access Control List, etc. Out of this Registration App, is a good example and
a good thing about it is that the features can be used out-of-the-box.

➢ With the Authentication Views, you can take advantage of the following features

1. Login
2. logout
3. User Registration
4. Change Password
5. Reset Password or Forgot Password

9/11/2023 Priya Singh Python web development with Django Unit III 63
Login Functionality Test and Logout

9/11/2023 Priya Singh Python web development with Django Unit III 64
Login Functionality Test and Logout

9/11/2023 Priya Singh Python web development with Django Unit III 65
Login Functionality Test and Logout

9/11/2023 Priya Singh Python web development with Django Unit III 66
Daily Quiz

1. Discuss Django Authentication System.


2. What is the role of frameworks in python.
3. Discuss any three frameworks.
4. Discuss about , Security Problem & Solution with Django .
5. Discuss implementation rule of Falcon.
6. Discuss the Zappa framework.
7. Discuss the role of Dash.
8. Discuss the application area of cherryPy.
9. Discuss about the Request Http methods in Python.
10. Discuss about Flask application.

Priya Singh Python web development with Django Unit III


9/11/2023 67
Weekly Assignment

1. What are the most important uses of Django.


2. What are the disadvantages of Django?
3. What are the different data types used in Django.
4. What are the salient features of Django.
5. What are some of the technical features that Django includes

9/11/2023 Priya Singh Python web development with Django Unit III 68
Topic Link ( YouTube & NPTEL Video Links)

YouTube /other Video Links


• https://youtu.be/eoPsX7MKfe8?list=PLIdgECt554OVFKXRpo_kuI0XpUQKk0ycO

• https://youtu.be/tA42nHmmEKw?list=PLh2mXjKcTPSACrQxPM2_1Ojus5HX88ht7

• https://youtu.be/8ndsDXohLMQ?list=PLDsnL5pk7-N_9oy2RN4A65Z-PEnvtc7rf

• https://youtu.be/QXeEoD0pB3E?list=PLsyeobzWxl7poL9JTVyndKe62ieoN-MZ3

• https://youtu.be/9MmC_uGjBsM?list=PL3pGy4HtqwD02GVgM96-V0sq4_DSinqvf

9/11/2023 Priya Singh Python web development with Django Unit III 69
MCQ s
1. What is a Django App? 2. Django was introduced by
ADjango app is an extended package with base package
is Django A. Adrian Holovaty
B. Django app is a python package with its own B. Bill Gates
components. C. Rasmus Lerdorf
C. Both 1 & 2 Option D. Tim Berners-Lee
D. All of the above
3. What are Migrations in Django
A. They are files saved in migrations directory.
B. They are created when you run make migrations
command.
C. Migrations are files where Django stores changes to
your models.
D. All of the above
4. Which architectural pattern does django follow
APHP
B. MVT
C. HTML Priya Singh Python web development with Django Unit III
9/11/2023 70
D. None of the above
MCQ s

which of these is not a valid backend for caching in django


A. Django.core.cache.backends.sys.memory
B. django.core.cache.backends.db.DatabaseCache
C. django.core.cache.backends.locmem.LocMemCache
D. None of the above
5. Which architectural pattern does django follow
A.PHP
B. MVT
C. HTML
D. None of the above

Priya Singh Python web development with


9/11/2023 71
Django Unit III
MCQ s
6. Python is a : 7. Python is Case Sensitive when dealing with
▪Development environment Identifiers?
▪Set of editing tools ▪Yes
▪Programming Language ▪No
▪Sometimes Only
▪None Of the Above

8. What is the OUTPUT of the following Statement? 9. What is the OUTPUT when the following
print 0xA + 0xB + 0xC : Statement is executed?
▪0xA0xB0xC “abc”+”xyz”
▪33 ▪abc
▪ABC ▪abcxyz
▪000XXXABC ▪abcz
▪abcxy

10.what is the type of a? a={1,2:3} list


set
dict Priya Singh Python web development with Django Unit III
9/11/2023 72
syntax error
Glossary Questions
Top 10 design pattern interview questions

1. Explain Django Architecture?


2. Explain the Django project directory structure?
3. What are models in Django?
4. What are templates in Django or Django template language?
5. What are views in Django?
6. What is Django ORM?
7. What is Django Rest Framework(DRF)?
8. What is the difference between a project and an app in Django?
9. What are different model inheritance styles in the Django?
10.What are Django Signals?
9/11/2023 Priya Singh Python web development with Django Unit III 73
Expected Questions for University Exam
Top 10 design pattern interview questions

1. Explain Django Architecture?


2. Explain the Django project directory structure?
3. What are models in Django?
4. What are templates in Django or Django template language?
5. What are views in Django?
6. What is Django ORM?
7. What is Django Rest Framework(DRF)?
8. What is the difference between a project and an app in Django?
9. What are different model inheritance styles in the Django?
10.What are Django Signals?
Priya Singh Python web development with Django Unit
9/11/2023 74
III
Unit IV Content

• Database Migrations.
• Fetch Data From Database.
• Displaying Data On Templates.
• Adding Condition On Data.
• Sending data from url to view.
• Sending data from view to template.
• Saving objects into database, Sorting objects, Filtering objects, Deleting
objects.
• Difference between session and cookie, Creating sessions and cookies in
Django.

11/3/23 Priya Singh Python web development with Django Unit IV 26


Unit IV Objective

In Unit IV, the students will be able to find


• Definitions of terms Database Migrations.
• How Fetch Data From Database & Displaying Data On Templates.
• How to Send data from url to view.
• How to Send data from view to template.
• The idea of a python Library .
• Difference between session and cookie, Creating sessions and cookies
in Django

Priya Singh Python web development with Django Unit IV


11/3/23 27
Topic Objective

Topic : Database Migrations


• In this topic, the students will gain , The idea of Database migration
is the process of migrating data from one or more source databases
to one or more target databases by using a database migration
service.

11/3/23 Priya Singh Python web development with Django Unit IV 28


Database Migrations
Database migration: Concepts and principles

Ø Database migration is the process of migrating data from one or more source databases
to one or more target databases by using a database migration service.

Ø When a migration is finished, the dataset in the source databases resides fully, though
possibly restructured, in the target databases. Clients that accessed the source databases
are then switched over to the target databases, and the source databases are turned
down.

Ø A database migration service runs within Google Cloud and accesses both source and
target databases. Two variants are represented: (a) shows the migration from a source
database in an on-premises data center or a remote cloud to a managed database like
Cloud Spanner; (b) shows a migration to a database on Compute Engine
11/3/23 Priya Singh Python web development with Django Unit IV 29
Database Migrations

Database Migration Process

11/3/23 Priya Singh Python web development with Django Unit IV 30


Database Migrations
We describe Database migration from an architectural stand pointwise:-

ü The services and technologies involved in database migration.


ü The differences between homogeneous and heterogeneous database
migration.
ü The tradeoffs and selection of a migration downtime tolerance.
ü A setup architecture that supports a fallback if unforeseen errors occur
during a migration.
ü This document does not describe how you set up a particular database
migration technology. Rather, it introduces database migration in
fundamental, conceptual, and principle terms.

11/3/23 Priya Singh Python web development with Django Unit IV 31


Database Migrations
Database Migration Architecture:-

Even though the target databases are different in type (managed and unmanaged) and setup,
the 11/3/23
database migration architecture
Priya Singh and configuration
Python web development withis the same
Django Unit IV for both cases. 32
Database Migrations
Terminology :-

11/3/23 Priya Singh Python web development with Django Unit IV 33


Database Migrations
Terminology :-

11/3/23 Priya Singh Python web development with Django Unit IV 34


Database Migrations

Database migration architecture :-

A database migration architecture describes the various components required for executing a
database migration. This section introduces a generic deployment architecture and treats the
database migration system as a separate component. It also discusses the features of a
database management system that support data migration as well as non-functional
properties that are important for many use cases.

Deployment architecture:-

A database migration can occur between source and target databases located in any
environment, like on-premises or different clouds. Each source and target database can be in
a different environment; it is not necessary that all are collocated in the same environment.
11/3/23 Priya Singh Python web development with Django Unit IV 35
Database Migrations

11/3/23 Priya Singh Python web development with Django Unit IV 36


Fetch Data From Database

How to fetch data from database in django?

Ø In django, we retrieve the data in the views.py file, where we write our
functions.
Ø To retrieve data from database, first we have to create a url for that. Open the
urls.py file inside the application folder, and create a new path as shown
below:
path('students/', views.students, name="students"),

Now create a function in the views.py file, with the name "students" as shown in
the above path.

11/3/23 Priya Singh Python web development with Django Unit IV 37


Fetch Data From Database

Ø Here, we have created a variable form and we have called all the objects of the Student
model. Objects is nothing but the records in the database. Then we have created a
dictionary named context and passed the form variable in the dictionary and passed
that dictionary in the render() function.

Ø As we have mentioned in the render(), let us create a .html file with the name
index.html and we will be displaying the all the data in the index.html. To display the
data, we will be using the for loop as there will be multiple data in our database.
11/3/23 Priya Singh Python web development with Django Unit IV 38
Fetch Data From Database

This will print all the data that we had fetched and
stored in the form variable.
11/3/23 Priya Singh Python web development with Django Unit IV 39
Displaying Data On Templates
Django templates

Ø Sometimes you want parts of your website to display dynamic data -


that is, data that might be different every time someone opens your
website. In that case, plain HTML won't be enough.

Ø Luckily, Django templates allow us to do a lot more than just write


HTML. We can display some Python variables that we defined in our
view. Django also gives us some helpful built-in template tags for
displaying data.

Ø Django template tags allow us to transfer Python-like things into


HTML, so you can build dynamic websites faster and easier
11/3/23 Priya Singh Python web development with Django Unit IV 40
Displaying Data On Templates

Display the current date and time:

11/3/23 Priya Singh Python web development with Django Unit IV 41


Displaying Data On Templates

11/3/23 Priya Singh Python web development with Django Unit IV 42


Adding Condition On Data
Ø The if template tag is one of the template tags in Django that can be
used to render HTML content for a particular condition. Let us see
how to use the if template tag in Django.

Ø In a Django template, the if statement is referred to as if tag. You can


use this if tag to render HTML content based on a particular
condition. The syntax of the if template tag is:

11/3/23 Priya Singh Python web development with Django Unit IV 43


Adding Condition On Data

Ø In a Django template, you have to close the if template tag. You can write
the condition in an if template tag. Inside the block, you can write the
statements or the HTML code that you want to render if the condition
returns a True value.

Ø Now let us see an example of the if tag.

Ø I have created an example where I will enter two numbers and compare
them inside a Django template.

Ø The following is the Django template where I will submit the two numbers:

11/3/23 Priya Singh Python web development with Django Unit IV 44


Adding Condition On Data

11/3/23 Priya Singh Python web development with Django Unit IV 45


Sending data from url to view
Get URL parameters in Django

Ø In Django, you can also pass parameters as part of the URL. In this Django tutorial, you will
learn how to get URL parameters in Django.

Ø In various web applications, you might have seen some URLs that end with some
parameters. For example, look at the below URL:

https://www.shop.tsinfo.com/products/12

Ø The above URL fetches the products page corresponding to a product id i.e. 12. This means
12 is a URL parameter and the result is shown according to this value.

11/3/23 Priya Singh Python web development with Django Unit IV 46


Sending data from url to view
To get a parameter from the URL, you have to perform the steps explained below:

1. Create and map a path to a view in the application’s URLs file and pass the
parameters to the view

2. Define a function in the view that will take the parameter and pass the parameters to
Django template.

3. Design the Django template to show the results corresponding the passed
parameters.

Let us discuss these steps briefly in the upcoming sections.

11/3/23 Priya Singh Python web development with Django Unit IV 47


Sending data from url to view

Django URL pass parameter to view

Ø You can pass a URL parameter from the URL to a view using a path converter.
Ø But, firstly you have to create a path and map it to a view.
Ø For this, you have to edit your application’s urls.py file.
Ø A sample urls.py file will look like this:

11/3/23 Priya Singh Python web development with Django Unit IV 48


Sending data from url to view
For example, if the requested URL is:

https://www.shop.tsinfo.com/products/12

Then “products” will be the URL endpoint.


1. A path converter defines which type of data will a parameter store. You can compare
path converters with data types. In the above example, the path converter will be
int.
2. You will learn more about various path converters in the upcoming sections.
3. URL parameter name will be the name that you will use to refer to the parameter.
4. The view_name will be the view that will handle the request and the function_name
is the function that will be executed when the request is made to the specified URL
endpoint.
5. The name will be the name of the path that you are going to create.
11/3/23 Priya Singh Python web development with Django Unit IV 49
Sending data from view to template

We will talk about passing dynamic data to templates for rendering it.

Ø As we know django is a MVC framework. So, we separate business logic


from presentational logic. We write business logic in views and we pass
data to templates to present the data.

Ø The data that we pass from views to template is generally called as


"context" data. Let's get started with an example.

Ø Let's write a simple view that takes user information such as first name,
last name and address and renders it in the template.

11/3/23 Priya Singh Python web development with Django Unit IV 50


Sending data from view to template

11/3/23 Priya Singh Python web development with Django Unit IV 51


Sending data from view to template

11/3/23 Priya Singh Python web development with Django Unit IV 52


Sending data from view to template

Ø “Render" is the most used function in django. It combines a given template


with a given context dictionary and returns an HttpResponse object with
that rendered text.
Ø It takes three arguments "request", "template_name" and "context"
dictionary.
Ø In template we can access the context dict keys as names**or variables**
and display them like "{{ <variable/name>}}".
Ø Django provides a template tag "for" to provide the for loop functionality in
django templates. You can find the “for loop” syntax below.
Ø {% for local_name in iterable_name %}
Ø {{ local_name }}
Ø {% endfor %}
11/3/23 Priya Singh Python web development with Django Unit IV 53
Saving objects into database
//ONE LINE SYNTAX TO SAVE DATA

person = Person.objects.create(first_name="John", last_name="Deo")

//YOU CAN ALSO USE BELOW CODE TO SAVE DATA

person = Person(first_name="John", last_name="Deo")


person.save()
ü Creating or saving object data in Django is very simple and it can be achieved using
the provided code snippet. In the code snippet, we are using a 'Person' model which
has fields named 'first_name' and 'last_name'. The above code will insert data into
the table where 'John' will be inserted in the 'first_name' column and 'Deo' will be
inserted into the 'last_name' column.
11/3/23 Priya Singh Python web development with Django Unit IV 54
Sorting objects, Filtering objects, Deleting objects

11/3/23 Priya Singh Python web development with Django Unit IV 55


Sorting objects, Filtering objects, Deleting objects

11/3/23 Priya Singh Python web development with Django Unit IV 56


Sorting objects, Filtering objects, Deleting objects

11/3/23 Priya Singh Python web development with Django Unit IV 57


Session and Cookie
Ø Cookies, technically called HTTP Cookies are small text files which are created and
maintained by your browser on the particular request of Web-Server. They are stored
locally by your browser, and most browser will also show you the cookies generated
in the Privacy and Security settings of the browser.
Ø HTTP is a stateless protocol. When any request is sent to the server, over this protocol,
the server cannot distinguish whether the user is new or has visited the site
previously.

Ø Suppose, you are logging in any website, that website will respond the browser with
some cookies which will have some unique identification of user generated by the
server and some more details according to the context of the website.
Ø Cookies made these implementations possible with ease which were previously not
possible over HTTP implementation.

11/3/23 Priya Singh Python web development with Django Unit IV 58


Session and Cookie
How do Cookies work?
Cookies work like other HTTP requests over the Internet. In a typical web-system, the
browser makes a request to the server. The server then sends the response along
with some cookies, which may contain some login information or some other data.
When the browser makes a new request, the cookie generated previously is also
transmitted to the server. This process is repeated every time a new request is made
by the browser.

The browser repeats the process until the cookie expires or the session is closed and
the cookie is deleted by the browser itself.
Then, the cookie applies in all sorts of tasks, like when your login to a website or
when shopping online on the web. Google AdSense and Google Analytics can also
track you using the cookies they generate. Different websites use cookies differently
according to their needs.
11/3/23 Priya Singh Python web development with Django Unit IV 59
Session and Cookie
What are Sessions?
ü After observing these problems of cookies, the web-developers came with a new and more
secure concept, Sessions.
ü The session is a semi-permanent and two-way communication between the server and the
browser.
ü Let’s understand this technical definition in detail. Here semi means that session will exist until
the user logs out or closes the browser. The two-way communication means that every time
the browser/client makes a request, the server receives the request and cookies containing
specific parameters and a unique Session ID which the server generates to identify the user. The
Session ID doesn’t change for a particular session, but the website generates it every time a
new session starts.
ü Generally, Important Session Cookies containing these Session IDs deletes when the session
ends. But, this won’t have any effect on the cookies which have fix expire time.
ü Making and generating sessions securely can be a hefty task, and now we will look at Django’s
implementation of the same.

11/3/23 Priya Singh Python web development with Django Unit IV 60


Creating sessions and cookies in Django.
Creating Cookies in Django

Django bypasses lots of work which otherwise would be required when working
on cookies. Django has methods like set_cookie() which we can use to create
cookies very easily.
The set_cookie() has these attributes:

11/3/23 Priya Singh Python web development with Django Unit IV 61


Creating sessions and cookies in Django

11/3/23 Priya Singh Python web development with Django Unit IV 62


Creating sessions and cookies in Django

11/3/23 Priya Singh Python web development with Django Unit IV 63


Creating sessions and cookies in Django

11/3/23 Priya Singh Python web development with Django Unit IV 64


Creating sessions and cookies in Django
Creating & Accessing Django Sessions

Django allows you to easily create session variables and manipulate them accordingly.
The request object in Django has a session attribute, which creates, access and edits the
session variables. This attribute acts like a dictionary, i.e., you can define the session names
as keys and their value as values.
Step 1. We will start by editing our views.py file. Add this section of code.

11/3/23 Priya Singh Python web development with Django Unit IV 65


Creating sessions and cookies in Django

11/3/23 Priya Singh Python web development with Django Unit IV 66


Daily Quiz

1. Discuss database migration.


2. What is the role of frameworks in python.
3. Discuss any three frameworks.
4. Discuss about concept and process of database migration.
5. Discuss implementation rule session and cookies in django.
6. Discuss the session and cookies.
7. Discuss how to save a object in data base .
8. Discuss the application area of django.
9. Discuss about the Request Http methods in Python.
10. Discuss about http application.

Priya Singh Python web development with Django Unit IV


11/3/23 67
Weekly Assignment

1. What are the most important uses of Django.


2. What are the disadvantages of Django?
3. What are the different data types used in Django.
4. What are the salient features of Django session and cookies.
5. What are some of the technical features that Django includes

11/3/23 Priya Singh Python web development with Django Unit IV 68


Topic Link ( YouTube & NPTEL Video Links)

YouTube /other Video Links


• https://youtu.be/eoPsX7MKfe8?list=PLIdgECt554OVFKXRpo_kuI0XpUQKk0ycO

• https://youtu.be/tA42nHmmEKw?list=PLh2mXjKcTPSACrQxPM2_1Ojus5HX88ht7

• https://youtu.be/8ndsDXohLMQ?list=PLDsnL5pk7-N_9oy2RN4A65Z-PEnvtc7rf

• https://youtu.be/QXeEoD0pB3E?list=PLsyeobzWxl7poL9JTVyndKe62ieoN-MZ3

• https://youtu.be/9MmC_uGjBsM?list=PL3pGy4HtqwD02GVgM96-V0sq4_DSinqvf

11/3/23 Priya Singh Python web development with Django Unit IV 69


MCQ s
1. What is a Django App? 2. Django was introduced by
ADjango app is an extended package with base package
is Django A. Adrian Holovaty
B. Django app is a python package with its own B. Bill Gates
components. C. Rasmus Lerdorf
C. Both 1 & 2 Option D. Tim Berners-Lee
D. All of the above
3. What are Migrations in Django
A. They are files saved in migrations directory.
B. They are created when you run make migrations
command.
C. Migrations are files where Django stores changes to
your models.
D. All of the above
4. Which architectural pattern does django follow
APHP
B. MVT
C. HTML Priya Singh Python web development with Django Unit IV
11/3/23 70
D. None of the above
MCQ s

which of these is not a valid backend for caching in django


A. Django.core.cache.backends.sys.memory
B. django.core.cache.backends.db.DatabaseCache
C. django.core.cache.backends.locmem.LocMemCache
D. None of the above
5. Which architectural pattern does django follow
A.PHP
B. MVT
C. HTML
D. None of the above

11/3/23 Priya Singh Python web development with Django Unit IV 71


MCQ s
6. Python is a : 7. Python is Case Sensitive when dealing with
§Development environment Identifiers?
§Set of editing tools §Yes
§Programming Language §No
§Sometimes Only
§None Of the Above

8. What is the OUTPUT of the following Statement? 9. What is the OUTPUT when the following
print 0xA + 0xB + 0xC : Statement is executed?
§0xA0xB0xC “abc”+”xyz”
§33 §abc
§ABC §abcxyz
§000XXXABC §abcz
§abcxy

10.what is the type of a? a={1,2:3} list


set
dict Priya Singh Python web development with Django Unit IV
11/3/23 72
syntax error
Glossary Questions
Top 10 design pattern interview questions

1. Explain Django Architecture?


2. Explain the Django project directory structure?
3. What are models in Django?
4. What are templates in Django or Django template language?
5. What are views in Django?
6. What is Django ORM?
7. What is Django Rest Framework(DRF)?
8. What is the difference between a project and an app in Django?
9. What are different model inheritance styles in the Django?
10.What are Django Signals?
11/3/23 Priya Singh Python web development with Django Unit IV 73
Expected Questions for University Exam
Top 10 design pattern interview questions

1. Explain Django Architecture?


2. Explain the Django project directory structure?
3. What are models in Django?
4. What are templates in Django or Django template language?
5. What are views in Django?
6. What is Django ORM?
7. What is Django Rest Framework(DRF)?
8. What is the difference between a project and an app in Django?
9. What are different model inheritance styles in the Django?
10.What are Django Signals?
11/3/23 Priya Singh Python web development with Django Unit IV 74
Unit V Content
• Creating a functional website in Django.
• Four Important Pillars to Deploy.
• Registering on Heroku and GitHub, Push project from Local System to
GitHub.
• Working with Django Heroku.
• Working with Static Root.
• Handling WSGI with gunicorn.
• Setting up Database & adding users.

11/3/23 Priya Singh Python web development with Django Unit V 26


Unit V Objective

In Unit V, the students will be able to find


• Define Four Important Pillars to Deploy.
• How to Registering on Heroku and GitHub .
• Working with Django Heroku.
• What is WSGI and relationship with gunicorn.
• Setting up Database & adding users.

Priya Singh Python web development with Django Unit V


11/3/23 27
Topic Objective

Topic : Collection— Creating a functional website in Django

• In this topic, the students will gain , The idea of Having a website
helps grow an online presence, whether that be your personal blog
or business, by connecting you with a broader audience. A website
can also become a platform for sharing your opinions and skills,
creating opportunities for personal or work-related projects.

11/3/23 Priya Singh Python web development with Django Unit V 28


Creating a functional website in Django

Ø Having a website helps grow an online presence, whether that be your personal
blog or business, by connecting you with a broader audience. A website can also
become a platform for sharing your opinions and skills, creating opportunities
for personal or work-related projects.

Ø This lecture will help you turn your website idea into a fully-functional website –
pick a suitable platform, get a web hosting plan, and choose a memorable
domain name. We’ll also give you tips on how to optimize it.

Ø Before creating your first website, you need to understand these three essential
elements – what’s a website building platform, web hosting, and a domain
name.
11/3/23 Priya Singh Python web development with Django Unit V
29
Creating a functional website in Django

Priya Singh Python web development with Django Unit V


11/3/23 30
Four Important Pillars to Deploy
Pillar One: Technology
Ø Front and backend development processes can drastically affect the
overall performance of your site. Visitors are mostly affected by
frontend site performance, e.g. the way that your site performs
when a user goes to the homepage or clicks on an internal link. It’s
the most visible indicator of site performance, because it’s pretty
obvious if a user is staring at a blank screen for 5-10 seconds, that a
site isn’t performing at its peak.
Ø When you change a piece of tech, add a new feature, or even update
an existing plugin, you should always test your performance to see if
it was negatively impacted. That way you can continue to upgrade
your tech, while also improving overall performance.
Priya Singh Python web development with Django Unit V
11/3/23 31
Four Important Pillars to Deploy

Ø Where you host your site also has a huge impact on frontend and backend
performance. Check what kind of performance-enhancing features your host
might offer, like caching or a global CDN. Having these kinds of features with
your host can really take the burden off of your internal development team.

Ø While a lot of updates add new functions or improve the performance of their
particular piece of software, we’re all familiar with how one seemingly
miniscule update can bring even the most immaculately maintained site to its
knees. This, of course, will have terrible effects on your site performance. As
you continue to update individual pieces of your site, you need to remember to
maintain the whole, or find a partner to perform regular site maintenance.

Priya Singh Python web development with Django Unit V


11/3/23 32
Four Important Pillars to Deploy

Pillar Two: UX and Usability

Ø The basic goal of UX work is to reduce friction, i.e. to make the experience
feel as seamless and smooth as possible. Believe it or not, friction is
actually a measurable datapoint.

Ø There are plenty of frameworks that exist to measure friction. One of the
easiest ways is to observe users interacting with your site. Perform an
evaluation on your site to see where exactly users are experiencing
friction, and where you can improve. Some of the most common areas of
friction are:
Priya Singh Python web development with Django Unit V
11/3/23 33
Four Important Pillars to Deploy

Ø Page speed is a huge indicator for how happy a user will be on your site.
After all, if a page never loads, how can you ever see if it actually converts?

Ø Constantly getting sold and marketed to has made users numb to the sales-
centric copywriting of days past.

Ø Now users just want the information they’re looking for explained clearly
and concisely. Try combing through your site and look for ways to improve
CTAs, menus, and headers. You’d be surprised at the impact a seemingly
tiny change can have.

11/3/23 Priya Singh Python web development with Django Unit V 34


Four Important Pillars to Deploy

Pillar Three: Conversions

Ø Conversion can mean a lot of different things. Is your site converting visitors into
leads? Leads into customers? Are users converting from one page to another? Filling
out a form? There are plenty of ways to define conversions. Put plainly, if your site
isn’t converting, is it really performing the way it should?

Ø That wasn’t a rhetorical question. Of course it’s not! Every pillar of performance is
connected, and if users aren’t converting, your technology or user experience is
probably lacking. So what can you do? Make some changes! Of course, those
changes don’t mean anything if you’re not…

Ø (Always Be Testing)

11/3/23 Priya Singh Python web development with Django Unit V 35


Four Important Pillars to Deploy

Pillar Four: Retention

Ø Which costs more? Attracting a new customer, or reselling to an existing one? Not
surprisingly, keeping existing customers happy is a lot less expensive than attracting
new ones. A large part of keeping existing customers happy depends on your
platform and how it performs, not just when the initial sale gets made, but as
customers continue to interact with your business.

Ø Retention and churn are often seen as an issue of platform or service, but in reality
churn can be attributed to something much more simple: attracting the wrong
customer. When you spend your time creating a great user experience, speedy
website, testing changes, and collecting data, you attract the right customer to your
product. This means less churn and more long-term customer success.

11/3/23 Priya Singh Python web development with Django Unit V 36


Django Middleware

• In Django, middleware is a lightweight plugin that processes during request


and response execution. Middleware is used to perform a function in the
application. The functions can be a security, session, csrf protection,
authentication etc.
• Django provides various built-in middleware and also allows us to write our
own middleware. See, settings.py file of Django project that contains various
middleware, that is used to provides functionalities to the application. For
example, Security Middleware is used to maintain the security of the
application.

Priya Singh Python web development with Django


11/3/23 37
Unit V
Custom middleware in Django

Custom middleware in Django is created either as a function style that takes a


get_response callable or a class-based style whose call method is used to
process requests and responses. It is created inside a file middleware.py. A
middleware is activated by adding it to the MIDDLEWARE list in Django
settings.

Very often you would have used request.user inside the view. Django
wants user attribute to be set on request before any view executes. Django takes
a middleware approach to accomplish this. So Django provides
an AuthenticationMiddleware which can modify the request object.

Priya Singh Python web development with Django


11/3/23 38
Unit V
Version Control System

• Version control systems are a category of software tools that helps in


recording changes made to files by keeping a track of modifications
done in the code.
• A version control system is a kind of software that helps the developer
team to efficiently communicate and manage(track) all the changes that
have been made to the source code along with the information like who
made and what changes have been made.

Priya Singh Python web development with Django


11/3/23 39
Unit V
WSGI and uWSGI
• WSGI: A Python spec that defines a standard interface for communication between
an application or framework and an application/web server. This was created in
order to simplify and standardize communication between these components for
consistency and interchangeability. This basically defines an API interface that can be
used over other protocols.

• uWSGI: An application server container that aims to provide a full stack for
developing and deploying web applications and services. The main component is an
application server that can handle apps of different languages. It communicates with
the application using the methods defined by the WSGI spec, and with other web
servers over a variety of other protocols. This is the piece that translates requests
from a conventional web server into a format that the application can process.

Priya Singh Python web development with Django


11/3/23 40
Unit V
Registering on Heroku and GitHub

HERUKO
Ø Heroku is one of the longest running and popular cloud-based PaaS services. It originally
supported only Ruby apps, but now can be used to host apps from many programming
environments, including Django.

Why to chose Heroku:


•Heroku has a free tier that is really free.
•As a PaaS, Heroku takes care of a lot of the web infrastructure for us. This makes it much
easier to get started, because you don't worry about servers, load balancers, reverse proxies,
or any of the other web infrastructure that Heroku provides for us under the hood.
•Some of the companies using Heroku are:
StackShare, Accenture, Product Hunt, Stitch Fix, MAK IT, Heroku, Pier, ReadMe.io.

11/3/23 Priya Singh Python web development with Django Unit V 41


Registering on Heroku and GitHub

So, what is Heroku and how does it work?


• Heroku runs Django websites within one or more "Dynos", which are isolated, virtualized
Unix containers that provide the environment required to run an application. The dynos are
completely isolated and have an ephemeral file system (a short-lived file system that is
cleaned/emptied every time the dyno restarts).
• The only thing that dynos share by default are application configuration variables. Heroku
internally uses a load balancer to distribute web traffic to all "web" dynos.
• Since nothing is shared between them, Heroku can scale an app horizontally by adding
more dynos.
• Because the file system is ephemeral you can't install services required by your application
directly. Instead Heroku web applications use backing services provided as independent
"add-ons" by Heroku or 3rd parties.

11/3/23 Priya Singh Python web development with Django Unit V 42


Registering on Heroku and GitHub
In order to execute your application Heroku needs to be able to set up the appropriate
environment and dependencies, and also understand how it is launched. For Django apps we
provide this information in a number of text files:
•runtime.txt: the programming language and version to use.
•requirements.txt: the Python component dependencies, including Django.
•Procfile: A list of processes to be executed to start the web application. For Django this will
usually be the Gunicorn web application server (with a wsgi script).
•wsgi.py: WSGI configuration to call our Django application in the Heroku environment.

In order to get our application to work on Heroku we'll need to put our Django web application
into a git repository, add the files above, integrate with a database add-on, and make changes
to properly handle static files.
Once we've done all that we can set up a Heroku account, get the Heroku client, and use it to
install our website.

11/3/23 Priya Singh Python web development with Django Unit V 43


Registering on Heroku and GitHub
Why use Heroku when AWS is present?

Ø Heroku runs on Amazon Web Services (AWS).

Ø AWS is an Infrastructure as a Service(IaaS) provider, meaning they are responsible for


managing large, shared data centers. These data centers are what we call “the cloud”.
Companies like AWS, Azure, and Google have all created IaaS so that developers can pay to
host their applications in these data centers instead of building servers themselves.

Ø This is a great trade-off but due to the nature of their business, IaaS providers are more
concerned with running the data centers than the developer’s experience working with
them. This means there is a high level of knowledge of AWS is required to keep your apps
running, especially at scale.

11/3/23 Priya Singh Python web development with Django Unit V 44


Registering on Heroku and GitHub

Ø Heroku, on the other hand, is a Platform as a Service that sits on top of AWS
to provide an experience that is specifically designed to make developers
lives easier. For example, in order to keep an application running at scale on
Heroku, it only takes knowledge of a few commands on the Heroku CLI and
Dashboard.

Ø These commands can easily be found in Heroku’s documentation. Again,


Heroku was built by developers for developers. The experience is easy to
navigate, developers know exactly what they need to do when they log in,
and they know exactly how their application is running every second the
platform.

11/3/23 Priya Singh Python web development with Django Unit V 45


Registering on Heroku and GitHub

What is GitHub And How To Use It?

Ø GitHub is an increasingly popular programming resource used for code sharing. It's a
social networking site for programmers that many companies and organizations use to
facilitate project management and collaboration.

Ø According to statistics collected in October 2020, it is the most prominent source code
host, with over 60 million new repositories created in 2020 and boasting over 56
million total developers.

Ø GitHub is a Git repository hosting service that provides a web-based graphical


interface. It is the world’s largest coding community. C language is mainly used in Git.

11/3/23 Priya Singh Python web development with Django Unit V 46


Registering on Heroku and GitHub
§ GitHub helps every team member work together on a project from any location while
facilitating collaboration. You can also review previous versions created at an earlier point
in time.
§ Features:
1. Easy Project Management
GitHub is a place where project managers and developers come together to coordinate,
track, and update their work so that projects are transparent and stay on schedule.
2. Increased Safety With Packages
Packages can be published privately, within the team, or publicly to the open-source
community. The packages can be used or reused by downloading them from GitHub.
3. Effective Team Management
GitHub helps all the team members stay on the same page and organized. Moderation tools
like Issue and Pull Request Locking help the team to focus on the code.

11/3/23 Priya Singh Python web development with Django Unit V 47


Commands that helps to push your files to GitHub repository
•git init

•git add

•git commit -m "Add existing project files to Git“

•git remote add origin https://github.com/cameronmcnz/example-website.git

•git push -u -f origin master

Priya Singh Python web development with Django


11/3/23 48
Unit V
Priya Singh Python web development with Django
11/3/23 49
Unit V
.gitignore File
Agitignore file specifies intentionally untracked files that Git should ignore. Files already tracked
by Git are not affected; see the NOTES below for details.
Each line in a gitignore file specifies a pattern. When deciding whether to ignore a path, Git
normally checks gitignore patterns from multiple sources, with the following order of precedence,
from highest to lowest (within one level of precedence, the last matching pattern decides the
outcome):
• Patterns read from the command line for those commands that support them.
• Patterns read from a .gitignore file in the same directory as the path, or in any parent directory
(up to the top-level of the working tree), with patterns in the higher level files being overridden by
those in lower level files down to the directory containing the file. These patterns match relative to
the location of the .gitignore file. A project normally includes such .gitignore files in its
repository, containing patterns for files generated as part of the project build.
• Patterns read from$GIT_DIR/info/exclude.
• Patterns read from the file specified by the configuration variable core.excludesFile.

Priya Singh Python web development with Django


11/3/23 50
Unit V
Push project from Local System to GitHub

11/3/23 Priya Singh Python web development with Django Unit V 51


Working with Django Heroku
How to Deploy Django application on Heroku ?
Django is an MVT web framework used to build web applications. It is robust,
simple, and helps web developers to write clean, efficient, and powerful
code. In this lecture, we will learn how to deploy a Django project on Heroku
in simple steps. For this, a Django project should be ready.
Heroku account

1. Install your Heroku toolbelt which you can find here:


https://toolbelt.heroku.com
2. Authenticate your Heroku account either running the below command in
cmd or gitbash
$heroku login
11/3/23 Priya Singh Python web development with Django Unit V 52
Working with Django Heroku

11/3/23 Priya Singh Python web development with Django Unit V 53


Working with Static Root

11/3/23 Priya Singh Python web development with Django Unit V 54


Working with Static Root

11/3/23 Priya Singh Python web development with Django Unit V 55


Working with Static Root

11/3/23 Priya Singh Python web development with Django Unit V 56


Working with Static Root

11/3/23 Priya Singh Python web development with Django Unit V 57


Working with Static Root

11/3/23 Priya Singh Python web development with Django Unit V 58


Working with Static Root

11/3/23 Priya Singh Python web development with Django Unit V 59


Working with Static Root

11/3/23 Priya Singh Python web development with Django Unit V 60


Handling WSGI with gunicorn

Gunicorn - WSGI server:-

Gunicorn ‘Green Unicorn’ is a Python WSGI HTTP Server for UNIX. It’s a pre-fork
worker model ported from Ruby’s Unicorn project. The Gunicorn server is broadly
compatible with various web frameworks, simply implemented, light on server
resources, and fairly speedy.
Features
Natively supports WSGI, Django, and Paster
Automatic worker process management
Simple Python configuration
Multiple worker configurations
Various server hooks for extensibility
Compatible with Python 3.x >= 3.5

11/3/23 Priya Singh Python web development with Django Unit V 61


Handling WSGI with gunicorn

Ø Gunicorn is a stand-alone WSGI web application server which offers a lot of


functionality. It natively supports various frameworks with its adapters, making it an
extremely easy to use drop-in replacement for many development servers that are
used during development.

Ø Technically, the way Gunicorn works is very similar to the successful Unicorn web
server for Ruby applications. They both use what’s referred to as the pre-fork
model. This, in essence, tasks the central [Gunicorn] master process to handle the
management of workers, creation of sockets and bindings, etc.

Ø Nginx is a very high performant web server / (reverse)-proxy. It has reached its
current popularity due to being light weight, relatively easy to work with, and easy
to extend (with add-ons / plug-ins).

11/3/23 Priya Singh Python web development with Django Unit V 62


Setting up Database & adding users

Ø There are several ways to extend the the default Django User model. Perhaps one
of the most common way (and also less intrusive) is to extend the User model
using a one-to-one link.

Ø This strategy is also known as User Profile. One of the challenges of this particular
strategy, if you are using Django Admin, is how to display the profile data in the
User edit page. And that’s what this tutorial is about.

Ø Then a very important thing, we need to override the get_inline_instances


method, so to display the inlines only in the edit form. Otherwise we might get
some problems because of how the Signals work. Remember that the Signal is
responsible for creating the Profile instance.

11/3/23 Priya Singh Python web development with Django Unit V 63


Setting up Database & adding users

11/3/23 Priya Singh Python web development with Django Unit V 64


Daily Quiz

1. Discuss Four Important Pillars to website.


2. What is the role of frameworks in python.
3. Discuss any three frameworks.
4. What is Heroku, explain its architecture.
5. Discuss WSGI .
6. Explain gunicorn .
7. Discuss the role of Git .
8. Discuss the architecture of Git.
9. Discuss about the Request Http methods in Python.
10. Discuss about Flask application.

Priya Singh Python web development with Django Unit V


11/3/23 65
Weekly Assignment

1. What are the most important pillar of website .


2. What are the disadvantages of Django?
3. What are the different data types used in Django.
4. What are the salient features of Django.
5. What are some of the technical features that Django includes

11/3/23 Priya Singh Python web development with Django Unit V 66


Topic Link ( YouTube & NPTEL Video Links)

YouTube /other Video Links


• https://youtu.be/eoPsX7MKfe8?list=PLIdgECt554OVFKXRpo_kuI0XpUQKk0ycO

• https://youtu.be/tA42nHmmEKw?list=PLh2mXjKcTPSACrQxPM2_1Ojus5HX88ht7

• https://youtu.be/8ndsDXohLMQ?list=PLDsnL5pk7-N_9oy2RN4A65Z-PEnvtc7rf

• https://youtu.be/QXeEoD0pB3E?list=PLsyeobzWxl7poL9JTVyndKe62ieoN-MZ3

• https://youtu.be/9MmC_uGjBsM?list=PL3pGy4HtqwD02GVgM96-V0sq4_DSinqvf

11/3/23 Priya Singh Python web development with Django Unit V 67


MCQ s
1. What is a Django App? 2. Django was introduced by
ADjango app is an extended package with base package
is Django A. Adrian Holovaty
B. Django app is a python package with its own B. Bill Gates
components. C. Rasmus Lerdorf
C. Both 1 & 2 Option D. Tim Berners-Lee
D. All of the above
3. What are Migrations in Django
A. They are files saved in migrations directory.
B. They are created when you run make migrations
command.
C. Migrations are files where Django stores changes to
your models.
D. All of the above
4. Which architectural pattern does django follow
APHP
B. MVT
C. HTML Priya Singh Python web development with Django Unit V
11/3/23 68
D. None of the above
MCQ s

which of these is not a valid backend for caching in django


A. Django.core.cache.backends.sys.memory
B. django.core.cache.backends.db.DatabaseCache
C. django.core.cache.backends.locmem.LocMemCache
D. None of the above
5. Which architectural pattern does django follow
A.PHP
B. MVT
C. HTML
D. None of the above

11/3/23 Priya Singh Python web development with Django Unit V 69


MCQ s
6. Python is a : 7. Python is Case Sensitive when dealing with
§Development environment Identifiers?
§Set of editing tools §Yes
§Programming Language §No
§Sometimes Only
§None Of the Above

8. What is the OUTPUT of the following Statement? 9. What is the OUTPUT when the following
print 0xA + 0xB + 0xC : Statement is executed?
§0xA0xB0xC “abc”+”xyz”
§33 §abc
§ABC §abcxyz
§000XXXABC §abcz
§abcxy

10.what is the type of a? a={1,2:3} list


set
dict Priya Singh Python web development with Django Unit V
11/3/23 70
syntax error
Glossary Questions
Top 10 design pattern interview questions

1. Explain Django Architecture?


2. Explain the Django project directory structure?
3. What are models in Django?
4. What are templates in Django or Django template language?
5. What are views in Django?
6. What is Django ORM?
7. What is Django Rest Framework(DRF)?
8. What is the difference between a project and an app in Django?
9. What are different model inheritance styles in the Django?
10.What are Django Signals?
11/3/23 Priya Singh Python web development with Django Unit V 71
Expected Questions for University Exam
Top 10 design pattern interview questions

1. Explain Django Architecture?


2. Explain the Django project directory structure?
3. What are models in Django?
4. What are templates in Django or Django template language?
5. What are views in Django?
6. What is Django ORM?
7. What is Django Rest Framework(DRF)?
8. What is the difference between a project and an app in Django?
9. What are different model inheritance styles in the Django?
10.What are Django Signals?
11/3/23 Priya Singh Python web development with Django Unit V 72

You might also like