Django Framework

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Django Web Framework

Why Django?¶
Django is a high-level Python Web framework that encourages rapid
development and clean, pragmatic design. Built by experienced developers, it
takes care of much of the hassle of Web development, so you can focus on
writing your app without needing to reinvent the wheel.

With Django, you can take Web applications from concept to launch in a
matter of hours. Django takes care of much of the hassle of Web development,
so you can focus on writing your app without needing to reinvent the wheel.
It’s free and open source.
Fully loaded Django includes dozens of extras you can use to handle
common Web development tasks. Django takes care of user authentication,
content administration, site maps, RSS feeds, and many more tasks — right out
of the box.
Ridiculously fast Django was designed to help developers take
applications from concept to completion as quickly as possible.
Reassuringly secure Django takes security seriously and helps
developers avoid many common security mistakes.
Exceedingly scalable some of the busiest sites on the Web leverage
Django’s ability to quickly and flexibly scale.
Incredibly versatile Companies, organizations and governments have
used Django to build all sorts of things — from content management systems
to social networks to scientific computing platforms.

Introduction to Django Web Framework¶

Django is a high level python web framework. It is a open source web


framework released under the licence of BSD. Django allows developers
to build web applications in a short span of time. Django applications are
powerful, fast, most secure and exceedingly scalable.

Django was designed to help developers to complete the web


applications as quickly as possible. Django provides best security
mechanisms it helps developers to avoid many common security
mistakes. Django follows rapid web development so that developers can
make changes to any complex application easily with timely deadlines.

Django follows the MVC (Model, View, and Controller) architecture. It


allows clean design and development. Model deals with databases and
Controller deals with business logic and View deals with presentation
logic. In Django MVC has just changed to MTV (Model, Template, and
View)

Model = Model, View = Template, Controller = View


Django has built in ORM (Object Relational Mapper). It simplifies
everything. Developers need not to worry about writing of SQL queries.
Developers just have to write a Django query that deals with objects.
ORM will convert the Django query into SQL query and performs it on
database and again converts database results into objects. Developers
just have to play with objects. It saves a lot of time. Django provides
multiple language support for web applications. Django is one of the
best python web frameworks.

Django comes with inbuilt security checks such as SQL injection, cross-
site scripting, cross-site request forgery and clickjacking. Django’s user
authentication system provides a secure way to manage user accounts
and passwords. Some of the high traffic websites on the web use
Django’s ability to quickly and flexibly scale to meet the heaviest traffic
demands.

Reasons to choose Django Web Framework¶


 Write less code do more
 Open source web framework
 Tons of packages available to use
 Great Community Support
 Suits for projects of any size
 Used and trusted by world best companies
 Perfect for time based projects Highly Scalable

Advantages of using Django Web Framework¶


 Built-in ORM(Object Relational Mapper) Support
 Multiple Language Support
 Built-in Frameworks for Sitemaps, RSS, Caching, etc.

Awesome Websites developed by Django Web


Framework¶
 Disqus
 Bitbucket
 Instagram
 Mozilla
 Pinterest
 NASA
 The Onion
 Eventbrite

Basic process in to create Django project in Ubuntu¶


$ mkdir my_first_app
$ cd my_first_app
$ virtualenv -p python3 env3
$ source ./env3/bin/activate
(env3)$ pip install Django
(env3)$ Django -admin startproject myproject
(env3)$ cd myproject
(env3)$ python manage.py runserver 8000

Open browser and access http://127.0.0.1:8000/ to see congrats page.


Understanding Django Project Structure¶
In the previous article we have seen how to setup the Django
development environment. In this article we will learn about how to
create Django project and Django project structure. We care about
project structure because it helps us to organise the complex project
code. A well-structured project will helps the developers to navigate
through the code quickly.

Create Django project¶


To create Django project open the terminal (Ubuntu) or command (cmd)
prompt and change the directory to a new directory where you want to
create the project. Now, run the below command.

Django -admin start project my project

Above command will create the Django project with project name "my
project" and we can see the below project structure.

My project/
├── manage.py
└── My project
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py

Django project structure¶


1. manage.py:
 It is a python module it provides the command-line
utilities for Django project just like Django -admin.
 To know the commands that provided by the
"manage.py" then just run the command. It will show
us all available commands.
2. python manage.py --help
 Most commonly used command is "run server". It is
