Django Framework
Django Framework
Django 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.
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.
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
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.
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.
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.
$ 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
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
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
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")
]
def hello(request):
data = """
<html>
<title>Hello World</title>
<body>
<h1>Hello World</h1>
</body>
</html>
"""
return HttpResponse(data)
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.
# .....
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.
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.
2. Add "STATIC_URL"
STATIC_URL = '/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
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
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>}} ".
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:
DATABASES = {
'default': {
'ENGINE': 'Django .db.backends.sqlite3',
'NAME': 'database_name'
}
}
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.
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.
# 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.
We can perform the delete operation in two ways like above code.
Above query filters the objects whose first name contains the word
"john".