0% found this document useful (0 votes)
176 views86 pages

Django Models

This document discusses Django models and how they map to database tables. It covers: 1. Models are Django's data access layer and map to database tables through a Python class. 2. Each model attribute represents a database field. Django provides an automatically generated database API. 3. Common field types include CharField, IntegerField, DateField, and relationship fields like ForeignKey and ManyToManyField. Fields have options like null, blank, default, and unique.

Uploaded by

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

Django Models

This document discusses Django models and how they map to database tables. It covers: 1. Models are Django's data access layer and map to database tables through a Python class. 2. Each model attribute represents a database field. Django provides an automatically generated database API. 3. Common field types include CharField, IntegerField, DateField, and relationship fields like ForeignKey and ManyToManyField. Fields have options like null, blank, default, and unique.

Uploaded by

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

DJANGO

MODELS
What is a Model ?

Model is a data access layer of Django.


01
It gives way to access it, validate it and
describes the relationship between the
02 data.

It maps single database table to a python


03 class.

04
It handles the inconsistency of SQL
across different platform.
Django ORM

Each Model is a python class that subclasses


01 django.db.models.Model

Each attribute of model represent a database


02 field

With all of this django gives you an automat


03 ically-generated
generated database-access
database API
Model Creation
Example

from django.db import models

class Person(models.Model
models.Model):
first_name = models.CharField(max_length=30)
models.CharField
last_name = models.CharField(max_length=30)
models.CharField
Model Fields
• Fields are specified by class attributes which represents columns in
the database table(Model)

• Each Field in model class should be an instance of appropriate Field


class(Which is an abstract class)

• These are the things to know for creating model fields

Field Types Field Options Relationships


Fields Types
AutoField() BooleanField
BooleanField() DateField()

Store A date field


An integer field
true/false represents
that
value and python
automatically
generally used datetype.date
increments
for check boxes instance

IntegerField() CharField
CharField() FloatField()

It stores value A string field It stores floating


from for small to point number
-2147483648 large sized represented in
to 2147483647 strings python by a float
instance
Special Field Type

EmailField
EmailField()

A CharField that
check valid email
address

Relationship Fields

ForeignKey() ManyToManyField
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 customize and put constraint on table rows

Each field takes certain field specific arguments

Eg:

name = models.CharField(max_length
max_length=60)

Here “max_length”
” specifies the size of the VARCHAR field
The following are some common and mostly used field options:

01 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

03 default 04 primary_key
Puts unique ke
constraint for a
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
many to--one

02 many
any--to
to--many

