0% found this document useful (0 votes)
3 views21 pages

Advance Python Unit - 5

Django is a Python-based web application framework that follows the MVT design pattern, facilitating rapid development and scalability. It includes built-in components for user authentication, an admin interface, and supports multiple database backends. The document also covers installation, project setup, and the MVC design pattern, providing a comprehensive overview of Django's features and functionalities.

Uploaded by

disecek477
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)
3 views21 pages

Advance Python Unit - 5

Django is a Python-based web application framework that follows the MVT design pattern, facilitating rapid development and scalability. It includes built-in components for user authentication, an admin interface, and supports multiple database backends. The document also covers installation, project setup, and the MVC design pattern, providing a comprehensive overview of Django's features and functionalities.

Uploaded by

disecek477
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/ 21

UNIT 5

Introduction to web Framework Django

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?

1. It’s very easy to switch database in Django framework.


2. It has built-in admin interface which makes easy to work with it.
3. Django is fully functional framework that requires nothing else.
4. It has thousands of additional packages available.
5. It is very scalable.

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.

MVC Design Pattern


The Model View Controller (MVC) design pattern specifies that an application consist of a data
model, presentation information, and control information. The pattern requires that each of
these be separated into different objects.
MVC is more of an architectural pattern, but not for complete application. MVC mostly relates
to the UI / interaction layer of an application. You’re still going to need business logic layer,
maybe some service layer and data access layer.
UML Diagram MVC Design Pattern

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;

public String getRollNo()


{
return rollNo;
}

public void setRollNo(String rollNo)


{
this.rollNo = rollNo;
}

public String getName()


{
return name;
}

public void setName(String name)


{
this.name = 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;

public StudentController(Student model, StudentView view)


{
this.model = model;
this.view = view;
}

public void setStudentName(String name)


{
model.setName(name);
}
public String getStudentName()
{
return model.getName();
}

public void setStudentRollNo(String rollNo)


{
model.setRollNo(rollNo);
}

public String getStudentRollNo()


{
return model.getRollNo();
}

public void updateView()


{
view.printStudentDetails(model.getName(), model.getRollNo());
}
}

class MVCPattern
{
public static void main(String[] args)
{
Student model = retriveStudentFromDatabase();

StudentView view = new StudentView();

StudentController controller = new StudentController(model, view);

controller.updateView();

controller.setStudentName("Vikram Sharma");

controller.updateView();
}

private static Student retriveStudentFromDatabase()


{
Student student = new Student();
student.setName("Lokesh Sharma");
student.setRollNo("15UCS157");
return student;
}

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.

Now follow the simple three-step process:


1. Install Python
2. Install a Python Virtual Environment; and
3. Install Django

How to install Django on Windows


This document will guide you through installing Python 3.8 and Django on Windows. It also
provides instructions for setting up a virtual environment, which makes it easier to work on
Python projects. This is meant as a beginner’s guide for users working on Django projects and
does not reflect how Django should be installed when developing patches for Django itself.

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.

To install Python on your machine go to https://python.org/downloads/. The website should


offer you a download button for the latest Python version. Download the executable installer
and run it. Check the boxes next to “Install launcher for all users (recommended)” then click
“Install Now”.

After installation, open the command prompt and check that the Python version matches the
version you installed by executing:

...\> python --version


About pip

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.

Setting up a virtual environment

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:

...\> python -m venv project-name

In another drive

...\> python -m venv d:\\project-name

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:

...\> python -m pip install Django

This will download and install the latest Django release.

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

The Project Structure


The “myproject” folder is just your project container, it actually contains two elements −
• manage.py − This file is kind of your project local django-admin for interacting with
your project via command line (start the development server, sync db...). To get a full
list of command accessible via manage.py you can use the code −
$ python manage.py help
• The “myproject” subfolder − This folder is the actual python package of your project. It
contains four files −
o __init__.py − Just for python, treat this folder as package.
o settings.py − As the name indicates, your project sePngs.
o urls.py − All links of your project and the funcQon to call. A kind of ToC of your
project.
o wsgi.py − If you need to deploy your project over WSGI.
Setting Up Your Project
Your project is set up in the subfolder myproject/settings.py. Following are some important
options you might need to set −
DEBUG = True
This option lets you set if your project is in debug mode or not. Debug mode lets you get more
information about your project's error. Never set it to ‘True’ for a live project. However, this
has to be set to ‘True’ if you want the Django light server to serve static files. Do it only in the
development mode.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'database.sql',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}

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.

Get the Project to Know About Your Application


