The Django Web Application
Framework
Vu Dinh Hong
2021
Outline
ü Overview
ü Architecture
ü Modules
ü Example
ü Links
Outline
ü Overview
ü Architecture
ü Example
ü Modules
ü Links
Web Application Framework
Ø Define
“A software framework that is designed to support the development of
dynamic website, Web applications and Web services”(from wikipedia)
Ø The ideal framework
p Clean URLs
p Loosely coupled components
p Designer-friendly templates
p As little code as possible
p Really fast development
Web Application Framework(cont..)
Ø Ruby
Ruby on Rails (famous, beauty)
Ø Python
Django, TurboGears, Pylons, Zope, Quixote,web2py(simple)
Ø PHP
CakePHP, CodeIgniter, PRADO, ThinkPHP,QeePHP (poor performance)
Ø Others
Apache, J2EE, .NET...(complex)
Web Application Framework(cont..)
Comparsion
What a Django
Ø “Django is a high-level Python web framework that
encourages rapid development and clean, pragmatic
design.”
Ø Primary Focus
p Dynamic and database driven website
p Content based websites
Django History
Ø Named after famous Guitarist “Django Reinhardt”
Ø Developed by Adrian Holovaty & Jacob Kaplan-moss
Ø Open sourced in 2005
Ø 1.0 Version released Sep.3 2008, now 1.1 Beta
Why Use Django
Ø Lets you divide code modules into logical groups to make it flexible
to change
MVC design pattern (MVT)
Ø Provides auto generated web admin to ease the website
administration
Ø Provides pre-packaged API for common user tasks
Ø Provides you template system to define HTML template for your
web pages to avoid code duplication
DRY Principle
Ø Allows you to define what URL be for a given Function
Loosely Coupled Principle
Ø Allows you to separate business logic from the HTML
Separation of concerns
Ø Everything is in python (schema/settings)
Outline
ü Overview
ü Architecture
ü Modules
ü Example
ü Links
Django as an MVC Design Pattern
MVT Architecture:
p Models
Describes your data structure/database schema
p Views
Controls what a user sees
p Templates
How a user sees it
p Controller
The Django Framework
URL dispatcher
Django Project Layout
[Link] startproject
<PROJECT_ROOT>
[Link]
<PROJECT_DIR>
__init__.py
[Link]
[Link]
[Link]
[Link]
Ø Defines settings used by a Django application
Ø Referenced by [Link] to bootstrap the project
loading
Ø Techniques for managing dev vs prod settings:
p Create [Link] and [Link] and use symlink to link
[Link] to the correct settings
p Factor out common settings into [Link] and import. Use
conditionals to load correct settings based on DEBUG or other setting
Sample Settings…
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
)
Django Apps
Ø Reusable modules
Ø [Link] startapp <APP_NAME>
Ø Creates stub layout:
<APP_NAME>
[Link]
[Link]
templates (directory)
[Link]
[Link]
[Link]
Architecture Diagram
Brower
Template URL dispatcher
View
Model
DataBase
Model
Brower
Template URL dispatcher
View
Model
DataBase
Model Overview
SQL Free
ORM
Relations
API
Django Models
Ø Defined in [Link]
Ø Typically inherit from [Link]
Example Model:
from [Link] import models
class TestModel([Link]):
name = [Link](max_length = 20)
age = [Link]()
Models (cont’d)
Ø Default is to set NOT NULL on all fields. Override by
adding null = True to field definition:
name = [Link](max_length=20, null =
True)
Ø Relationships defined through special field types:
[Link](model)
[Link](model)
[Link](model)
Models (cont’)
Ø Need Nulls in a Boolean Field? Use
[Link]()
Ø Set Default value with “default”:
count = [Link](default = 0)
Ø Use a inner Meta class to define additional options,
especially useful for abstract classes:
class TestModel([Link]):
class Meta:
abstract = True
Model Methods
Ø [Link](self, *args, **kwargs)
Ø [Link](self, *args, **kwargs)
Ø model.get_absolute_url(self)
Ø model.__str__(self) [Python 3]
model.__unicode__(self) [Python 2]
Ø Override with super(MODEL, self).save(*args,
**kwargs)
Activating a Model
Ø Add the app to INSTALLED_APPS in [Link]
Ø Run [Link] makemigrations
Ø Run [Link] migrate
Selecting Objects
Ø Models include a default manager called objects
Ø Manager methods allow selecting all or some
instances
[Link]()
[Link](pk = 1)
Use try block, throws DoesNotExist
exception if no match
[Link](created_date__lt = ‘2014-
01-01’)
Ø Returns QuerySet
Introspecting Legacy Models
Ø [Link] inspectdb
Ø It will generate code for models.
Ø Cut and paste generated code into [Link] –
Easy!!
Full Sample
from [Link] import models
from datetime import datetime
class TimestampedModel([Link]):
created_datetime = [Link]()
updated_datetime = [Link]()
def save(self, *args, **kwargs):
if [Link] is None:
self.created_datetime = [Link]()
updated_datetime = [Link]()
super(TimestampedModel,self).save(*args, **kwargs)
class Meta:
abstract = True
Full Sample (cont’d)
class Question(TimestampedModel):
question_text = [Link](max_length = 200)
def __str__(self):
return self.question_text
Other model example
class Category([Link]):
name = [Link](max_length=200)
slug = [Link](unique=True)
class Entry([Link]):
title = [Link](max_length=200)
slug = [Link](unique=True)
body = [Link]()
data = [Link](default=[Link])
categories = [Link](Category)
python [Link] makemigrations
python [Link] migrate
Model API
>>> category = Category(slug='django', name='Django')
>>> [Link]()
>>> print [Link]
u'Django'
>>> categories = [Link]()
>>> categories = [Link](slug='django')
>>> categories
[<Category: Category object>]
>>> entry = Entry(slug='welcome', title='Welcome', body='')
>>> [Link]()
>>> [Link]( category[0] )
>>> print [Link]()
[<Category: Category object>]
View
Brower
Template URL dispatcher
View
Model
DataBase
Function vs. Class Views
Ø Django allows two styles of views – functions or class
based views
Ø Functions – take a request object as the first
parameter and must return a response object
Ø Class based views – allow CRUD operations with
minimal code. Can inherit from multiple generic
view classes (i.e. Mixins)
View
from [Link] import get_object_or_404, render
def entry_list(request):
entries = [Link]()[:5]
return render('[Link]', {'entries': entries})
def entry_details(request, slug):
entry = get_object_or_404(Entry, slug = slug)
return render('[Link]', {'entry': entry})
Sample – Viewing a List of Questions
Ø Function based:
from .models import Question
from [Link] import render
def question_list(request):
questions = [Link]()
return render(‘question_list.html’, {
‘questions’:questions})
Quick CRUD Operations with Generic Views
Ø ListView
Ø UpdateView
Ø CreateView
Ø If Model is specified, automagically creates a
matching ModelForm
Ø Form will save the Model if data passes validation
Ø Override form_valid() method to provide custom
logic (i.e sending email or setting additional fields)
Sample – As Class Based View
from .models import Question
from [Link] import ListView
class QuestionList(ListView):
model = Question
context_object_name = ‘questions’
Template
Brower
Template URL dispatcher
View
Model
DataBase
Django Templates
Ø Very simple syntax:
variables = {{variable_name}}
template tags = {%tag%}
Ø Flexible – can be used to render html, text, csv,
email, you name it!
Ø Dot notation – template engine attempts to resolve
by looking for matching attributes, hashes and
methods
Question List Template
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>List of Questions</title>
</head>
<body>
{%if questions%}
<ul>
{%for q in questions%}
<li>{{q.question_text}}</li>
{%endfor%}
</ul>
{%else%}
<p>No questions have been defined</p>
{%endif%}
</body>
</html>
Custom tags, filters
Custom tags, filters
Custom tags, filters
Template Syntax
Ø {{ variables }}, {% tags %}, filters ([Link])
<html>
<head>
<title>My Blog</title>
</head>
<body>
{% for entry in entries %}
<h1>{{ [Link]|upper }}</h1>
{{ [Link] }}<br/>
Published {{ [Link]|date:"d F Y" }},
<a href=”{{ entry.get_absolute_url }}”>link</a>.
{% endfor %}
</body>
</html>
Tag and Filter
Ø Build in Filters and Tags
Ø Custom tag and filter libraries
Put logic in tags
{% load comments %}
<h1>{{ [Link]|upper }}</h1>
{{ [Link] }}<br/>
Published {{ [Link]|date:"d F Y" }},
<a href=”{{ entry.get_absolute_url }}”>link</a>.
<h3>评论: </h3>
{% get_comment_list for entry as comment_list %}
{% for comment in comment_list %}
{{ [Link] }}
{% endfor %}
Template Inheritance
[Link] [Link]
<html>
<head>
<title>
{% extend “[Link]” %}
{% block title %}
{% block title %}
{% endblock %}
Main page
</title>
{% endblock %}
</head>
{% block body %}
<body>
Content
{% block body %}
{% endblock %}
{% endblock %}
</body>
</html>
URL Dispatcher
Brower
Template URL Dispatcher
View
Model
DataBase
[Link]
Ø Defines routes to send urls to various views
Ø Can use regular expressions
Ø Extract parameters from a url and pass to the view as
a named parameter:
r(‘^question/(?P<question_id>\d+)/$’,’views.question_
detail’)
Ø Extensible – [Link] can include additional url files
from apps:
r(‘^question/’,include([Link]))
Hooking up the Question List
from [Link] import patterns, url, include
urlpatterns = patterns(‘’,
(r’^questions/$’,’[Link]’)
)
OR:
from [Link] import patterns
from views import QuestionList
urlpatterns = patterns(‘’,
(r’^questions/$’,QuestionList.as_view())
)
URL Dispatcher
#[Link]
urlpatterns = patterns('', ((r'^articles/$', ‘[Link]'), )
#[Link]
(r'^articles/(?P<year>\d{4})/$', ‘[Link].year_archive'),
# [Link] 12/
(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$',
'[Link].month_archive'),
# [Link] 12/3
(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$',
'article..views.article_detail'), )
Outline
ü Overview
ü Architecture
ü Modules
ü Example
ü Links
Modules
Ø Form
Ø Adminstration interface
Ø Custom Middleware
Ø Caching
Ø Signals
Ø Comments system
Ø More...
Forms in Django
Ø [Link] provides a class to build HTML forms
and validation. Example:
from django import forms
class EditQuestionForm([Link]):
question_text = [Link](max_length = 200)
Ø Often redundant when creating forms that work on a
single model
ModelForms
Ø Automatically generate a form from a model.
Ø Handles saving a bound model
Ø Can specify fields to be included or excluded in the form
Ø Sample:
from [Link] import ModelForm
from .models import Question
class QuestionForm(ModelForm):
class Meta:
model = Question
fields = [‘question_text’]
Using a ModelForm
Ø Create an instance of an empty form:
form = QuestionForm()
Ø Create a form to update an existing instance of a model:
question = [Link](pk = 1)
form = QuestionForm(instance = question)
Ø Pass the form into the template and use the form
methods to render the form:
form.as_p
form.as_ul
form.<field_name>
form.<field_name>.errors
Modules:Form
class ContactForm([Link]):
subject = [Link](max_length=100)
message = [Link](widget=[Link])
sender = [Link]()
cc_myself = [Link](required=False)
<form action="/contact/" method="POST">
{{ form.as_table}}
<input type="submit" value="Submit" />
</form>
Modules:Adminstration interface
Modules: Custom Middleware
chain of processes
request Common Session Authentication Profile response
Middleware Middleware Middleware Middleware
Modules: Caching
Memcached Database Filesystem Local-memory Dummy
BaseCache
template caching
Per-Site Caching Per-View Caching
Modules:More...
Ø Sessions
Ø Authentication system
Ø Internationalization and localization
Ø Syndication feeds(RSS/Atom)
Ø E-mail(sending)
Ø Pagination
Ø Signals
Authentication
Ø Django’s out of the box Auth system uses database
authentication.
Ø Changed extensively in Django 1.6 to allow custom
User objects.
Ø AUTHENTICATION_BACKENDS setting in [Link]
allows overriding how User objects are authenticated
Ø If using the Authentication middleware and
context_processors the current user is available to
code as [Link] and {{user}} is defined in all
templates
Auth Decorators
Ø Live in [Link]
Ø login_required
@login_required
def function_view(request):
….
Ø user_passes_test (can be used with lambda functions for
real power) –
@user_passes_test(lambda u: u.is_staff)
def function_view(request):
…
Ø has_perms – test for user permissions
Decorating CBVs
Ø Decorator is applied to the dispatch method
Ø Must be converted to a method_decorator – use
[Link].method_decorator function:
class MyView(ListView):
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
super(MyView,self).dispatch(*args, **kwargs)
Custom Auth Backend for the Bubble
Add to [Link]
AUTHENTICATION_BACKENDS = [‘[Link]']
Sending Email
Ø [Link] includes functions and classes for
handling email
Ø Set EMAIL_HOST in [Link] to outgoing
mailserver
Ø Import send_mail for simple mail:
send_mail(subject, message, from, to_emails)
Ø Use [Link].render_to_string to format a
message using a template
Ø Use EmailMultiAlternatives to create a text message
and attach a html version as well.
Outline
ü Overview
ü Architecture
ü Modules
ü Example
ü Links
Example
Ø django_admin startproject leyubbs
Ø modify [Link]
p set database options
p append admin app: [Link]
Ø Run makemigrations and migrate
Ø python [Link] runserver
Ø modify [Link], append /admin path
Example(cont...)
Ø python [Link] startapp article
Ø add a model
Ø Run makemigrations and migrate
Ø explore admin page
Ø inset a record in adminstration interface
Ø add a veiw function
Ø add a url
Outline
ü Overview
ü Architecture
ü Modules
ü Example
ü Links
Links: Who Use
Links: Resource
Ø [Link]
For more information (Documentation,Download and News)
Ø [Link]
A Good book to learn Django
Ø [Link]
A lot of Django Pluggables available online Explore at
Ø [Link]
Community Development
Thanks (Q&A)