Advance Python Unit - 5
Advance Python Unit - 5
Introduction to Django
Django is a web application framework written in Python programming language. It is based on
MVT (Model View Template) design pattern. The Django is very demanding due to its rapid
development feature. It takes less time to build application after collecting client requirement.
By using Django, we can build web applications in very less time. Django is designed in such a
manner that it handles much of configure things automatically, so we can focus on application
development only.
When you’re building a website, you always need a similar set of components: a way to handle
user authentication (signing up, signing in, signing out), a management panel for your website,
forms, a way to upload files, etc. Django gives you ready-made components to use.
Why Django?
Popularity
Django is widely accepted and used by various well-known sites such as:
o Instagram
o Mozilla
o Disqus
o Pinterest
o Bitbucket
o The Washington Times
Features of Django
Rapid Development
Django was designed with the intention to make a framework which takes less time to build
web application. The project implementation phase is a very time taken but Django creates it
rapidly.
Versatility
Django can build almost any type of website. It can also work with any client-side framework
and can deliver content in any format such as HTML, JSON, XML etc. Some sites which can be
built using Django are wikis, social networks, new sites etc.
Security
Since Django framework is made for making web development easy, it has been engineered in
such a way that it automatically do the right things to protect the website. For example, In the
Django framework instead of putting a password in cookies, the hashed password is stored in it
so that it can’t be fetched easily by hackers.
Scalability
Django web nodes have no stored state, they scale horizontally – just fire up more of then
when you need them. Being able to do this is the essence of good scalability. Instagram and
Disqus are two Django based products that have millions of active users, this is taken as an
example of the scalability of Django.
Portability
All the codes of the Django framework are written in Python, which runs on many platforms.
Which leads to run Django too in many platforms such as Linux, Windows and Mac OS.
Fully loaded
Django includes various helping task modules and libraries which can be used to handle
common Web development tasks. Django takes care of user authentication, content
administration, site maps, RSS feeds etc.
Open Source
Django is an open source web application framework. It is publicly available without cost. It can
be downloaded with source code from the public repository. Open source reduces the total
cost of the application development.
Design components
• The Model contains only the pure application data, it contains no logic describing how to
present the data to a user.
• The View presents the model’s data to the user. The view knows how to access the
model’s data, but it does not know what this data means or or what the user can do to
manipulate it.
• The Controller exists between the view and the model. It listens to events triggered by
the view (or another external source) and executes the appropriate reaction to these
events. In most cases, the reaction is to call a method on the model. Since the view and
the model are connected through a notification mechanism, the result of this action is
then automatically reflected in the view.
Advantages
• Multiple developers can work simultaneously on the model, controller and views.
• MVC enables logical grouping of related actions on a controller together. The views for a
specific model are also grouped together.
• Models can have multiple views.
Disadvantages
• The framework navigation can be complex because it introduces new layers of abstraction
and requires users to adapt to the decomposition criteria of MVC.
• Knowledge on multiple technologies becomes the norm. Developers using MVC need to
be skilled in multiple technologies.
Example of MVC Design Pattern.
class Student
{
private String rollNo;
private String name;
class StudentView
{
public void printStudentDetails(String studentName, String studentRollNo)
{
System.out.println("Student: ");
System.out.println("Name: " + studentName);
System.out.println("Roll No: " + studentRollNo);
}
}
class StudentController
{
private Student model;
private StudentView view;
class MVCPattern
{
public static void main(String[] args)
{
Student model = retriveStudentFromDatabase();
controller.updateView();
controller.setStudentName("Vikram Sharma");
controller.updateView();
}
Output:
Student:
Name: Lokesh Sharma
Roll No: 15UCS157
Student:
Name: Vikram Sharma
Roll No: 15UCS157
Django Installation
To install Django, first visit to django official site (https://www.djangoproject.com) and
download django by clicking on the download section.
The steps in this guide have been tested with Windows 10. In other versions, the steps would
be similar. You will need to be familiar with using the Windows command prompt
Install Python
Django is a Python web framework, thus requiring Python to be installed on your machine. At
the time of writing, Python 3.8 is the latest version.
After installation, open the command prompt and check that the Python version matches the
version you installed by executing:
pip is a package manager for Python and is included by default with the Python installer. It
helps to install and uninstall Python packages (such as Django!). For the rest of the
installation, we’ll use pip to install Python packages from the command line.
It is best practice to provide a dedicated environment for each Django project you create.
There are many options to manage environments and packages within the Python ecosystem,
some of which are recommended in the Python documentation. Python itself comes
with venv for managing environments which we will use for this guide.
To create a virtual environment for your project, open a new command prompt, navigate to
the folder where you want to create your project and then enter the following:
In another drive
This will create a folder called ‘project-name’ if it does not already exist and setup the virtual
environment. To activate the environment, run:
...\> project-name\Scripts\activate.bat
...\> d:\\project-name\Scripts\activate.bat
The virtual environment will be activated and you’ll see “(project-name)” next to the
command prompt to designate that. Each time you start a new command prompt, you’ll need
to activate the environment again.
Install Django
Django can be installed easily using pip within your virtual environment.
In the command prompt, ensure your virtual environment is active, and execute the following
command:
After the installation has completed, you can verify your Django installation by
executing django-admin --version in the command prompt.
Starting Project
Now that we have installed Django, let's start using it. In Django, every web app you want to
create is called a project; and a project is a sum of applications. An application is a set of
code files relying on the MVT pattern. As example let's say we want to build a website, the
website is our project and, the forum, news, contact engine are applications. This structure
makes it easier to move an application between projects since every application is
independent.
Create a Project
Whether you are on Windows or Linux, just get a terminal or a cmd prompt and navigate to
the place you want your project to be created, then use this code −
django-admin startproject myproject
This will create a "myproject" folder with the following structure −
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
wsgi.py
Database is set in the ‘Database’ dictionary. The example above is for SQLite engine. As stated
earlier, Django also supports −
• MySQL (django.db.backends.mysql)
• PostGreSQL (django.db.backends.postgresql_psycopg2)
• Oracle (django.db.backends.oracle) and NoSQL DB
• MongoDB (django_mongodb_engine)
Before setting any new engine, make sure you have the correct db driver installed.
You can also set others options like: TIME_ZONE, LANGUAGE_CODE, TEMPLATE…
Now that your project is created and configured make sure it's working −
$ python manage.py runserver
You will get something like the following on running the above code −
Validating models...
0 errors found
September 03, 2015 - 11:41:50
Django version 1.6.11, using settings 'myproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
A project is a sum of many applications. Every application has an objective and can be reused
into another project, like the contact form on a website can be an application, and can be
reused for others. See it as a module of your project.
Create an Application
We assume you are in your project folder. In our main “myproject” folder, the same folder
then manage.py −
python manage.py startapp myapp
You just created myapp application and like project, Django create a “myapp” folder with the
application structure −
myapp/
__init__.py
admin.py
models.py
tests.py
views.py
• __init__.py − Just to make sure python handles this folder as a package.
• admin.py − This file helps you make the app modifiable in the admin interface.
• models.py − This is where all the applicaQon models are stored.
• tests.py − This is where your unit tests are.
• views.py − This is where your applicaQon views are.
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
)
For MIDDLEWARE_CLASSES −
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
Before launching your server, to access your Admin Interface, you need to initiate the
database −
python manage.py migrate
syncdb will create necessary tables or collections depending on your db type, necessary for the
admin interface to run. Even if you don't have a superuser, you will be prompted to create
one.
If you already have a superuser or have forgotten it, you can always create one using the
following code −
python manage.py createsuperuser
Now to start the Admin Interface, we need to make sure we have configured a URL for our
admin interface. Open the myproject/url.py and you should have something like −
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'myproject.views.home', name = 'home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
Once connected with your superuser account, you will see the following screen −
That interface will let you administrate Django groups and users, and all registered models in
your app. The interface gives you the ability to do at least the "CRUD" (Create, Read, Update,
Delete) operations on your models.
Django project architecture
Django is based on MVT (Model-View-Template) architecture. MVT is a software design
pattern for developing a web application.
Model: Model is going to act as the interface of your data. It is responsible for maintaining
data. It is the logical data structure behind the entire application and is represented by a
database (generally relational databases such as MySql, Postgres)
View: The View is the user interface — what you see in your browser when you render a
website. It is represented by HTML/CSS/Javascript and Jinja files.
Template: A template consists of static parts of the desired HTML output as well as some
special syntax describing how dynamic content will be inserted.
Project Structure:
A Django Project when initialized contains basic files by default such as manage.py, view.py,
etc. A simple project structure is enough to create a single page application. Here are the
major files and there explanations. Inside the project folder there will be following files-
manage.py-This file is used to interact with your project via the command line(start the
server, sync the database… etc). For getting the full list of command that can be executed by
manage.py type this code in the command window-
$ python manage.py help
Project folder – This folder contains all the packages of your project. Initially it contains four
files –
• _init_.py – It is python package.
• settings.py – As the name indicates it contains all the website settings. In this file we
register any applications we create, the location of our static files, database configuration
details, etc.
• urls.py – In this file we store all links of the project and functions to call.
• wsgi.py – This file is used in deploying the project in WSGI. It is used to help your Django
application communicate with the web server.
Creating an App
To create an app, we can use the following command.
See the directory structure of the created app, it contains the migrations folder to store
migration files and model to write business logic.
Initially, all the files are empty, no code is available but we can use these to implement business
logic on the basis of the MVC design pattern.
To run this application, we need to make some significant changes which display hello
world message on the browser.
Open views.py file in any text editor and write the given code to it and do the same
for urls.py file too.
// views.py
def hello(request):
return HttpResponse("<h2>Hello, Welcome to Django!</h2>")
// urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', views.hello),
]
We have made changes in two files of the application. Now, let's run the it by using the
following command. This command will start the server at port 8000.
Run the Application
Python manage.py runserver
Open any web browser and enter the URL localhost:8000/hello.. It will show the output given
below.
HTTP Client-Server
Server Request – Response, concept of web
we
framework and web application
The client-server
server architecture includes two major components request and response. The
Django framework uses client-server
client server architecture to implement web applications.
When a client requests for a resource, a HttpRequest object is created and correspond view
function is called that returns HttpResponse object.
To handle request and response, Django provides HttpRequest and HttpResponse classes. Each
class has its own attributes and methods.
Django HttpRequest
This class is defined in the django.http module and used to handle the client request. Following
are the attributes of this class.
HttpRequest.path It returns the full path to the requested page does not
include the scheme or domain.
HttpRequest.content_type It shows the MIME type of the request, parsed from the
CONTENT_TYPE header.
def methodinfo(request):
return HttpResponse("Http request is: "+request.method)
// urls.py
path('info',views.methodinfo)
Start the server and get access to the browser. It shows the request method name at the
browser.
Output:
Django HttpResponse
This class is a part of django.http module. It is responsible for generating response corresponds
to the request and back to the client.
This class contains various attributes and methods that are given below.
Django HttpResponse Attributes
Attribute Description
We can use these methods and attributes to handle the response in the Django application.