used to run the development server.
3. my project: It is the python package of our project. It contains
the configuration files of project settings, urls and wsgi.
a. __init__.py: It's a python file which tells the python that
the directory is a python package.
b. settings.py: It's settings configuration file for the
project. It contains the settings like database, urls,
usgi and etc.
c. urls.py: It base file of urls for Django application. It is
pointed in the settings.py file using the
setting 'ROOT_URLCONF'.
d. wsgi.py: It is file which contains the configuration of
wsgi application. It is used to run the Django
application. It is pointed in settings.py file using the
setting 'WSGI_APPLICATION'

Let's talk about settings in settings.py¶


 DEBUG: It is set to Boolean "True" in development mode and to
Boolean "False" in production mode. It will enable server to
show us errors that helps developers to debug and fix the error
if DEBUG set to "True".
 ALLOWED_HOSTS: It is a security measure in Django. It
prevents the HTTP Host header attacks. It takes a list of string
that represents the host/domain names that Django application
can serve.
 INSTALLED_APPS: In Django, we divide complex projects in
sub projects and develop them to make it simple. We call these
sub projects as apps. We put all these apps in this setting.
Django considers database migrations only for the apps which
are in INSTALLED_APPS setting.
 ROOT_URLCONF: It is the base point for urls. When a request
comes in Django routes the request based on the url patterns.
 DATABASES: In Django, database settings are used to connect
to the database for information storing and retrying.
 TEMPLATES: when a request comes in we generally create an
http response using a html template. In Django template
settings we provide template directory paths and template
engines. Template paths are used to find the given template
name and template engines are used to render the templates.
 STATIC_URL: It is a prefix added to the static files path when
we use "static" template tag in a template.
 STATICFILES_DIRS: When we define a static resource in
templates then it has to be served. In order to serve it Django
has to look in some directories. Django uses this setting to look
for static files.
 STATIC_ROOT: When deploying the Django app we serve static
files with servers like nginx, apache. These servers takes a
directory path where all static files resides. To do it in Django
we have a command "python manage.py collect static". When
we run this command it will collects all static files to the
STATIC_ROOT directory.
 MEDIA_URL its prefix added to the medial files path when a
media resource is specified in templates.
 MEDIA_ROOT: It's a directory path where all media files will be
stored. When a user uploads a file then it has to store
somewhere. In general files deals with large amount of
memort.So, we do not store files in databases instead we store
it in filesystem. Above mentioned settings are basic settings
that we use in Django while developing the applications. In
coming articles we will be discussing other Django settings also.

Understanding Model View Controller


(Mvc) In Django ¶

What is Model View Controller? We call it in short MVC. It's a software


architecture pattern that is used to divide the complex software into
simple parts based on the functionality. When we use Google for web
search, we simply open Google and search for "food" let's say. Then
google will show us results about food. This what we see. But, actually
what happens is when we search google with keyword "food", browser
sends request to google server with query parameter as "food". Then, it
will query the google search index database and fetches the records from
the database. Let's say, these records not in the order as we see it in the
google webpage. So, Google has to process queried database records to
put them in order to display it. By using the processed data it will
generate the html document to present it to the user.

To simplify the software development software architects divided the


process into 3 parts.

1. Model
2. Controller
3. View

Model:¶
 It deals with the database operations.
 Creating and updating the tables
 Fetching and updating the data in the database

Controller¶
 It deals with processing of data. Some developers also call it as
Business Logic part.
 Process the data and generate it into required format to be sent
to next layer View.

View¶
 It deals with presenting the data to the end user.
 It receives the data from the controller and generates the html
to present it to the end user.

The Django framework also follows the MVC architecture pattern. But, it
just renamed MVC into MTV (Model, Template, and View).
Advantages of Model View Controller Architecture¶
 Multiple developers can work simultaneously.
 It will be easy to divide and distribute the work among multiple
developers.
 It can be easy to debug and fix the errors because of separation
of responsibilities.

Understanding the Request-Response


Lifecycle in Django ¶
Let's start understanding the request-response lifecycle of a Django
application. Every web application uses HTTP/HTTPS protocol. In the
HTTP/HTTPS protocol client sends a request to the server based on the
request data server sends the response back to the client. It's the basic
principle of HTTP protocol. While setting up the Django application in the
server we need a webserver and wsgi server. Webserver helps us in serving
static files/content. If we did not use the webserver to serve static files then
it has to serve by WSGI server which results in more number of requests to
the server. So, gradually it slow down the application performance. Web
server balances the requests load on the server. So, it's highly
recommended to use the webserver.