03 Httpresponse
Choices
A sequence of 2-tuples
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', 'Sophomore’),
('JR', 'Junior’),
('SR', 'Senior’),
('GR', 'Graduate’),
]
se PostgreSQL with your Django Application on Ubunt

Django is a powerful web framework that can help you ge


your Python application or website off the ground.

Django includes a simplified development server for testin


your code locally, but for anything even slightly productio
related, a more secure and powerful web server is required.

Prerequisites and Goals


1. We will be installing Django within a virtual environment.

2. 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.
repositories

We will use the Python package manager pip to install additional


components a bit later.

We need to update the local apt package 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 Django with Python 3, type:

$ sudo apt-get update


$ sudo apt-get install python3-pip
pip python3-dev
python3 libpq-dev postgresql
postgresql-contrib nginx

his will install pip, the Python development files needed to build Gunicorn
ater, the Postgres database system and the libraries needed to interact with
, and the Nginx web server.
Create the PostgreSQL Database and User
We’re going to jump right in and create a database and database user for ou
Django application.

By default, Postgres uses an authentication scheme called “pee


authentication” for local connections.
connections

Basically, this means that if the 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;


mydatabase

Note:
Every Postgres statement must end with a semi-colon,
semi 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 password:

postgres=# CREATE USER myprojectuser 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 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 from uncommitted transactions.

Lastly, we are setting the timezone.


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 myprojectuser SET default_transaction_isolation
TO 'read committed';
postgres=# ALTER ROLE myprojectuser 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 the virtualenv command. We can install


this with pip.

If you are using Python 3, upgrade pip and install the package by typing:

$ sudo -H pip3 install --upgrade


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 version 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 project’s Python requirements,
we need to activate the virtual environment. You can
do that by 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 directory, we will tell Django to install the
files here. It will create a second level directory with the actual code,
which is normal, and place a management script in this directory.

$ django-admin.py startproject Myproject


At this point, your project directory (~/Myproject
(~/ in our case)
should have the following content:

~/Myproject/manage.py:
/manage.py: A Django
~/Myproject/manage.py: project
A Django management
project management script. script.

~/Myproject/:/: The Django project package. This should contain the


~/Myproject/manage.py: A Django project management script.
__init__.py, settings.py, urls.py, and wsgi.py files.

~/Myproject/ENV/:
/ENV/: The virtual environment directory we created
~/Myproject/ENV/: The virtual environment directory we created earlier.
earlier.
Adjust the Project Settings

The first thing we should do with our newly created project files is adjust
the settings.

~/Myproject/ENV/: The virtual environment directory we created earlier.


$ nano ~/Myproject/settings.py

Start by locating the ALLOWED_HOSTS directive.

This defines a list of the server’s addresses 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 to prevent a certain class of security
vulnerability.
In the square brackets, list the IP addresses or domain names that ar
associated with your Django server.

Each item should be listed in quotations with entries separated 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 few
commented out examples used to demonstrate:
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
~/Myproject/manage.py: A Django project management script.
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 the 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 tell


Django to use the psycopg2 adaptor we installed with pip. We need to give
the database name, the database username, the database user’s password,
and then specify that the database is located on the local computer. You
can leave the PORT setting as an empty string:
Myproject/settings.py

DATABASES = {
'default’:
{
'ENGINE': 'django.db.backends.postgresql_psycopg2’,
'NAME': 'mydatabase',
'USER': 'myprojectuser’,
~/Myproject/manage.py: A Django project management script.
'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
following line tells Django to place them in a directory called static in the
base project directory:

Myproject/settings.py

STATIC_URL = '/static/’
~/Myproject/manage.py:
/manage.py: A Django project management script.
STATIC_ROOT = os.path.join(BASE_DIR,
(BASE_DIR, 'static/')
Save and close the file when you are finished.

~/myproject/python manage.py makemigrations


~/Myprject/manage.py:
/manage.py: A Django project management script.
~/myproject/python
/python manage.py migrate
Create an administrative user for the project by typing:

~/myproject/python manage.py
~/anage.py: A Djangocreatesuperuser
project management script.

You will have to select a username, provide an email address, and choose
and confirm a password.
We can collect all of the static content into the directory
cation we configured by typing:

~/anage.py:
~/myproject/python manage.pyA Djangocollectstatic
project management script.

You will have to confirm the operation. The static files will then be placed in a
directory called static within your project directory.
If you followed the initial server setup guide, you should have a UFW
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~/anage.py:
runserver 8000
A Django project management script.
f you append /admin to the end of the URL in th
ddress bar, you will be prompted for the administrativ
sername and password you created with th
reatesuperuser command:

After authenticating, you can access the default Django admin


interface:
When you are finished exploring, hit CTRL-C
CTRL 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
API 2.0 implementation, using PIP.

Getting Oracle Database ready

We work with Oracle Database 11g Express Edition (XE). If you have not yet
installed it, go to Oracle Database 11g Express 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


cx_Oracle

Go to directory where pip.exe (or pip3.6.exe) is present and give t


following command. Pip.exe is present in /Scripts folder in Windo
installation. Check your platform for details.

pip install cx_Oracle


~/anage.py: A Django project management script.
Installing Instant 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 download for your 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 we


need support for only English.
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)]
~/anage.py: A Django project management script.
on win32 Type "help", "copyright", "credits" 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:

~/anage.py: A Django project


\>set PATH=%PATH%;C:\oraclexe\app management script.
app\oracle\product\11.2.0\server\bi

If you are using InstantClient,, use folder into which you installed InstantClient (
ex: c:\python\instantclient)
instantclient) as follows:

:\>set PATH=%PATH%;C:\python\instantclient
instantclient
~/anage.py: A Django project management script.
The following program will connect to Oracle Database using username gktcs and
password gktcs.

In case you are trying to use a different account or a different version of Oracle
database then feel free to change the details and experiment.

import os
import cx_Oracle

# Connect to hr account in Oracle Database 11g Express Edition(XE)


~/anage.py: A Django
con = cx_Oracle.connect(“gktcs", project"localhost/xe")
“gktcs
gktcs", management script.
print("Connected!")
con.close()
Creating Django Project and Application

We need to install Django Framework using PIP as follows:

pip install django ~/anage.py: A Django project management script.

Installing Django, installs django-admin.exe


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 with the following commands:
django-admin startproject oracledemo
~/anage.py: A Django project management script.

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


~/anage.py:blog
A Django project management script.
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 installed applications by adding it to


INSTALLED_APPS list.

INSTALLED_APPS = [
'django.contrib.admin’,
'django.contrib.auth’,
'django.contrib.contenttypes
django.contrib.contenttypes’,
'django.contrib.sessions’,
~/anage.py: A Django project management script.
'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
django.db.backends.oracle’,
'NAME': 'XE’,
'USER': ‘gktcs’,~/anage.py: A Django project management script.
'PASSWORD': ‘gktcs’,
'HOST': 'localhost’,
'PORT': '1521' } }
Creating Model
Create a class that represents JOBS table in Oracle database
in oracledemo/hr/models.py file.

ass Post(models.Model):
title =models.CharField(max_length=120) =120)
content=models.TextField()
updated=models.DateTimeField(auto_now auto_now=True,
~/anage.py: A Django auto_now_add=False)
project management script.
timestamp=models.DateTimeField(auto_now 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):


~/anage.py: A Django project management script.
return render(request,’blog_post.html',{‘posts' : Post.objects.all()})

Here is oracledemo/blog/templates/blog_post.html
/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">
8">
<title>Blogs</title>
</head>
<body>
<h1>Blog</h1>
~/anage.py: A Django project management script.
<table width="100%" border="1">
<tr style="background-color:lightgray
color:lightgray">
<th>Title</th>
<th>Content</th>
<th>Updated Time</th>
</tr>
{% for post in posts %}
<tr>
<td>{{post.title}}</td>
}}</td>
<td>{{post.content}}</td>
}}</td>
<td>{{post.updated
post.updated}}</td>
</tr>
{% endfor %}

