You are on page 1of 35

Why do we need a Framework?

• To understand what Django is actually for,


• we need to know the servers. The first thing is that the
server needs to know serve a web page to the end user.
• Imagine a mailbox (port) which is monitored for incoming
letters (requests). This is done by a web server. The web
server reads the letter and then sends a response with a
webpage.
• But when you want to send something, you need to have
some content.
• And Django is something that helps you create the content.
What happens when someone requests a
website from your server?
• When a request comes to a web server, it's
passed to Django which tries to figure out what
is actually requested.
• It takes a web page address first and tries to
figure out what to do.
• This part is done by Django's urlresolver (note
that a website address is called a URL –
Uniform Resource Locator – so the
name urlresolver makes sense).
• Imagine a mail carrier with a letter. She is
walking down the street and checks each
house number against the one on the letter. If it
matches, she puts the letter there. This is how
the urlresolver works!
Django web framework
What is Django?
• Django is a free and open source web application
framework, written in Python.
• A web framework is a set of components that
helps you to develop websites faster and easier.
• When you're building a website, you always need
a similar set of components: a way to handle user
authentication, a management panel for your
website, forms, a way to upload files, etc.
Django web framework-contd.
• People long ago noticed that web developers
face some problems when building a new site,
so they teamed up and created frameworks that
give you ready-made components to use.
Django web framework-Contd.
• Django is a high level Python web framework
that encourages rapid development and clean
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.
Django web framework-Contd.
• Uses Of Django – Django is an open-
source python web framework used for rapid
development, pragmatic, maintainable, clean
design, and secures websites. A
web application framework is a toolkit of all
components need
for application development.
Django web framework-Contd.
• Django is a web application framework that
uses Python.
• Python is a programming language. Django is
a web framework which is coded in Python.
So, the difference is just like the difference
between a given programming language and
the software that is built using it.
Model-View-Controller
• The Model-View-Controller (MVC) is an architectural pattern
that separates an application into three main logical components:
• The model, the view, and the controller.
• Each of these components are built to handle specific
development aspects of an application.
• MVC is one of the most frequently used industry-standard web
development framework to create scalable and extensible
projects.
• MVC Components -Following are the components of MVC
Model
• The Model component corresponds to all the
data-related logic that the user works with.
• This can represent either the data that is being
transferred between the View and Controller
components or any other business logic-
related data.
• For example, a Customer object will retrieve
the customer information from the database,
manipulate it and update it (data back) to the
database or use it to render data.
View
• The View component is used for all the UI
logic of the application.
• For example, the Customer view will include
all the UI components such as text boxes,
dropdowns, etc. that the final user interacts
with.
Controller

• Controllers act as an interface between Model and


View components to process all the business logic and
incoming requests, manipulate data using the Model
component and interact with the Views to render the
final output.
• For example, the Customer controller will handle all
the interactions and inputs from the Customer View
and update the database using the Customer Model.
• The same controller will be used to view the Customer
data.
• Taken together, these pieces loosely follow a
pattern called Model-View-Controller (MVC).
• Simply put, MVC is way of developing software
so that the code for defining and accessing
• data (the model) is separate from request-
routing logic (the controller), which in turn is
separate from the user interface (the view).
DJANGO MVC - MVT Pattern

• The Model-View-Template (MVT) is slightly different


from MVC.
• In fact the main difference between the two patterns
is that Django itself takes care of the Controller part
(Software Code that controls the interactions
between the Model and View), leaving us with the
template.
• The template is a HTML file mixed with Django
Template Language (DTL).
The following diagram illustrates how each of the components of the MVT pattern interacts with each other to serve a user request −
The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user.
 
Python CGI Vs Python Web Framework
Approach
CGI
• Here’s a sample Python CGI script that displays the ten most recently published books
from a database. Don’t worry about syntax details; just get a feel for the basic things it’s doing.

#!/usr/bin/env python
import MySQLdb
print "Content-Type: text/html\n"
print "<html><head><title>Books</title></head>"
print "<body>"
print "<h1>Books</h1>"
print "<ul>"
connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db')
cursor = connection.cursor()
cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10")
for row in cursor.fetchall():
print "<li>%s</li>" % row[0]
print "</ul>"
print "</body></html>"
connection.close()