A client can be defined as a piece of software which can send a request by


following the HTTP/HTTPS protocol. In general we consider client as a Web
Browser. While deploying the Django application on the server we use one
of the combinations of a "Nginx, uWSGI and Django” or "Nginx, gunicorn
and Django “or "Apache, mod_wsgi and Nginx". As of now, we will discuss
the deployment process but we discuss about request-response lifecycle
of Django application. We will be discussing on when a request comes in
how it can be processed and how the response will be created and sent
back to the client.

When a client sends a request to the server it first passed to the webserver,
It contains the configuration rules to dispatch the request to the WSGI
server or served by itself. WSGI server pass the request to the Django
application. Django has the following layers in dealing with request-
response lifecycle of a Django application.

Layers of Django Application¶


1. Request Middlewares
2. URL Router(URL Dispatcher)
3. Views
4. Context Processors
5. Template Renderers
6. Response Middlewares
7.
Whenever the request comes in it is handled by the Request middleware.
We can have multiple middleware. We can find it in project settings
(settings.py). Django request middleware follows the order while
processing the request. Suppose if we have request middleware in the
order A, B, C then the request first processed by the middleware A and
then B and then C. Django comes up with bunch of default middleware.
We can also write our own or custom middleware. After request processed
by the middleware it will be submitted to the URL Router or URL dispatcher.

URL Router will take the request from the request middleware and it takes
the URL Path from the request. Based on the url path URL router will tries
to match the request path with the available URL patterns. These URL
patterns are in the form of regular expressions. After matching the URL
path with available URL patterns the request will be submitted to the View
which is associated with the URL.

Now, we are in business logic layer Views. Views processes the business
logic using request and request data (data sent in GET, POST, etc.). After
processing the request in the view the request is sent context processors,
by using the request context processors adds the context data that will
help Template Renderers to render the template to generate the HTTP
response.

Again the request will send back to the Response middleware’s to process
it. Response middleware’s will process the request and adds or modifies
the header information/body information before sending it back to the
client (Browser). After the browser will process and display it to the end
user.

Getting Started With Django First App¶


Let's get started with our very first Django application. I always recommend
newbies to use the latest versions of Django and python. Python2.X.X has
no active support. We generally develop many projects on a single machine
with different requirements (python packages). If we install python
packages globally some projects may not work properly. To avoid it we
should use virtual environments. Before we dive into our first Django
application I recommend you to read ["setting up Django development
environment"]/course/Django /setting-up-Django -development-
environment/).
Let's create the our first Django application¶
Steps to create a Django application

1. Create a directory named "my_first_app" and change directory


into it.
2. Now, install Django package with pip.
3. Create a virtual environment for python3 with command
"virtualenv -p python3 env3"
4. Create a Django project named "my project" and change the
directory path to "my project".
5. Now, run the command "python manage.py run server 8000".
After, open the browser (I prefer mozilla or google chrome) and
access "https://localhost:8000" to see the success output.

I've added reference code below (OS: Ubuntu)

$ mkdir my_first_app
$ cd my_first_app
$ virtualenv -p python3 env3
$ source ./env3/bin/activate
(env3)$ pip install Django
(env3)$ Django -admin startproject myproject
(env3)$ cd myproject
(env3)$ python manage.py runserver 8000

Let's understand the Django project structure¶


After above steps our project structure looks like below

myfirst_app
└── myproject
├── db.sqlite3
├── manage.py
└── myproject
├── __init__.py
├── __pycache__
├── settings.py
├── urls.py
└── wsgi.py
Our project execution starts from "management.py" for development
server which is a python dev server. In production we replace the python
dev server with servers like "Nginx", "Apache2", etc. Whenever a request
comes to the server that is sent to WSGI application which we can see it in
file "myptoject/wsgi.py" Django WSGI application uses settings in
"myproject/settings.py" . "settings.py" files contains settings like URL
Routing point, Database, Template directories, Static directories and more
which we will learn about all these settings in coming articles.

As

Django is a MVC (MTV) framework it is divided into 3 parts 1.Model


(Databases & ORM), 2.View (Business Logic) and 3.Template (User
Presentation). Whenever a request comes in first it is passed to url router
and then to view. View renders the template (HTML) and returns the
response.

Let's write our First Django View¶


