Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 23

Django Framework

Introduction

 a high-level python-based free and open-source web


framework 
 maintained by Django Software Foundation (DSF), an
independent organization based in the US
 It was created in the fall of 2003 when the web
programmers at the Lawrence Journal-World newspaper,
Adrian Holovaty and Simon Willson.
What is a framework?
 A Web framework is a collection of packages or modules which allow
developers to write web applications or services without having to handle such
low-level details as protocols, sockets or process/thread management.
 frameworks provide support for a number of activities such as interpreting
requests (getting form parameters, handling cookies and sessions), producing
responses (presenting data as HTML or in other formats), storing data
persistently, and so on.
 Examples:
 PHP Framework – Laravel, Phalcon, CakePHP, Zend etc
 Javascript Framework – AngularJS, React Native, Mojito, Meteor
 Java Framework – Spring, Hibernate, JSF(Java Server Faces), Struts
 Python Framework – Django, CherryPy, Bottle and Flask, Streamlit(Machine
Learning)
Django Architecture
Django Architecture
 Django follows the MVT (Model View Template) pattern which is
based on the Model View Controller architecture.
 Model
 A model provides the interface for the data stored in the Database.
 It is responsible for maintaining the data and handling the logical
data structure for the entire web application.
 Template
 A template contains the static parts of the desired HTML output as
well as some special syntax describing how dynamic content will be
inserted(Django Template Language (DTL).)
Django Architecture
 View (Controller)
  It acts as a bridge between Models and Templates

 The view is where you actually write code that generates web pages

 Responsible for handling all the business logic behind the web app

 It sees the user request,  retrieves appropriate data from the database,, then
renders back the template along with retrieved data.
 response can be HTML contents of a web page, or a redirect, or a 404
error, or an XML document, or an image, etc. 
Steps
1.The user sends a URL request for a
resource to Django.
2.Django framework then searches
for the URL resource.
3.If the URL path links up to a View,
then that particular View is called.
4.The View will then interact with
the Model and retrieve the
appropriate data from the database.
5.The View then renders back an
appropriate template along with the
retrieved data to the user.
django-admin and manage.py

 django-admin is Django’s command-line utility for


administrative tasks.
 manage.py file is automatically created in each Django
project.
 it performs the same purpose as the django-admin but it
also sets the DJANGO_SETTINGS_MODULE
environment variable to point to the project's
settings.py file.
 django project directory structure
• manage.py - A command-line utility that allows you
to interact with your Django project
• __init__.py - An empty file that tells Python that the
current directory should be considered as a Python
package
• settings.py - Comprises the configurations of the
current project like DB connections.
• urls.py - All the URLs of the project are present here
• wsgi.py - This is an entry point for your application
which is used by the web servers to serve the project
you have created
• asgi.py – This is used to execute Python apps via
asynchronous callables
wsgi vs asgi
 Web Server Gateway Interface  Asynchronous Server Gateway Interface
 The traditional way to deploy a By allowing the webserver to have an
Django application asynchronous callable, it can handle
multiple incoming and outgoing events
for each application.
• the ASGI specification in Python is a superset of WSGI and can be a drop-in
replacement for WSGI.
• Django allows for an “async outside, sync inside” mode that allows your code to
be synchronous internally, while the ASGI server handles requests asynchronously
• The Django application is still synchronous internally to allow for backward
compatibility and to avoid the complexity of parallel computing.
• Django app requires no changes to switch from WSGI to ASGI.
settings.py
 this file stores the configurations or settings of our Django project,
 like database configuration,
 backend engines,
 middlewares,
 installed applications,
 main URL configurations,
 static file addresses,
 templating engines,
 security keys,
 allowed hosts, and much more.
urls.py
 The django.urls module contains various functions,
path(route,view,kwargs,name) is one of those which is
used to map the URL and call the specified view.
 include() adds urls from your app directory's urls.py to
the main urls.py (in memory). This keeps the main
urls.py from getting too big to read.
 URLconf is a set of patterns that Django will try to
match the requested URL to find the correct view.
views.py

 In the Django framework, views are Python functions or


classes that receive a web request and return a web
response.
 The response can be a simple HTTP response, an HTML
template response, or an HTTP redirect response that
redirects a user to another page.
 Views hold the logic that is required to return information
as a response in whatever form to the user.
Class-based Views (Generic)
 Class-based views allow you to create views from inherited classes, thus making
coding the views much easier.
 Generally, there are five types of common class-based views (generic) that perform the
CRUD (create, retrieve(read), update, delete) operations for any common web app.
 All of these views involve operating on data via a model instance.
 At all times, a model instance is provided.
1. List View: generates a list of items in the model from the database
2. DetailView: used to display the data for a single record from the database.
3. CreateView :creates a new record in the database using the model instance.
4. UpdateView: performs an update operation to an existing record in the database.
5. Delete View :performs a delete operation on a single record in the database via
the specified model.
Function-based Views
 Function-based views are functions that return an HTTP response after executing the
required business logic of a certain view.
1. Simple HTTP Response:
 This is used in cases where the message is very simple—maybe just short text—
important, and the presentation does not matter.
def simple_http_response(request):
# perform business logic
return HttpResponse("Hello world from Django !")
2. HTTP Response Redirect:
 This redirect is used when the logic requires that after execution, the user is redirected
to another view. An example would be after deleting a record in a detail view, the page
redirects to the home page.
def delete_item(request, id):
#perform delete operation successfully
return HttpResponseRedirect(reverse('url_name_of_homepage'))
Function-based Views

3. Template Response:
 A template response is used when the response is complex and may
require further processing on the HTML side, such as displaying multiple
records via looping. This use case also requires proper presentation, so it
allows rendering of a HTML file.

def simple_template(request):
# perform business logic
return render(request"sports/simple_template.html", {})
models.py
from django.db import models class  A model in Django refers to a class
SampleModel(models.Model): that maps to a database table or
field1 = models.CharField(max_length = 50) database collection.
field2 = models.IntegerField()  Each attribute of the Django model
class represents a database field.
class Meta:  They are defined in app/models.py
db_table = “sample_model”
 Every model inherits from
django.db.models.Model
 The metaclass helps you set things
like available permissions, singular
and plural versions of the name,
associated database table name,
whether the model is abstract or not,
admin.py

 The admin.py file is used to display your models in the


Django admin panel.
 You can also customize your admin panel.
Django form's workflow 
CSRF
What is it ?
How does it work with Django ?
CSRF or Cross-Site Request Forgery
 is technique used by cyber-criminals to force users into executing
unwanted actions on a web application.
 in order to perform a CSRF attack all that's needed is for a user to have an
active session on a given site and a cyber-criminal crafty enough to trick
a user into clicking on a link or page that performs actions on said site.
 Hence the term's name: "Cross-Site", because the request doesn't come
from the original site, and "Request Forgery" because it's a forged request
by a cyber-criminal.
 Web forms must be equipped with a unique identifier -- often called a
CSRF token -- that's unique to a user and has an expiration time, similar
to a session identifier.
 if a request is made by an authenticated user to a site, only requests that
match his CSRF token are considered valid and all other requests are
discarded.
What is
CSRF ?
How csrf_token works?

You might also like