At this stage we have our "myapp" application, now we need to register it with our Django
project "myproject". To do so, update INSTALLED_APPS tuple in the settings.py file of your
project (add your app name) −
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
)
Django provides a ready-to-use user interface for administrative activities. We all know how an
admin interface is important for a web project. Django automatically generates admin UI
based on your project models.

Starting the Admin Interface


The Admin interface depends on the django.countrib module. To have it working you need to
make sure some modules are imported in the INSTALLED_APPS and MIDDLEWARE_CLASSES
tuples of the myproject/settings.py file.
For INSTALLED_APPS make sure you have −

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

from django.contrib import admin


admin.autodiscover()

urlpatterns = patterns('',
# Examples:
# url(r'^$', 'myproject.views.home', name = 'home'),
# url(r'^blog/', include('blog.urls')),

url(r'^admin/', include(admin.site.urls)),
)

Now just run the server.


python manage.py runserver
And your admin interface is accessible at: http://127.0.0.1:8000/admin/

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.

MVT Structure has the following three parts –

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.

python manage.py startapp appname


Django App Example
python manage.py startapp myapp

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

from django.shortcuts import render

# Create your views here.


from django.http import HttpResponse

def hello(request):
return HttpResponse("<h2>Hello, Welcome to Django!</h2>")

// urls.py

from django.contrib import admin


from django.urls import path
from myapp import views

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.

Django HttpRequest Attributes


Attribute Description

HttpRequest.scheme A string representing the scheme of the request (HTTP


or HTTPs usually).

HttpRequest.body It returns the raw HTTP request body as a byte string.

HttpRequest.path It returns the full path to the requested page does not
include the scheme or domain.

HttpRequest.path_info It shows path info portion of the path.

HttpRequest.method It shows the HTTP method used in the request.

HttpRequest.encoding It shows the current encoding used to decode form


submission data.

HttpRequest.content_type It shows the MIME type of the request, parsed from the
CONTENT_TYPE header.

HttpRequest.content_params It returns a dictionary of key/value parameters included


in the CONTENT_TYPE header.

HttpRequest.GET It returns a dictionary-like object containing all given


HTTP GET parameters.
HttpRequest.POST It is a dictionary-like object containing all given HTTP
POST parameters.

HttpRequest.COOKIES It returns all cookies available.

HttpRequest.FILES It contains all uploaded files.

HttpRequest.META It shows all available Http headers.

HttpRequest.resolver_match It contains an instance of ResolverMatch representing


the resolved URL.

And the following table contains the methods of HttpRequest class.

Django HttpRequest Methods


Attribute Description

HttpRequest.get_host() It returns the original host of the request.

HttpRequest.get_port() It returns the originating port of the request.

HttpRequest.get_full_path() It returns the path, plus an appended query string, if


applicable.

HttpRequest.build_absolute_uri It returns the absolute URI form of location.


(location)

HttpRequest.get_signed_cookie It returns a cookie value for a signed cookie, or raises


(key, default=RAISE_ERROR, a django.core.signing.BadSignature exception if the
salt='', max_age=None) signature is no longer valid.
HttpRequest.is_secure() It returns True if the request is secure; that is, if it was
made with HTTPS.

HttpRequest.is_ajax() It returns True if the request was made via an


XMLHttpRequest.

Django HttpRequest Example


// views.py

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

HttpResponse.content A bytestring representing the content, encoded


from a string if necessary.

HttpResponse.charset It is a string denoting the charset in which the


response will be encoded.

HttpResponse.status_code It is an HTTP status code for the response.

HttpResponse.reason_phrase The HTTP reason phrase for the response.

HttpResponse.streaming It is false by default.

HttpResponse.closed It is True if the response has been closed.

Django HttpResponse Methods


Method Description

HttpResponse.__init__(content='', It is used to instantiate an HttpResponse object


content_type=None, status=200, with the given page content and content type.
reason=None, charset=None)

HttpResponse.__setitem__(header, It is used to set the given header name to the


value) given value.

HttpResponse.__delitem__(header) It deletes the header with the given name.


HttpResponse.__getitem__(header) It returns the value for the given header name.

HttpResponse.has_header(header) It returns either True or False based on a case-


insensitive check for a header with the provided
name.

HttpResponse.setdefault(header, value) It is used to set default header.

HttpResponse.write(content) It is used to create response object of file-like


object.

HttpResponse.flush() It is used to flush the response object.

HttpResponse.tell() This method makes an HttpResponse instance a


file-like object.

HttpResponse.getvalue() It is used to get the value of


HttpResponse.content.

HttpResponse.readable() This method is used to create stream-like object


of HttpResponse class.

HttpResponse.seekable() It is used to make response object seekable.

We can use these methods and attributes to handle the response in the Django application.

You might also like