If we see our project settings, we can find that our url setting is configured
to "myproject/urls.py" (ROOT_URLCONF = 'myproject.urls'). In "urls.py" file
we create url configurations in which are used by Django to route the url
paths to respected views. In Django, we divide complex web application
into simple apps which provides us quick navigation to the project.

Let's write a simple view that returns plain text "Hello World". Before that
let's create an app named "myapp". To create app run the command
"python manage.py startapp myapp". After the command executed our
project structure looks like below.

myproject
├── db.sqlite3
├── manage.py
├── myapp
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
└── myproject
├── __init__.py
├── __pycache__
├── settings.py
├── urls.py
└── wsgi.py

Let's take a small introduction of Django applicaiton


structure.¶
 admin.py: Django comes with built in admin panel. This file
contains the configurations for built-in admin panel.
 apps.py: We already know Django can have multiple apps and
each app can have its specific configurations. This file contains
the app configurations.
 __init__.py : This file used to represent the directory "myapp" as a
python package.
 Migrations/: Whenever we make database related changes all
those changes are recorded in the form of migrations and stored
in this directory.
 models.py: A model is a equivalent representation of relational
database table. It contains the database tables in the form of
Django models.
 tests.py: Django comes with unit tests. We write Django unit
tests in this file.
 views.py: Views are mapped to urls which will return
HttpResponse. This file contains the app related views.

Let's write our very first Django app view¶


 We will write a view that will return "Hello World" as a response.
 Open file **"myapp/views.py"**and add below code to it.
from Django .http import HttpResponse

def hello(request):
data = "Hello World"
return HttpResponse(data)
Every Django view takes request as a first parameter and returns the
HttpResponse. Above view will return response "hello world" * Now, we
have to map the view to urls. To do it, open file "myproject/urls.py" edit
it as below.
from Django .contrib import admin
from Django .urls import path
from myapp.views import hello

urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', hello, name="hello")
]

We have imported our view "hello" from myapp/views.py and mapped it


to url "hello/" using Django “path" utility.

 Now, access https://localhost:8000 you will get 404 page. Because


we have updated our myproject/urls.py the page also says that it
only contains 2 patters 1. admin/ 2. hello/ .
 Access http://localhost:8000/hello/ to see our very first view
response Hello World . It's only returned plain text. Now, it's time
to return some HTML response.
 Let's change our view hello ( myapp/views.py ) to below code
from Django .http import HttpResponse

def hello(request):
data = """
<html>
<title>Hello World</title>
<body>
<h1>Hello World</h1>
</body>
</html>
"""
return HttpResponse(data)

If we access the page http://localhost:8000/hello/ we can see the HTML


response which contains text "Hello World" inside a "h1" tag. We can add
more views to our our very first Django application. In the above view we
have written all the HTML code inside the view. It's not a good practice.
I've shown it just to make you understand how the view works. For live
projects we maintain the project structure. The project structure divided
into Django code (views, urls, tests, forms, models and other utilities),
templates (HTML files) and static files (CSS, JavaScript, Images, Videos,
etc.).

How to Use Templates in Django ¶

Django is a web framework so, It needs to maintain the code in such a way
that it should be easy to navigate and easy to read and maintain. As we
already know the Django framework is a MVC, we do not write the HTML
code in the views.py instead we write it in a template. In Django web
framework we generate dynamic HTTP response. While generating the
dynamic HTML content we use a special syntax called "Django template
syntax". It will make the process easy for us. Before using the templates
in our Django project we need to configure some settings. Let's use
templates in Django by configuring template settings.

Django Template Settings Configuration:¶


 myproject/settings.py
# .....
TEMPLATES = [
{
'BACKEND': 'Django .template.backends.Django .Django Templates',
'DIRS': ['templates',],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'Django .template.context_processors.debug',
'Django .template.context_processors.request',
'Django .contrib.auth.context_processors.auth',
'Django .contrib.messages.context_processors.messages',
],
},
},
]

# .....

 project structure
myproject
├── db.sqlite3
├── manage.py
├── myapp
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── myproject
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── templates
└── home.html

 myapp/views.py
from Django .shortcuts import render

def home(request):
return render(request, 'home.html')

 myproject/urls.py
from Django .urls import path
from myapp import views

urlpatterns = [
path('', views.home, name='home'),
]

 templates/home.html
<html>
<title>Hello World</title>
<body>
<h1>Hello World</h1>
</body>
</html>

