DJANGO
MO
ELS
What is a Model ?
Model is a data access layer of
0 Django.
1 It gives way to access it, validate it and
0 describes the relationship between the
data.
2
It maps single database table to a python
0 class.
3
0
4 It handles the inconsistency of SQL
across different platform.
Django ORM
Each Model is a python class that
01
0 subclasses django.db.models.Model
1
Each attribute of model represent a
02
0 database field
2
With all of this djan go gives you an
03
0 automat ically-generated database-access
3 API
Model Creation
Example
from django.db import mo dels
class Person(models.Mod l):
first_name = models.CharField(max_length=30)
last_name =
models.CharField(max_length=30)
Model
• Fields
Fields are specified by class attrib utes which represents columns
in the database table(Model)
• Each Field in model class should be an instance of appropriate
class(Which is an abstract class) Field
• These are the things to know reating model
for fields
Field Types Field Relationships
Options
Fields Types
AutoField() Boolean Field() DateField()
St o re A date field
An integer
true/false represents
field that
valu e and python
automatically
generally datetype.dat
increments
used e instance
for check
boxes
IntegerField() CharField() FloatField()
It stores value A string field It stores floating
from for small to point number
-2147483648 large sized represented in
to 2147483647 strin gs python by a
float instance
Special Field Type
EmailField()
A CharField that
check valid email
addre ss
Relationship
Fields
ForeignKey() ManyToManyField() OneToOneField()
A many to one Defines a many to Define a one-to-one
relationship many relationship relationship
requires one with another
positional argument model
to define related
model
Field Options
Field option are used to customiz e and put constraint on table
rows
Each field takes certain field specific arguments
Eg:
m
name = models.CharField( ax_length=60)
Here “max_length” specifies the size of the VARCHAR field
The following are some common and mostly used field options:
1 null
02 blank
If True, the field
To store empty
is allowed to be
values as NULL
blank. Default is
in database
False
05 unique_key
3 default 04 primary_key
Puts unique ke
constraint for
Stores default This key will be column
value for the the primary key
field for the table
Relationships
Django provides ways to define the three most common types
of database relationships:
01 many-to-one
02 many-to-many
03 Httpresponse
Choices
A sequence of 2-tuples to use as choices for this field.
The default form widget will be a select box instead of the standard text field
and will limit choices to the choices given.
choices list looks like this:
YEAR_IN_SCHOOL_CHOICES = [
('FR', 'Freshman’),
('SO', 'Sophomo e’),
('JR', 'Junior’),
('SR', 'Senior’),
('GR', 'Graduate’),
]
se PostgreSQL with your Django Application on
Ubunt
Django is a powerful web framework that can help you g
your Python application or website off the ground.
Django includes a simplified development server for
testi your code locally, butn for a ything even slightly
producti related, a more secure and powerful web server is
required.
rerequisites and Goals
w
. We will be installing Django ithin a virtual environment.
. Installing Django into an environment specific to your
project will allow your projects and their requirements to
be handled separately.
Install the Packages from the Ubuntu Repositories
To begin the process, we’ll download and install all of the items
we need from the Ubuntu repositories.
We will use the Python packag e manager pip to install
additional components a bit later.
We need to update the local apt p ckage index and then download
and install the packages.
The packages we install depend on which version of Python
your project will use.
If you are using Djan go with Python 3,
type:
$ sudo apt-get
update
$ sudo apt-get install python3-pip python3-dev libpq-dev
postgresql postgresql-contrib nginx
his will install pip, the Python develop ment files needed to build Gunicorn
ter, the Postgres database system and the libraries needed to interact
with
, and the Nginx web server.
Create the PostgreSQL Database and
User
e’re going to jump right in and create a database and database user for
ou jango application.
By default, Postgres uses an authentication scheme called
“pee authentication” for local connections.
Basically, this means that ife th user’s operating system
usernam matches a valid Postgres username, that user can login with
no furthe authentication.
During the Postgres installation, an operating system user
name postgres was created to correspond to the postgres
PostgreSQ administrative user.
We need to use this user to perform administrative tasks. We can
us sudo and pass in the username with the -u option.
og into an interactive Postgres session by
typin
$ sudo -u postgres psql
You will be given a PostgreSQL prompt where we can set up
our requirements.
First, create a database for your project:
postgres=# CREATE DATABASE mydatabase;
Note:
Every Postgres statement must end with a semi-colon, so make sure
that your command ends with one if you are experiencing issues.
Create a database user for our project.
Make sure to select a secure passw ord:
postgres=# CREATE USER myproj e ctuser WITH PASSWORD ‘12345';
Afterwards, we’ll modify a few of the connection parameters for
the user we just created.
This will speed up database operations so that the correct values
do not have to be queried and setc ea h time a connection is
established.
n
We are setting the default encodi g to UTF-8, which Django
expects.
We are also setting the default transaction isolation scheme to
“read committed”, which blocks reads from uncommitted
transactions.
Lastly, we are setting the timezone. By default, our Django
projects will be set to use UTC.
These are all recommendations from the Django project itself:
postgres=# ALTER ROLE myprojectuser SET client_encoding TO 'utf8';
postgres=# ALTER ROLE myprojectu s er SET default_transaction_isolation
TO 'read committed';
postgres=# ALTER ROLE myprojectu s er SET timezone TO
'UTC';
Now, we can give our new user access to
administer our new database:
postgres=# GRANT ALL PRIVILEGES ON DATABASE mydatabase TO
myprojectuser;
When you are finished, exit out of the
PostgreSQL prompt by typing:
postgres=# \q
Create a Python Virtual Environment for your
Project
Now that we have our database, we can begin getting the rest of
ou project requirements ready. We will be installing our Python
requirement within a virtual environment for easier management.
To do this, we first need access to
h t e virtualenv command. We can
instal this with pip.
If you are using Python 3, upgrade pip and install the package by typing:
$ sudo -H pip3 install --upgrade pip
$ sudo -H pip3 install virtualenv
Within the project directory, create a Python virtual
environment by typing:
$ virtualenv ENV
This will create a directory called ENV within your Myproject directory.
Inside, it will install a local versio of Python and a local version of
pip. We can use this to install and configure an isolated Python
environment for our project.
Before we install our proj ect’s Python
requirements, we need to activate the virtual
do that by
environment. You can
typing:
$ source ENV/bin/activate
With your virtual environment active, install Django, Gunicorn,
and the psycopg2 PostgreSQL adaptor with the local instance of
pip:
$ pip install django gunicorn
psycopg2
Create and Configure a New Django Project
With our Python components installed, we can create the actual
Django project files.
Create the Django Project
Since we already have a project direc tory, we will tell Django to install
the files here. It will create a secondelev l directory with the actual
code, which is normal, and place a management script in this directory.
$ django-admin.py startproject Myproject
t this point, your project directory (~/Myproject in our case)
hould have the following content:
~/Myproject/manage.py: A Django project management
script.
~/Myproject/: The Django project p ackage. This should contain
the d
init .py, settings.pj y, urlas.pyy, ana wsgei.py files.
~/Myproject/ENV/: The virtual environment directory we created
earlier.
Adjust the Project Settings
The first thing we should do with our newly created project files is
adjust he settings.
$ nano ~/Myproject/settings.py
Start by locating the ALLOWED_HOSTS directive.
This defines a list of the server’s ad dresses or domain names may
be used to connect to the Django instance.
Any incoming requests with a Host header that is not in this
list will raise an exception.
Django requires that you set this o prevent a certain class of
tvulnerability. security
In the square brackets, list the IP addresses or domain names that a
associated with your Django server.
o tations with entries separated
Each item should be listed in qu
by comma.
If you wish requests for an entire domain and any subdomains, prepend
period to the beginning of the entry. In the snippet below, there are a
fe commented out examples used to demonstrate:
Myproject/settings.py
# The simplest case: just add the domain name(s) and IP addresses
of your Django server
# ALLOWED_HOSTS = [ 'example.com', '203.0.113.5’]
# To respond to 'example.com' and any subdomains, start the
domain with a dot
# ALLOWED_HOSTS = ['.example.com',
'203.0.113.5']ALLOWED_HOSTS = ['your_server_domain_or_IP',
'second_domain_or_IP', . . .]
Next, find the section that configures database access. It will start with
DATABASES. The configuration in h t e file is for a SQLite database.
We already created a PostgreSQL database for our project, so we
need to adjust the settings.
Change the settings with your PostgreSQL database information. We tel
Django to use the psycopg2 adaptor we installed with pip. We need to
give he database name, the database use name, the database user’s
password and then specify that the database is located on the local
computer. You an leave the PORT setting as an empty string:
Myproject/settings.py
DATABASES = {
'default’:
{
'ENGINE': 'django.db.backen d
s.postgresql_psycopg2’, 'NAME': 'mydatabase',
'USER': 'myprojectuser’,
'PASSWORD': '12345',
'HOST': 'localhost’,
'PORT': ‘’,
}
}
Next, move down to the bottom of the file and add a
setting indicating where the static files should
be placed.
This is necessary so that Nginx can handle requests for these items.
The ollowing line tells Django to place
h t em in a directory called static in
the base project directory:
yproject/settings.py
STATIC_URL = '/static/’
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
Save and close the file when you are finished.
~/myproject/python manage.py m a kemigrations
~/myproject/python manage.py migrate
reate an administrative user for the project by typing
~/myproject/python manage.py createsuperuser
You will have to select a username, provide an email address, and
choose and confirm a password.
e can collect all of the static content into the
cation
director
we configured by
typing:
~/myproject/python manage.py collectstatic
You will have to confirm the operation. The static files will then be placed in
a directory called static within your projec
t directory.
If you followed the initial server setup guide, you should have a
UF firewall protecting your server.
In order to test the development server, we’ll have to allow access to th
port we’ll be using.
Create an exception for port 8000 by typing:
Finally, you can test our your project by starting
up
the Django development server with this command:
$ python manage.py runserver
8000
you append /admin to the end of the URL in
ddress
th bar, you will be prompted for the administrativ
sername and password you created with th
eatesuperuser command:
After authenticating, you can access t he default Django
admin interface:
When you are finished exploring, hit CTRL-C in the terminal window
to shut down the development server.
Use Oracle Database With Django In Windows
In order to connect to Oracle from Python , we need to install cx_Oracle package,
which is DB-API 2.0 implementation, usi n g PIP.
Getting Oracle atabase
ready
We work with Oracle Database 11g Express Edition (XE). If you have not yet
installed it, go to Oracle Database 11g Ex press Edition and download the
version relevant to your platform.
Download and install Python 3.6 for our platform
The python package that is used to connect to Oracle from Python
is x_Oracle
Go to directory where pip.exe (or pip3.6.exe) is present and
give following command. Pip.exe is present in
/Scripts folder in Windo installation. Check your platform for
details.
pip install cx_Oracle
Installing I n stant
Client
In order to access Oracle from Python, you need to install Instant
Client that is specific to your platform.
Go to Instant Client and select w nload for your
do platform.
You need to download Instant Client 64 bit if your Python is 64 bit
otherwise download 32 bit version . Python edition and Instant
Client edition must be same.
It is enough to download Instant Client Basic Light version as
need support for only English. we
You can check which version of Python you are using
C:\python>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)
on win32 Type "help", "copyright", "cre d its" or "license" for more information.
>>>
Make sure Oracle's BIN directory or InstantClient folder is in system PATH.
The following command shows how to add Oracle's BIN directory to system
PATH:
\>set PATH=%PATH%;C:\oraclexe\ a pp\oracle\product\11.2.0\server\bi
If you are using InstantClient, use folder into which you installed InstantClient
ex: c:\python\instantclient) as follows:
\>set PATH=%PATH%;C:\python\instantclient
The following program will connect to Oracle Database using username gktcs
password gktcs.
and
In case you are trying to use a different account or a different version of Oracle
database then feel free to change the deta ils and experiment.
import os
import cx_Oracle
# Connect to hr account in Oracle Database 11g Express Edition(XE)
con = cx_Oracle.connect(“gktcs", “gktcs", "localhost/xe")
print("Connected!")
con.close()
Creating Django Project and Application
We need to install Django Framework using PIP as follows:
pip install django
Installing Django, installs django-admin.exe in Scripts folder of Python
installation directory.
Let's create a new Django Project called oracledemo and
Application called blog in that project
o with the f llowing
commands:
django-admin startproject oracledem
o
It will create a new folder oracledemo and places manage.py and
anothe folder oracledemo inside that. Get into oracledemo folder and
then run manage.py to create a new application called blog inside that
project.
python manage.py startapp
blog
Configure Django
settings.py
Open settings.py file that is placed in oracledemo folder, which is
inside oracledemo (project) folder.
Add application hr as one of the ins alled applications by adding it
to INSTALLED_APPS list.
INSTALLED_APPS = [
'django.contrib.admin’,
'django.contrib.auth’,
'django.contrib.contenttypes’
, 'django.contrib.sessions’,
'django.contrib.messages’,
'django.contrib.staticfiles’,
‘blog’,
]
Modify default database configuration so that Oracle is used
as default database.
we are using Oracle Database 11g XE running on the
current system.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle’,
'NAME': 'XE’,
'USER': ‘gktcs’,
'PASSWORD': ‘gktcs’,
'HOST': 'localhost’,
'PORT': '1521' } }
Creating
ModelJOBS table in Oracle
Create a class that represents
database in oracledemo/hr/models.py file.
ss Post(models.Model):
title =models.CharField(max_length=120)
content=models.TextField()
updated=models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp=models.DateTimeField(auto_now=False, auto_now_add=True
class Meta:
db_table = “posts"
Creating view and
template
Create the following function view
in oracledemo/blog/views.py to display details of posts from
Post table.
def blog_posts (request):
~ / n a
return render(r e q u est,’blog_post.html',{‘posts' :
Post.objects.all()})
Here is oracledemo/blog/templates/blog_post.html to display
details of Jobs in HTML table.
og_post.html
<!DOCTYPE html>
<html lang="en">
<head> <meta charset="UTF-8">
<title>Blogs</title>
</head>
<body>
<h1>Blog</h1>
<table width="100%" border="1">
<tr style="background-color:li g
htgray">
<th>Title</th>
<th>Content</th>
<th>Updated Time</th>
</tr>
{% for post in posts %}
<tr>
<td>{{post.title}}<
/td>
<td>{{post.content}}</td>
<td>{{post.updated}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
Finally add a new URL in mo/oracledemo/urls.py that invokes
oraclede blog_posts().
from django.urls
import path import blog.views as bl g_views
urlpatterns = [
path(‘post’, blog_views. blog_posts )
]
Start server after adding Oracle's bin directory or InstantClient
director to system PATH.
>set PATH=%PATH%;C:\oraclexe\app\oracle\product\11.2.0\server\bi
r
>python manage.py
runserver
Now go to browser and enter the following URL to get list of
Jobs.
http://localhost:8000/post
reating a Django Web Application with a PostgreSQL
atabase on Windows
Installing Python 3
To run the Django Framework on your system you would need Python 3
installed on your system.
You just have to download the package from the official
website, www.python.org, according to your operating system.
Keep in mind you have to install a Python 3 version, not the
version 2.
While installing Python 3 don’t forge t to tick the option “Add Python 3
to your path” when the installation prompt opens.
You can check that the Python version is on your system by typing
this command in PowerShell:
python --version
Installin g Virtualenv
irtualenv is a Python package that lets you
createdifferent vir nvironments for multiple projects requiring
different versions of the softw
In PowerShell type in this command :
Pip install virtualenv
his will download and install virtualenv on your system
globally
Install PostgreSQL
Go to the download page for PostgreSQL installers and install the
latest version of PostgreSQL that is suitable to your system (64-bit
Windows).
The installation process is pretty sta ndard but here are some
things you should look out for:
In the PostgreSQL Setup Wizar d , in the Select Components
page, uncheck the components that you do not want to install, or just
leave it be.
If you uncheck anything, don’t worry, just launch the installer later
and select the component you need, and PostgreSQL will be
updated accordingly.
At the Password page, enter the password for the database
u will be
superuse (postgres). This account sed to access your SQL
Shell (pqsl later on.
At the Port page, choose the port number that the server should
listen on, or stick to the default 5432. Just make sure that the port
is not currently used by any otheraapplic tions.
Proceed with the rest of the installation. To verify the installation,
find the SQL Shell (pqsl) program cand lick on it to launch it. The pqsl
command line will appear.
Open the command line. Accept the default for the Server,
Database, Port, and Username fields
i by press ng Enter.
However, at the Password field, you must enter the password that you
chose during in the Setup Wizard.
If you your window is same as the above, then you have
successfully installed PostgreSQL!
You will be given a PostgreSQL prompt where we can set up
our requirements.
First, create a database for you r project:
postgress=# CREATE DATABASE mydatabase;
Note:
very Postgres statement must end with a semi-colon, so make sure
tha our command ends with one if you are experiencing issues.
Next, create a database user for our project. Make sure to select
a secure password:
postgress=# CREATE USER myprojectuser WITH PASSWORD
'password';
Afterwards, we’ll modify a few of the connection parameters for the
use we just created.
This will speed up database operations so that the correct values do
no have to be queried and set each time a connection is established.
We are setting the default encoding to UTF-8, which Django expects.
We are also setting the default transaction isolation scheme to
“read committed”, which blocks reads
m fro uncommitted
transactions.
By default, our Django projects will be set to use UTC. These are all
recommendations from the Django project itself:
postgress=# ALTER ROLE myprojectuser SET client_encoding TO 'utf8';
postgress=# ALTER ROLE myproject u ser SET default_transaction_isolation
TO 'read committed';
postgress=# ALTER ROLE myproject u ser SET timezone TO
'UTC';
Now, we can give our new user access to administer our new database:
ostgress=# GRANT ALL PRIVILEGES ON D
oATABASE mydatabase TO myprojectuser;
hen you are finished, exit out of the PostgreSQL prompt by
typing:
postgress=# \q
Installing Django
We can install Django on our system , for that again we will have to
just execute some commands on our s sy tem.
pip install django
This command will install Django’s l atest stable version and we will
be working on the same.
Setting Up a Virtual
Environment
All the necessary requirements have been fulfilled and now we can
start our project.
Our first step will be to set up a virtu al environment for our project.
To make a virtual environment, go to the directory of your choice
via PowerShell and execute this command:
irtualenv your_project_name
fter the virtual environment has been created it should look like this.
Now activate virual environment
or that execute this command:
n Windows, virtualenv creates a batch
file
\Environment Name\Scripts\activate.bat
e will also need to install psycopg2. psycopg2 is a package that will
allo ango to use the PostgreSQL database that we just configured.
Similarly, stall, write:
pip install
psycopg2
Now, it’s time to start a Django project!
Django-admin startproject myproject
We are ready to configure the Djang o database settings!
In the project directory, find the fil e “settings.py”. This file contains
the configurations for the app.
Open a section labelled “DATABASES”. The section should currently
look like this:
Django is automatically configured with
SQLite.
We’ll need to change this section to tell Django to use PostgreSQL
instead
The username and password you s et there will be used later when w
create a superuser for the database. Create the administrative account
b typing:
python manage.py
createsuperuser
Now that everything is set up, test whether your database is
performing by running the Django development
s erver.
python manage.py
runserver
Test it by going to the development server which can be found on
your command prompt.
Appending /admin to the url will redirect you to the Django
administration page where you can loga in with the s me credentials
that you earlier used to create a superuser.
Congratulations! You have set up a Django app with PostgreSQL as
the database!