Introduction
to
Django
1
Agend
01 a
What is a Web Framework?
02
What is a Django?
03
History of Django
04
Features of Django
05
Django Installation
2
What is Web Framework?
“ Web framework is a set of components designed
simplify
to
basic
structuring
your web development process. It has
tools in it, which serve as a solid base for
your project. It allows you to focus on the most
important details and project’s goals instead of
creating things, that you can simply pull out of the
framework.
3
What is Django?
Django is a web It takes less time to build
01 application framework 04 application after
written in Python collecting client
programming language. requirement.
It is based on MVT This framework uses
02 (Model View Template) 05 faamous tag line: The web
design pattern. framework for
perfectionists with deadlines.
The Django is very
03 demanding due to its
rapid development
feature.
4
History
Publicly released 2.0 version is
under BSD launched
license.
2003 2005 2008 2017 2018
Django was design 1.0 version is Its current stable
and developed by launched version 2.0.3 is
Lawrence journal launched.
world.
5
Version Date Description
0.90 16 Nov 2005
0.91 11 Jan 2006 magic removal
0.96 23 Mar 2007 newforms, testing tools
1.0 3 Sep 2008 API stability, decoupled admin, unicode
1.1 29 Jul 2009 Aggregates, transaction based tests
Multiple db connections, CSRF,
1.2 17 May 2010
model validation
Timezones, in browser testing,
1.3 23 Mar 2011
app templates.
1.5 26 Feb 2013 Python 3 Support, configurable user model
Dedicated to Malcolm Tredinnick, db
1.6 6 Nov 2013 transaction management,
connection pooling.
6
Migrations, application loading
1.7 2 Sep 2014
and configuration.
Migrations, application loading and
1.8 LTS 2 Sep 2014
configuration.
Native support for multiple template
1.8 LTS 1 Apr 2015
engines.Supported until at least April
2018
Automatic password validation. New styling
1.9 1 Dec 2015
for admin interface.
Full text search for PostgreSQL. New-style
1.10 1 Aug 2016
middleware.
Last version to support Python
1.11 LTS 1.11 LTS
2.7.Supported until at least April
2020
First Python 3-only release, Simplified URL
2.0 Dec 2017
routing syntax, Mobile friendly admin.
7
Features of Django
Versatil
e
Rapid
Development
Scalabl Open
e Source
Vast and
Secur Supported
e Community
8
Django Installation
To install Django, first visit to django official site (https://
www.djangoproject.com) and download django by clicking
on the download section. Here, we will see various options
to download The Django.
Django requires pip to start installation. Pip is a
package manager system which is used to install and
manage packages written in python. For Python 3.4 and
higher versions pip3 is used to manage packages.
9
Django Installation
In this tutorial, we are installing Django in
Ubuntu operating system.
The complete installation process is described
below.
Before installing make sure pip is installed in local
system.
Here, we are installing Django using pip3, the
installation 10
$ pip3 install django==2.0.3
11
Verify Django Installation
After installing Django, we need to verify the installation. Open terminal
and write python3 and press enter. It will display python shell where we
can verify django installation.
12
Django Project
In the previous topic, we have installed Django successfully.
Now, we will learn step by step process to create a Django
application.
13
Django Project Example
Here, we are creating a project djangpapp in the current
directory.
$ django-admin startproject djangpapp
14
Locate into the Project
Now, move to the project by changing the directory. The
Directory can be changed by using the following command.
cd djangpapp
15
To see all the files and subfolders of django project, we can use
tree command to view the tree structure of the application.
This is a utility command, if it is not present, can be
downloaded via apt-get install tree command.
16
Running the Django Project
Django project has a built-in development server which
is used to run application instantly without any external
web server. It means we don't need of Apache or another
web server to run the application in development mode.
To run the application, we can use the following command.
$ python3 manage.py runserver
17
18
Look server has started and can be accessed at localhost
with port 8000. Let's access it using the browser, it looks
like the below.
19
MTV Framework
Model - Data access layer.
This deals with access, validation and relationships among data. Models
are Python classes that mediate between Django ORM and the
database tables.
Template - Presentation layer.
This deals with how data is displayed to the client.
View - Business logic layer.
This is a bridge between models and templates. A view
accesses model data and redirects it to a template for
presentation. Unlike the definition of a view in traditional MVC
architecture, a Django view describes which data you see, not how you
see it. It's about processing, not presentation.
MTV Framework
MTV Framework
MTV Framework
Django ORM
Django ORM
Getting Started with Django
$ python manage.py startapp polls
polls/
init .py
admin.py
apps.py
migrations/
init
.py
models.py
tests.py
views.py
Django Project Layout
Django Project Layout
mysite/
manage.py
mysite/
init
.py
settings.py
urls.py
wsgi.py
polls/
init .py
admin.py
migrations/
init .py
0001_initial.py
models.py
static/
polls/
images/
background.gif
style.css
t
em
pl
at
es
/
p
ol
ls
/
detail.h
tml
index.html
results.html
Getting Started with Django
polls/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world.
You're at the polls index.")
Getting Started with Django
polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',
views.index,
name='index'),
]
Getting Started with Django
mysite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
Getting Started with Django
The path() function is passed four
arguments, two required: route and view, and two
optional: kwargs, and name. At this point, it’s
worth reviewing what these arguments are for.
path() argument: route
route is a string that contains a URL pattern.
When processing a request, Django starts at the
first pattern in urlpatterns and makes its way
down the list, comparing the requested URL
against each pattern until it finds one that
matches.
DJANGO
MODELS
AND
DATABASE
34
Agenda
01 What is Model 02 Create First Model
03 Model Fields 04 Databases
35
What is Model?
A model is the single, definitive source of information
about your data.
It contains the essential fields and behaviors of the
data
you’re storing
Generally, each model maps to a single database table.
Each model is a Python class that
subclasses django.db.models.Model.
Each attribute of the model represents a database field.
36
CREATE YOUR FIRST MODEL
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
37
MODEL FIELDS
Fields are organized into records, which contain all the
information within the table relevant to a specific
entity.
There are concepts to know before creating fields:
Field
Field Relationshi
Option
Type p
s
38
1. FIELD TYPE
The fields defined inside the Model class are the columns
name of the mapped table
E.g.
AutoField() BooleanField() CharField()
An integer Store true/false A string
field that value and field for
automatically generally used small to
increments for checkboxes large-sized
strings.
DateField()
A date field
represents
python
datetime.
date instance. 253
9
2. FIELD OPTIONS
Field option are used to customize and put constraint on
the table rows.
E.g.
name= models.CharField(max_length = 60)
here "max_length" specifies the size of the VARCHAR field.
40
The following are some common and mostly used field
option:
01 Null
02 Blank
to store empty if True, the field
values as NULL in s allowed to be
database. blank.
05 unique_key
03 default 04 primary_key
puts unique key
constraint for
store default this field will be column.
value for a the primary key
field for the table
41
3. MODEL FIELD RELATIONSHIP
The power of relational databases lies in relating tables to
each other Django offers ways to define the three most
common types of database relationships:
1. many-to-one
2. many-to-many
3. one-to-one.
42
1) Many-to-one relationships:
To define a many-to-one relationship, use
django.db.models.ForeignKey.
You use it just like any other Field type: by including it as a
class attribute of your model.
E.g.
class Manufacturer(models.Model)
pass
class Car(models.Model):
manufacturer = models.ForeignKey(Manufacturer,
on_delete=models.CASCADE)
43
2) Many-to-many relationships
To define a many-to-many relationship, use ManyToManyField.
You use it just like any other Field type: by including it as
a class attribute of your model.
For example, if a Pizza has multiple Topping objects – that is, a
Topping can be on multiple pizzas and each Pizza has multiple
toppings – here’s how you’d represent that:
44
from django.db import
models
class Topping(models.Model):
# ...
pass
class Pizza(models.Model):
# ...
toppings = models.ManyToManyField(Topping)
45
3) One-to-one relationships
To define a one-to-one relationship, use OneToOneField. You
use it just like any other Field type: by including it as a
class attribute of your model.
E.g.
from django.conf import
settings from django.db import
models
class
MySpecialUser(models.Model):
user =
models.OneToOneField(set 46
Meta Option
A metaclass is the class of a class.
A class defines how an instance of the class behaves
while a metaclass defines how a class behaves.
A class is an instance of a metaclass.
Give your model metadata by using an inner class Meta.
47
E.g.
from django.db import models
class Student(models.Model):
name = models.CharField(max_length =50)
class Meta:
ordering =["name"]
db_table = "students"
48
Databases
Django officially
supports the
following databases:
49
Telling Django About Your Database
Before we can create any models, we must first setup
our database configuration. To do this, open the settings.py
and locate the dictionary called DATABASES.
modify the default key/value pair so it looks something like
the following example.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': DATABASE_PATH,
}
}
50
Also create a new variable called DATABASE_PATH and
add
that to the top of your settings.py
DATABASE_PATH = os.path.join(PROJECT_PATH, 'rango.db')
51