Open settings.py file, you can find "TEMPLATE" setting. It contains list of
settings for templates. Every template setting is dictionary object. It
contains settings like BACKEND, DIRS, APP_DIRS, and OPTIONS.
In Django we render the template using the the function*"render “to
generate the dynamic HTML content. The *"render" function takes 3
parameters request, template name and a context (a dictionary of keys and
values which will be used inside the template). Before rendering the
template Django looks for the template using its name. It searches for the
template using its in "DIRS" setting for external templates. So, in the above
code we have added "templates" directory. After adding the directory our
project structure looks like above. When Django looks for the template it
will find it in "templates" direcory that we have added.

Now, access the url localhost:8000 in your browser you can see the HTTP
response "Hello World". We have simply rendered a static html. But, what
we discussed is we generate a dynamic response using Django web
framework. Let's see how we can generate a dynamic response in Django.

Let's change the views.py and home.html as follows

 myapp/views.py
from Django .shortcuts import render

def home(request):
context = {'name': 'Anjaneyulu Batta'}
return render(request, 'home.html', context)

 templates/home.html
<html>
<title>Hello {{ name }}</title>
<body>
<h1>Hello {{ name }}</h1>
</body>
</html>
Now, access the url localhost:8000 in your browser you can see the HTTP
response "Hello Anjaneyulu Batta". In the view we have passed the context
dictionary and accessed the value with key name in the template using the
Django template syntax "{{name}}". In this way we can make use of Django
templates.
Django Static Files Usage (images,css,js)
Every website needs to serve the extra files such as images, CSS, JavaScript.
The name "static" itself indicates that contents of files do not change. So,
in Django to work with static files we need to make some configurations
in setttings.py file. Django provides app " Django .contrib.staticfiles" to help us
manage it.

Configuring static files in settings.py¶


1. Add "Django .contrib.staticfiles" to "INSTALLED_APPS".
INSTALLED_APPS = [
# ...
'Django .contrib.staticfiles', # ...]

2. Add "STATIC_URL"
STATIC_URL = '/static/'

3. Add "STATICFILES_FINDERS" to make sure template tag "static"


can work in HTML templates.
# ...
STATICFILES_FINDERS = [
'Django .contrib.staticfiles.finders.FileSystemFinder',
'Django .contrib.staticfiles.finders.AppDirectoriesFinder',
]

4. Add extra static directories using "STATICFILES_DIRS". In below


example we added a directory "static" to static files finder which is
located at the root level of our project.
# ...
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]

5. Add static root to root project urls.py to make available static files
during development like below
from Django .conf import settings
from Django .conf.urls.static import static

urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
6. Serving files uploaded by a user during development

from Django .conf import settings


from Django .conf.urls.static import static

urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Django pass data from view to template¶

As we know Django is a MVC framework, we separate business logic from


presentational logic. We write business logic in views and we pass data to
templates to present the data. The data that we pass from views to
template is generally called as "context" data. Let us see an example

Django views, context data and template¶


Let's write a simple view that takes user information such as first name,
last name and address and renders it in the template.

views.py

from Django .shortcuts import render

def user_data(request):
context = {
"first_name": "Anjaneyulu",
"last_name": "Batta",
"address": "Hyderabad, India"
}
template_name="user_template.html"
return render(request, template_name, context)

user_template.html
<html>
<head>
<title>User Information</title>
{% load static %}
<script src=”{% static ‘myscript.js’ %}” ></script>
</head>
<body>
<p>First Name: {{first_name }}</p>
<p>Last Name: {{last_name }}</p>
<p>Address: {{address}}</p>
</body>
</html>
" Render" is the most used function in Django . It combines a given template
with a given context dictionary and returns an HttpResponse object with that
rendered text. It takes three arguments "request ", " template_name" and
" context" dictionary. In template we can access the context dict keys
as names**or variables** and display them like "{{ <variable/name>}} ".

Django Template for Loop¶

Django provides a template tag "for" to provide the for loop


functionality in Django templates. You can find the “for loop” syntax
below.

{% for local_name in iterable_name %}


{{ local_name }}
{% endfor %}

Let's talk about a real time use case, For example if you want to show all
athletes data in a ordered list in HTML then using Django for loop we
can do as follows.

views.py
from Django .shortcuts import render