First, to fulfill the requirements of CGI, this code prints a “Content-Type” line, followed
by a blank line. It prints some introductory HTML, connects to a database, and runs a query to
retrieve the names of the latest ten books. Looping over those books, it generates an HTML list
of the titles. Finally, it prints the closing HTML and closes the database connection.
• It’s also simple to deploy: just save this code in
a file that ends with .cgi, upload that file to a
Web server, and visit that page with a browser.
• This approach has a number of problems. Ask
yourself these questions:
• What happens when multiple parts of your application need to
connect to the database?
• Surely that database-connecting code shouldn’t need to be
duplicated in each individual CGI script.
• The pragmatic thing to do would be to refactor it into a shared
function.
• What happens when this code is reused in multiple environments,
each with a separate database and password? At this point, some
environment-specific configuration becomes essential.
• These problems are precisely what a Web framework intends to
solve.
• A Web framework provides a programming infrastructure for your
applications so that you can focus on writing clean, maintainable
code.
The MVC Design Pattern
• The difference between the previous
approach and a Web framework’s approach.
Here’s how you might write the previous CGI
code using Django.
• The first thing to note is that we split it over
three Python files
• (models.py, views.py, urls.py) and an HTML
template (latest_books.html):
The MVC Design Pattern-contd.
• (models.py, views.py, urls.py) and an HTML
template (latest_books.html):
# models.py (the database tables)
from django.db import models
class Book(models.Model):
name = models.CharField(max_length=50)
pub_date = models.DateField()
# views.py (the business logic)
from django.shortcuts import
render_to_response
from models import Book
def latest_books(request):
book_list = Book.objects.order_by('-pub_date')[:10]
return render_to_response('latest_books.html',
{'book_list': book_list})
url.py
# urls.py (the URL configuration)
from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',(r'^latest/$',
views.latest_books),)
latest_books.html
# latest_books.html (the template)
<html><head><title>Books</title></head>
<body>
<h1>Books</h1>
<ul>
{% for book in book_list %}
<li>{{ book.name }}</li>
{% endfor %}
</ul>
</body></html>
Explanation
 The models.py file contains a description of
the database table, represented by a Python
class.
 This class is called a model. Using it, you can
create, retrieve, update, and delete records in
your database using simple Python code
rather than writing repetitive SQL statements.
 The views.py file contains the business logic
for the page. The latest_books() function
 is called a view.
 The urls.py file specifies which view is called
for a given URL pattern. In this case, the
 URL /latest/ will be handled by the
latest_books() function. In other words, if your
 domain is example.com, any visit to the URL
http://example.com/latest/ will call the
latest_books() function.
 The latest_books.html file is an HTML
template that describes the design of the
page.
 It uses a template language with basic logic
statements—for example, {% for book in
book_list %}.
Django supports four database engines

• PostgreSQL (http://www.postgresql.org/)
• SQLite 3 (http://www.sqlite.org/)
• MySQL (http://www.mysql.com/)
• Oracle (http://www.oracle.com/)

• Setting up the database is a two-step process:


1. First, you’ll need to install and configure the database server.
2. Second, you’ll need to install the Python library for your
particular database back-end. This is a third-party bit of code
that allows Python to interface with the database.
Starting a Project

• Once you’ve installed Python, Django, and


(optionally) your database server/library, you can
take the first step of developing a Django application
by creating a project.
• A project is a collection of settings for an instance of
Django, including database configuration, Django-
specific options, and application-specific settings.
• run the command django-admin.py startproject
mysite. This will create a mysite directory in your
current directory.
• The startproject command creates a directory
containing four files:
• mysite/
• __init__.py
• manage.py
• settings.py
• urls.py
These files are as follows:
• __init__.py: A file required for Python to treat the mysite
directory as a package (a group of Python modules). It’s
an empty file, and you normally won’t add anything to it.

• manage.py: A command-line utility that lets you interact


with this Django project in various ways. Type python
manage.py help to get a feel for what it can do. You
should never have to edit this file; it’s created in the
directory purely for convenience.
• settings.py: Settings/configuration for this Django
project. Take a look at it to get an idea of the types of
settings available, along with their default values.

• urls.py: The URLs for this Django project. Think of it as


the “table of contents” of your Django-powered site. At
the moment, it’s empty.

Despite their small size, these files already constitute a


working Django application.
• Running the Development Server. The
following command can be used.
python manage.py runserver

You might also like