Django
Build an organized web application
Outline
1. Introduction
2. Basic Knowledge
3. Technical Details
4. Tutorial
5. Conclusion
Outline
1. Introduction
2. Basic Knowledge
3. Technical Details
4. Tutorial
5. Conclusion
Introduction
What is Django?
A high-level Python Web Framework
What is Django
“Django is a high-level Python web framework that
encourages rapid development and clean, pragmatic
design.”
Primary Focus
Dynamic and database driven website
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 2.14
Introduction
What is Framework?
Front-end & Back-end co-development
Introduction
What is Framework like?
A stage company for performers
Introduction
Why should I use Django?
Clean & Rapid development
Introduction
Who use Django?
Instagram & Pinterest & Bitbucket
Outline
1. Introduction
2. Basic Knowledge
3. Technical Details
4. Tutorial
5. Conclusion
Outline
1. Introduction
2. Basic Knowledge
3. Technical Details
4. Tutorial
5. Conclusion
Basic Knowledge
Basic Knowledge
Workflow
Web Browser
Template URL
View
Form
Model
Admin
Database
Basic Knowledge
Web Browser Web Browser
Template URL
• What users actually see
• Responds to what users do
View
when they
Form
Model 1. Click
2. Type
Admin
3. Press Enter
Database
Basic Knowledge
Web Browser URL
Template
• Often referred as the ‘web
URL
address’
View
• Provides mapping to View
Form
Model
What is mapping?
Admin The act of assigning
functions to URLs
Database
Basic Knowledge
Web Browser View
• Where all the functions are
Template URL
written
View
• Render content to Template
Form Get information from Model
•
Model before rendering content
• Put information into Model and
Admin
into Database through Form
Database
Basic Knowledge
Web Browser Template
• The place you systematically
Template URL
store all of your Html files
View
• You will have a ‘static’ folder to
Form store other CSS files,
Model Javascript files, or Images
Admin
Database
Basic Knowledge
Web Browser Form
Template URL HTML Form ≠ Django Form
View HTML Form
Form Consists of
• input element
Model • checkbox
• submit button
Admin
• radio button
Database and much more
•
Basic Knowledge
Web Browser Form
Template URL HTML Form ≠ Django Form
View Django Form
Form Aims to
• fetch data from html form
Model
• helps to connect to Model
Admin
Database
Basic Knowledge
Web Browser Model
• Describes the structure of an
Template URL
object you want to store in
View
Database
Form
• Goes straight to Database
Model and create & edit & request
Admin information as you wish
Database
Basic Knowledge
Web Browser Admin
Template URL
• Helps to register your object
in your Model so you can
View
manage data in Database
Form
• The registration has to be
Model
done in the first place
Admin
Database
Basic Knowledge
Web Browser Database
Template URL
View
Model
Form
Admin
?
Database
Basic Knowledge
Web Browser Database
Template URL
View
Form Collection of data
Model
Admin
Database
Basic Knowledge
Web Browser Database
• Collectionof data
Template URL
• Provided with a wonderful
View
back-end platform for easy
Form
management
Model
Admin
Database
Basic Knowledge
Workflow
Web Browser
Template URL
View
Form
Model
Admin
Database
Outline
1. Introduction
2. Basic Knowledge
3. Technical Details
4. Tutorial
5. Conclusion
Technical Details
1. Directory Architecture
2. Module
3. Commands
4. Template Tags
5. High-level URL Configuration
Technical Details
Directory Architecture
project_name/ ———————— Container of your entire project, which often referred as ‘workspace’
[Link] ————— The command-line utility to interact with your Django project
E.g1. python [Link] help E.g2. python [Link] runserver -h
your_project/ ———— The name of your Django project
inti .py ——- The file required for Python to treat this directory as a package
[Link] ——- Configuration for this Django project
[Link] ————- Management of URLs to provide mapping to [Link]
your_app/ —————- One of the web applications of this Django project
inti .py
migration/ ——- The file which stores all the variations in your database
static/ ———— The file which stores all of your CSS, JS, images
templates/ ——- The file which stores all of your Html
[Link] ——— It reads your model and provides interface to your database
[Link] ———- It is used to fetch data and performs validation
[Link] ——— Description of the format or structure of an object stored in Database
[Link] ——— All the functions needed to process or respond user’s request
db.sqlite3 ——- Your database
Technical Details
1. Directory Architecture
2. Module
3. Commands
4. Template Tags
5. High-level URL Configuration
Technical Details
Module
mypackage/
init .py
[Link]
• A module is a python source file
• A package is a directory of Python module(s)
Technical Details
1. Directory Architecture
2. Module
3. Commands
4. Template Tags
5. High-level URL Configuration
Technical Details
Commands
$ django-admin startproject project_name
To start an project
Technical Details
Commands
$ python [Link] startapp app_name
To start an application
Technical Details
Commands
$ python [Link] createsuperuser
To create a superuser
Technical Details
Commands
$ python [Link] run server [Link]:8080
To start up your server
Note: [Link]:8080 —> address:port
Technical Details
Commands
$ python [Link] makemigrations
To create new migration based on the changes you
made in your models
$ python [Link] migrate
To apply migration into your database
Note: Migration is Django’s way of propagating the changes you made into your database schema
Technical Details
Commands
$ python [Link] -h
To ask for what kind of command can be used
$ python [Link] runserver -h
To ask for what kind of command can be used
after runserver
Technical Details
1. Directory Architecture
2. Module
3. Commands
4. Template Tags
5. High-level URL Configuration
Technical Details
Template Tags
{% for object in objects %}
{{ [Link] }}
{% endfor %}
Django saves you the trouble of repeating your codes
Technical Details
Template Tags
{{ form.as_p }}
This is Django’s way of rendering Html Form
Note: Remember to wrap it within your HTML form tag
Technical Details
Template Tags
{{ csrf_token }}
This is used prevent ill-intentioned hacker from
hacking into your database
Note: Remember to wrap it within your HTML form tag
Django Project Level operations for Apps:
• Django-admin start project Mysite
• Python [Link] startapp polls
• Python [Link] runserver
• Python [Link] [Link]
• Python [Link] collectstatic
• Python [Link] compilemessages
• Python [Link] makemigrations
• Python [Link] migrate
• Python [Link]
createsuperuser|changepassword|loaddata
Django as an MVC
Design Pattern
MVT Architecture:
Models
Describes your data structure/database schema
Views
Controls what a user sees
Templates
How a user sees it
Controller
The Django Framework
URL dispatcher
Model Overview
Model
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] syncdb
View
def entry_list(request):
entries = [Link]()[:5]
return render_to_response('[Link]', {'entries': entries})
def entry_details(request, slug):
entry = get_object_or_404(Entry, slug = slug)
return render_to_response('[Link]', {'entry': entry})
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
urlpatterns = patterns('',
#[Link]
((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'), )
High-levelURL Configuration
url(r'^$', [Link])
?P< v > : to take v and sent to view as a variable
^ : beginning of the url
$ : end of the url
() : to capture part of the pattern
+ : to indicate the previous item should repeat at
least once
{} : to indicate a specific number of repetition
High-levelURL Configuration
url(r’^anything/(?P<variable>[0-9]+)/$’, [Link])
?P< v > : to take v and sent to view as a variable
^ : beginning of the url
$ : end of the url
() : to capture part of the pattern
+ : to indicate the previous item should repeat at
least once
{} : to indicate a specific number of repetition
High-levelURL Configuration
url(r'^(?P<variable>/[0-9]{n})/$', [Link])
?P< v > : to take v and sent to view as a variable
^ : beginning of the url
$ : end of the url
() : to capture part of the pattern
+ : to indicate the previous item should repeat at
least once
{} : to indicate a specific number of repetition
URL Dispatcher / Patterns
Root URLshould be configured [Link]
o ROOT_URLCONF ='[Link]'
Syntax
patterns(prefix,
(regular expression, Python callback function [, optional dictionary [, optional name]])
)
Example:
urlpatterns = patterns(' ',
(r'^articles-year/$', '[Link].articles_year'),
)
Note:
o No need to add a leading slash(/articles-year)
o The 'r' in front of each regular expression string is optional but recommended. It tells
Python that a
string is "raw" -- that nothing in the string should be escaped.
In python, the ‘\’ backslash character in control chars must be escaped for regular
expression use. Basically we have to add one more slash i.e \\t, \\b. To work around
backslash plague, you can raw string, by prefixing the string with the letter r.
56
Can include other URLconf modules
urlpatterns = patterns(' ',
url(r'^support/', include('[Link]')),
)
Using Prefix
urlpatterns = patterns(' ',
(r'^articles/(\d{4})/$', '[Link].articles_year'),
(r'^articles/(\d{4})/(\d{2})/$', '[Link].articles_month'),
)
Here [Link] is common, so can be rewritten as follows
urlpatterns = patterns('[Link]',
(r'^articles/(\d{4})/$', 'articles_year'),
(r'^articles/(\d{4})/(\d{2})/$', 'articles_month'),
)
Passing extra arguments and Dictionary mapping
patterns(' ',
(r'^articles/(?P<year>\d{4})/$', 'articles_year'), {'foo': 'bar'}),
)
We can get the values in [Link] as year='2005', foo='bar'
57
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
Thank you