def athletes_list(request):
context = {"athletes": ["John Snow", "Dean Winchester", "Sam Winchester"]}
return render(request, "template.html", context)
template.html
<ol>
{% for name in athletes %}
<li> {{name}}</li>
{% endfor %}
</ol>
output
<ol>
<li> John Snow</li>
<li> Dean Winchester</li>
<li> Sam Winchester</li>
</ol>

In the above example used list data structure with the for loop. In the
same way we can also use other data types like tuple, set, dict, etc.

Sometimes we may need to iterate the items in reverse order in this kinds
of cases we "reversed"

template.html
<ol>
{% for name in athletes reversed %}
<li> {{name}}</li>
{% endfor %}
</ol>
output:
<ol>
<li> Sam Winchester</li>
<li> John Snow</li>
<li> Dean Winchester</li>
</ol>

In some cases we may need to access index number of for loop then we
can use "forloop.counter" like below

template.html
{% for name in athletes %}
<p>{{forloop.counter}}. {{Name}}</p>
{% endfor %}
Output:
<p> 1. Sam Winchester</p>
<p> 2. John Snow</p>
<p> 3. Dean Winchester</p>
We can use nested for loops in Django templates.The for loop sets a
number of variables available within the loop:

forloop.counter The current iteration of the loop (1-indexed)


forloop.counter0 The current iteration of the loop (0-indexed)
forloop.revcounter The number of iterations from the end of the loop (1-indexed)
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed)
forloop.first True if this is the first time through the loop
forloop.last True if this is the last time through the loop
forloop.parentloop For nested loops, this is the loop surrounding the current one

Django template using if...elif...else


We can use if...elif..Else conditionals in Django template. The only
difference between python code and Django template code is its syntax.

Django template "if" syntax:¶


{% if <condition> %}
{{<variable>}}
{% endif %}

Django template "if..else" syntax:¶


{% if <condition> %}
{{<variable1>}}
{% else %}
{{<variable2>}}
{% endif %}

Django template "if..elif..Else" syntax:¶


{% if <condition1> %}
{{<variable1>}}
{% elif <condition2> %}
{{<variable2>}}
{% else %}
{{<variable3>}}
{% endif %}
Notes on Django template conditionals (if...elif...else)¶
 If you do not write syntax correctly then Django will throw
errors.
 Do not use object method calls using parenthesis (i.e "()") just
use method name instead.
 We can write multiple if..elif..Else conditionals.
 We can write any number of "if...elif...else" nested conditionals
in Django templates.
 We can use operators like "and", "or", "in", "==", "<", ">", etc.
 Evaluation takes from left to right.

Examples for Django template if...elif...else conditionals¶


{% if athlete_list %}
Number of athletes: {{ athlete_list|length }}
{% elif athlete_in_locker_room_list %}
Athletes should be out of the locker room soon!
{% else %}
No athletes.
{% endif %}
{% if athlete_list and coach_list %}
Both athletes and coaches are available.
{% endif %}
{% if not athlete_list %}
There are no athletes.
{% endif %}
{% if athlete_list or coach_list %}
There are some athletes or some coaches.
{% endif %}
{% if not athlete_list or coach_list %}
There are no athletes or there are some coaches.
{% endif %}

Django database connectivity¶


Django supports various relational databases like SQLite, mySQL,
PostgreSQL, Oracle. Django is completely designed for Relational
Databases so it does not support non-relational databases like mongoDB
directly. But we can use non-relational databases using third party
packages. Let's get started with connecting databases to Django
application.

All Django project configurations can be found in the "settings.py" file.


We configure the database settings in a variable "DATABASES" it's a
simple dictionary which holds the configurations of the database. When
we create a new Django project it comes with SQLite database
configurations. In order to other databases we have to configure the
settings based on the database type like MySQL, PostgreSQL, etc. The
"DATABASES" setting must configure a "default" database. We can use
multiple databases with Django.

Connecting "SQLite" with Django ¶


SQLite is a simple file based database and not recommended in the
production environment. Let's see its database configurations

DATABASES = {
'default': {
'ENGINE': 'Django .db.backends.sqlite3',
'NAME': 'database_name'
}
}

Connecting "MySQL" with Django ¶


