Django Models
Django Models
MODELS
What is a Model ?
04
It handles the inconsistency of SQL
across different platform.
Django ORM
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)
IntegerField() CharField
CharField() FloatField()
EmailField
EmailField()
A CharField that
check valid email
address
Relationship Fields
ForeignKey() ManyToManyField
ManyToManyField() OneToOneField()
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
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.
YEAR_IN_SCHOOL_CHOICES = [
('FR', 'Freshman’),
('SO', 'Sophomore’),
('JR', 'Junior’),
('SR', 'Senior’),
('GR', 'Graduate’),
]
se PostgreSQL with your Django Application on Ubunt
To begin the process, we’ll download and install all of the items we
need from the Ubuntu repositories.
repositories
We need to update the local apt package index and then download and
install the packages.
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.
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=# \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.
If you are using Python 3, upgrade pip and install the package 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:
~/Myproject/manage.py:
/manage.py: A Django
~/Myproject/manage.py: project
A Django management
project management script. script.
~/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.
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.
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.
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
~/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.
$ 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:
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
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:
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
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.
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.
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.
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.
Now go to browser and enter the following URL to get list of Jobs.
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:
In
PipPowerShell type in~/anage.py:
install virtualenv this command:
A Django project management script.
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.
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.
By default, our Django projects will be set to use UTC. These are all
recommendations from the Django project itself:
When you are finished, exit out of the PostgreSQL prompt by typing:
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
\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:
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:
script.
python manage.py createsuperuser
Now that everything is set up, test whether your database is performing
by running the Django development server.