Django Ppts
Django Ppts
• Collections-Container datatypes,
• Tkinter-GUI applications,
• Requests-HTTP requests,
• BeautifulSoup4-web scraping,
• Scrapy, Zappa, Dash, CherryPy, TurboGears,
• Flask, Web2Py,
• Bottle, Falcon, CubicWeb, Quixote, Pyramid.
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.
Geometry Management
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
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.
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.
• 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
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….)
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
• 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.
• 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.
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.
• 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.
• 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
• This may take you far, especially while learning. As your application grows,
Pyramid offers many features that make writing complex software take less
effort.
• 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
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
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
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
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.
➢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.
➢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.
▪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.
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.
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.
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.
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.
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)
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'), )
• 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
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.
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
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“)
▪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.
Example –
from django.db import models
• 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
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 57
Priya Singh Python web development with Django Unit II
Django Models(continue….)
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.
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.
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:
• 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
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
➢ 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.
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.
❑ 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
❑ Versions 1.4.14, 1.5.x before 1.5.9, 1.6.x before 1.6.6, and 1.7 .
❑ 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
‘scache,causingthenameserver 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
9/11/2023 Priya Singh Python web development with Django Unit III 39
Security Problem & Solution with Django
Django’s Top 10 Vulnerabilities
❑ V
ersionsthrough1.2.7 and 1.3.x through 1.3.1
❑ CSRF is short for Cross Site Request Forgery, an attack that utilizes the
user’swebbrowsertoperformanunwantedactiononanotherwebsitein
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
9/11/2023 Priya Singh Python web development with Django Unit III 41
Security Problem & Solution with Django
Django’s Top 10 Vulnerabilities
❑ 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)
❑ Versions1.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
❑ V
ersionsbefore1.4.21, 1.5.x through 1.6.x, 1.7.x before 1.7.9, and 1.8.x
before 1.8.3
9/11/2023 Priya Singh Python web development with Django Unit III 43
Security Problem & Solution with Django
Django’s Top 10 Vulnerabilities
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.
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.
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')
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/
9/11/2023 Priya Singh Python web development with Django Unit III 50
Adding Email ,Configuring email & Sending emails with Django
➢ 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
offers4breakpoints:“large”,“medium”,“small”and“tiny”.Thesedeterminefor
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
aheadlet’sfirstsneakpeekaboutthelogindecoratorinDjangoRest
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=”htmlpage”)
➢ 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).
➢ 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
9/11/2023 Priya Singh Python web development with Django Unit III 68
Topic Link ( YouTube & NPTEL Video Links)
• 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
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
• 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.
Ø 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
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 :-
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
Ø 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.
Ø 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
Ø 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.
Ø 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:
Ø 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.
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.
Ø 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:
https://www.shop.tsinfo.com/products/12
We will talk about passing dynamic data to templates for rendering it.
Ø Let's write a simple view that takes user information such as first name,
last name and address and renders it in the template.
Ø 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.
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.
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:
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.
• 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
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
• 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.
Ø 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
Ø 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.
Ø 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.
Ø 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)
Ø 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.
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.
• 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.
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.
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.
Ø 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.
Ø 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.
Ø 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.
•git add
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
Ø 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).
Ø 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.
• 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
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