Ch - 5 Advance Python
Ch - 5 Advance Python
Sem - 6
Introduction to Django
MVC Design Pattern
Django Installation
Starting project
Django project architecture
HTTP Client-Server Request – Response, concept of web framework and web
application.
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.
This framework uses a famous tag line:The web framework for perfectionists with
deadlines.
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.
History:
Django was design and developed by Lawrence journal world in 2003 and publicly
released under BSD license in July 2005. Currently, DSF (Django Software Foundation)
maintains its development and release cycle.
Django was released on 21, July 2005. Its current stable version is 2.0.3 which was
released on 6 March, 2018.
Page 1 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
Popularity:
Django is widely accepted and used by various well-known sites such as:
Instagram
Mozilla
Disqus
Pinterest
Bitbucket
The Washington Times
Features of Django:
1. 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.
2. Secure:
Django takes security seriously and helps developers to avoid many common security
mistakes, such as SQL injection, cross-site scripting, cross-site request forgery etc.
Its user authentication system provides a secure way to manage user accounts and
passwords.
3. Scalable:
Django is scalable in nature and has ability to quickly and flexibly switch from small to
large scale application project.
Page 2 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
4. 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.
5. Versatile:
Django is versatile in nature which allows it to build applications for different-different
domains.
Now a days, Companies are using Django to build various types of applications like:
content management systems, social networks sites or scientific computing platforms etc.
6. 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.
1. Model:
This handles your data representation, it serves as an interface to the data stored in the
database itself, and also allows you to interact with your data without having to
get perturbed with all the complexities of the underlying database.
2. View:
As the name implies, it represents what you see while on your browser for a web
application or In the UI for a desktop application.
3. Controller:
Provides the logic to either handle presentation flow in the view or update the model’s
data i.e it uses programmed logic to figure out what is pulled from the database through
the model and passed to the view,also gets information from the user through the view
Page 3 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
and implements the given logic by either changing the view or updating the data via the
model , To make it more simpler, see it as the engine room.
Now that we understand the general concept of the MVC, understanding how it is
implemented in different frameworks can be another task as some frameworks(Django
inclusive) like to implement this same functionality in another way making it a bit
difficult understanding what actually happens at each layer.
There’s a slight difference between Django’s MVC and MVT pattern.
In MVC pattern, the framework itself deals with the Controller part of the application.
While in MVT pattern, it leaves the Template part for the developers. Well, Controller is
that component of the software which regulates the interaction between the other
components, which are Model and View.
On the other hand, Template is a file written in HTML and DTL (Django Template
Language).
Django MVT:
The MVT (Model View Template) is a software design pattern.
It is a collection of three important components Model View and Template.
The Model helps to handle database.
It is a data access layer which handles the data.
The Template is a presentation layer which handles User Interface part completely.
The View is used to execute the business logic and interact with a model to carry data
and renders a template.
Although Django follows MVC pattern but maintains its? own conventions.
So, control is handled by the framework itself.
There is no separate controller and complete application is based on Model View and
Template. That?s why it is called MVT application.
See the following graph that shows the MVT based control flow.
Here, a user requests for a resource to the Django, Django works as a controller and
check to the available resource in URL.
Page 4 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
If URL maps, a view is called that interact with model and template, it renders a
template.
Django responds back to the user and sends a template as a response.
1. Model:
Just like the Model explanation in the MVC pattern , this also takes the same position as
the interface or relationship between the data and contains everything related to data
access and validation.
2. Template:
This relates to the View in the MVC pattern as it is the presentation layer that handles the
presentation logic in the framework and basically controls what should be displayed and
how it should be displayed to the user.
3. View:
This part relates to the Controller in the MVC pattern and handles all the business logic
that throws down back to the respective templates.
It serves as the bridge between the model and the template.
Django Installation:
1. Go to Windows Power Shell and execute as Administrator.
2. Go to C:\ root folder and type "Set-Execution-Policy Unrestricted" command. This will
allow you to write the command from anywhere. Say YES when it is asking for
confirmation
(Please note that if you don’t have Windows 10 / Power Shell, then you can go to
simple command prompt as well)
Page 5 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
For example, you are working on Python 3.8 but some company wants to develop
website in Python 2.7, here the syntax is different. Then how to cope up with this
situation. Virtual environment helps in this situation.
Create a folder for installing Virtual Environment and go inside that folder. In our
case the folder is “BCA”. Now give following command.
D:\BCA>pip install virtualenv
Go to the “Scripts” folder which is created inside “BCA” folder and run “activate”
file. D:\BCA\Scripts>activate
It will look as
follows (BCA)
D:\BCA\Scripts>
This means your virtual environment has started now. Now whatever you do, will be
for this particular environment only.
Note: You can write “deactivate” after your work is over to deactivate the virtual
environment.
6. Install “Django” in your python virtual environment. If don’t have virtual environment,
then also can do the same step.
(BCA) D:\BCA> pip install django
Page 6 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
Note : Remember that if you have installed virtual environment, then it will install
django again for that virtual environment even though you have installed it.
Note : If you want to confirm that Django is installed or not, go to “Scripts” folder.
There you will see a file called “django-admin”. It indicates that django has been
installed. That file will be used for further commands of django to create project and
all.
Starting Project:
We have installed Django successfully. Now, we will learn step by step process to create
a Django application.
To create a Django project, we can use the following command.
Projectname is the name of Django application.
django-admin startproject projectname
A directory (djangpapp) located inside, is the actual application package name. Its name
is the Python package name which we'll need to use to import module inside the
application.
2. __init__.py: It is an empty file that tells to the Python that this directory should be
considered as a Python package.
Page 7 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
Initially, this project is a default draft which contains all the required files and folders.
Look server has started and can be accessed at localhost with port 8000. Let's access it
using the browser, it looks like the below.
Page 8 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
It prompts for login credentials if no password is created yet, use the following command
to create a user.
Migrations:
Migration is a way of applying changes that we have made to a model, into the database
schema.
Django creates a migration file inside the migration folder for each model to create the
table schema, and each table is mapped to the model of which migration is created.
Django provides the various commands that are used to perform migration related tasks.
After creating a model, we can use these commands.
Page 9 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
1. makemigrations : It is used to create a migration file that contains code for the tabled
schema of a model.
2. migrate : It creates table according to the schema defined in the migration file.
3. sqlmigrate : It is used to show a raw SQL query of the applied migration.
4. showmigrations : It lists out all the migrations and their status.
You are required to launch the server so that you can access your admin interface. The
following command will help you to initiate the database:
python manage.py migrate
To create all the necessary tables or collections as required by your admin interface, you
need to use syncdb.
This command works as per your database type.
In case, if you haven’t created any superuser yet, then you will be prompted to create one.
To create a superuser, run the following command on the terminal.
python manage.py createsuperuser
Page 10 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
It is a Django Admin Dashboard. Here, we can add and update the registered models.
Django App:
We have seen a procedure to create a Django project. Now, in this topic, we will create
app inside the created project.
Django application consists of project and app, it also generates an automatic base
directory for the app, so we can focus on writing code (business logic) rather than
creating app directories.
The difference between a project and app is, a project is a collection of configuration files
and apps whereas the app is a web application which is written to perform business logic.
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.
Page 11 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
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
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.
Open any web browser and enter the URL localhost:8000/hello. It will show the output
given below.
Page 12 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
class Employee(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
The first_name and last_name fields are specified as class attributes and each attribute
maps to a database column.
This model will create a table into the database that looks like below.
Page 13 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
Page 14 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
Page 15 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
Field Options:
Each field requires some arguments that are used to set column attributes. For example,
CharField requires mac_length to specify varchar database.
Common arguments available to all field types. All are optional.
//models.py
class Student(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=30)
contact = models.IntegerField()
email = models.EmailField(max_length=50)
age = models.IntegerField()
//admin.py
admin.site.register(Student)
Page 16 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
DATABASES = {
'default': {
'ENGINE':'django.db.backends. mysql',
'NAME': 'abc',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS':{
'init_command':”SET sql_mode='STRICT_TRANS_TABLES'”
}
}
}
Migrating Database:
This will create several tables in your “mysql”.
Remember that we have given the name of our database as “abc”.
So before migrating project, you should create a database in mysql with name “abc”.
First you need to inform Django that you have several models.
For that you give following commands
It will create a table Student. The table structure looks like the below.
Page 17 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
2. Django Views:
A view is a place where we put our business logic of the application.
The view is a python function which is used to perform some business logic and return a
response to the user.
This response can be the HTML contents of a Web page, or a redirect, or a 404 error.
All the view function are created inside the views.py file of the Django app.
//views.py
import datetime
# Create your views here.
from django.http import HttpResponse
def index(request):
now = datetime.datetime.now()
html = "<html><body><h3>Now time is %s.</h3></body></html>" % now
return HttpResponse(html) # rendering the template in HttpResponse
Page 18 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
path('index/', views.index),
Output:
3. Django Templates:
Django provides a convenient way to generate dynamic HTML pages by using its
template system.
A template consists of static parts of the desired HTML output as well as some special
syntax describing how dynamic content will be inserted.
Page 19 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
],
},
},
]
Page 20 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
Page 21 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
// index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h2>Welcome to Django!!!</h2>
</body>
</html>
Loading Template:
To load the template, call get_template() method as we did below and pass template
name.
//views.py
//urls.py
path('index/', views.index),
Register app inside the INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'
]
Page 22 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
Run Server:
Execute the following command and access the template by
entering localhost:8000/index at the browser.
Page 23 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
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.
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.
Page 24 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
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 (location) It returns the absolute URI form of
location.
HttpRequest.get_signed_cookie (key, It returns a cookie value for a signed
default=RAISE_ERROR, salt='', cookie, or raises a
max_age=None) django.core.signing.BadSignature
exception if the 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.
// 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:
Page 25 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
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.
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.
Method Description
HttpResponse.__init__(content='', It is used to instantiate an HttpResponse
content_type=None, status=200, object with the given page content and
reason=None, charset=None) content type.
HttpResponse.__setitem__(header, value) It is used to set the given header name to
the 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.
Page 26 of 27
Subject: ADVANCE PYTHON Chapter - 5 B.C.A. Sem - 6
We can use these methods and attributes to handle the response in the Django
application.
Page 27 of 27