</table>
</body>
</html>
Finally add a new URL in oracledemo/oracledemo/urls.py that invokes
blog_posts().

from django.urls
import path import blog.views as blog_views

urlpatterns = [
path(‘post’, blog_views. blog_posts )
]
Start server after adding Oracle's bin directory or InstantClient directory
to system PATH.

>set PATH=%PATH%;C:\oraclexe\app app\oracle\product\11.2.0\server\bi


~/anage.py: A Django project management script.
>python manage.py runserver

Now go to browser and enter the following URL to get list of Jobs.

~/anage.py: A Django project management script.


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 forget 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 ~/anage.py: A Django project management script.


Installing Virtualenv

Virtualenv is a Python package that lets you create different vir


environments for multiple projects requiring different versions of the softwa

In
PipPowerShell type in~/anage.py:
install virtualenv this command:
A Django project management script.

This 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
(64 Windows).
The installation process is pretty standard but here are some things
you should look out for:
In the PostgreSQL Setup Wizard, 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 superuser
(postgres). This account will be used 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 other applications.
applications
Proceed with the rest of the installation. To verify the installation, find
the SQL Shell (pqsl)
) program and click 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 by pressing 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 your project:

postgress=# CREATE~/anage.py:
DATABASE A Django project management script.
mydatabase
mydatabase;

Note:
Every Postgres statement must end with a semi-colon, so make sure tha
your command ends with one if you are experiencing issues.
Next, create a database user for our project. Make sure to select a
secure password:

~/anage.py:
postgress=# CREATE A Django project management
USER myprojectuser WITHscript.
PASSWORD 'password';

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 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 from uncommitted transactions.

By default, our Django projects will be set to use UTC. These are all
recommendations from the Django project itself:

postgress=# ALTER ~/anage.py: A Django project management


ROLE myprojectuser script.
SET client_encoding TO 'utf8';
postgress=# ALTER ROLE myprojectuser SET default_transaction_isolation
~/anage.py: A Django project management script.
TO 'read committed';

postgress=# ALTER ROLE myprojectuser


~/anage.py: SET timezone
A Django project management script. TO 'UTC';
Now, we can give our new user access to administer our new database:

postgress=# GRANT ALL ~/anage.py:


PRIVILEGES ONproject
A Django DATABASE mydatabase
management script. TO myprojectuser;

When you are finished, exit out of the PostgreSQL prompt by typing:

postgress=# \q ~/anage.py: A Django project management script.


Installing Django
We can install Django on our system, for that again we will have to just
execute some commands on our system.

pip install django ~/anage.py: A Django project management script.

This command will install Django’s latest 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 virtual environment for our project.
To make a virtual environment, go to the directory of your choice via
PowerShell and execute this command:

virtualenv your_project_name
~/anage.py: A Django project management script.

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
~/anage.py:activate.bat
A Django project management script.
e will also need to install psycopg2. psycopg2 is a package that will allo
jango to use the PostgreSQL database that we just configured. Similarly,
stall, write:

pip install psycopg2 script.


Now, it’s time to start a Django project!

script.
Django-admin startproject myproject
We are ready to configure the Django database settings!
In the project directory, find the file “settings.py”.
“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 set there will be used later when we
create a superuser for the database.. Create the administrative account by
typing:

script.
python manage.py createsuperuser
Now that everything is set up, test whether your database is performing
by running the Django development server.

python manage.py runserver pt.

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 log in with the same credentials that you earlier used
to create a superuser.
Congratulations! You have set up a Django app with PostgreSQL as the
database!

You might also like