DATABASES = {
'default': {
'ENGINE': 'Django .db.backends.mysql',
'NAME': 'database_name',
'USER': 'database_user',
'PASSWORD': 'secret',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}

Connecting "PostgreSQL" with Django ¶


DATABASES = {
'default': {
'ENGINE': 'Django .db.backends.postgresql',
'NAME': 'database_name',
'USER': 'database_user',
'PASSWORD': 'secret',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}

Let's see the details of above configuration.

 ENGINE: The database backed to use.


 NAME: It’s the name of the database.
 USER: It's the name of the database user.
 PASSWORD: It's the password for the database user.
 HOST: It's the IP address of the database server.
 PORT: It's the port number for the database server.

Django create table from model¶


Django made creating the tables in the database very simple with its
built-in ORM. To create table in the database with Django is to create a
Django model with all required fields and then create migrations and
apply them. Let's jump-in learn how to create database table with Django
model.

Creating database table with Django model¶


from Django .db import models

class Person(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
address = models.TextField()
With the above code we are creating the table named " person" with fields
" first_name ", "last_name" and " address". The equivallent " SQL" for above
Django model is
CREATE TABLE <app name>_person (
id int,
first_name varchar(100),
last_name varchar(100),
address text,
);
As we know Django comes with ORM (Object Relational Mapper) so, we
do not need to write SQL queries to deal with the database. We write
database queries in Django and Django ORM converts all these queries
into equivalent SQL and performs the query on the database and returns
the results.

In the above code we have imported the " models" module which contains
the functionality related to database (i.e ORM). " models.Model" is a base
class for all model classes in Django application. Each model class
represents a database table.

Create migrations for above Django model¶


To create migrations for the Django application we have to run the below
command.
Python manage.py makemigrations <app name>
Above command will create migrations for the model in the directory
" migrations" under the application directory.

Apply migrations to create table in the database¶


To create table in the database for our Django application we have to
apply above created models using below command

python manage.py migrate <app name>

After running above command it creates the table in the database. To


write Django models we need to know the different fields provided by
Django to use correct field for the table.

Django model CRUD operations¶


Let's do CRUD operations on Django model. Let's write basic queries like
insert, update and delete queries using Django ORM.

Let's look at the Django Model¶


from Django .db import models

class Person(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
address = models.TextField()

Now, let's quickly perform basic CRUD operations using the Django shell.
To open Django shell execute the below command.

python manage.py shell

Create or insert query in Django ¶


Django model has a default query manager which has the API to perform
the queries. Let's create a "Person" object using below code.

from .models import Person


# query1
obj1 = Person(first_name="Pradeep", last_name="K", address="Hyderabad")
obj1.save()

# query2
obj2 = Person.objects.create(first_name="Anji", last_name="B", address="Warangal")

In the above code we have written queries to insert the data into the
table using Django ORM. If you observe the above code we have done it
in two ways. In the first query we have create the person object then
called the save method to save the object into the database table. In the
second query we have used Django ORM manager method "create" to
insert the data into the database table. Whenever a object is created
Django will automatically assigns a primary key "id" to the record which
is used to identify the record uniquely.

Get or Retrieve query in Django ¶


Django query manager has the method "get" to retrieve the data from
the database table. Let's see some code

from .models import Person


obj1 = Person.objects.create(first_name="John", last_name="B", address="Hyd")
print(obj.id)
#1
obj2 = Person.objects.get(id=1)
print(obj2.first_name)
# John
In the above code we first created the record and printed it's "id"
number. After that we have retrieved the record from the database using
Django model manger method "get" by passing id. We can also use the
other parameters (i.e " first_name", "last_name", "address").

Update query in Django ¶


We can update a record the database table using the Django model
manager’s method "save" like below. Let's do some code

from .models import Person


obj1 = Person.objects.get(id=1)
obj1.first_name = "Adam"
obj1.save()
To update the record the database table we need to retrieve the record
first and make some changes to it and then call the " save" method on
object.

Delete query in Django ¶


To delete the object from the database Django model manager provide a
" delete" method to perform the delete operation.
from .models import Person
# query1
obj1 = Person.objects.get(id=1)
obj1.delete()
# query2
Person.objects.filter(id=1).delete()

We can perform the delete operation in two ways like above code.

Filter query in Django ¶


Django makes filtering of objects or records very easy using the model
manager method " filter ". Let's do some code
from .models import Person
# create queries
Person.objects.create(first_name="John Snow", last_name="D", address="Hyderabad")
Person.objects.create(first_name="John Wind", last_name="D", address="Banglore")
Person.objects.create(first_name="Carl Miller", last_name="R", address="Banglore")
# filter query
obj_list = Person.objects.filter(first_name__icontains="John")
print(obj_list)

Above query filters the objects whose first name contains the word
"john".

You might also like