100% found this document useful (1 vote)
175 views78 pages

Django Workshop 2013.06.22

This document provides information about Jon Danao, an expert developer in the Philippines. It introduces Danao as a 30-something head of development who has experience in various languages like HTML, PHP, Python and more. It provides contact information for Danao including his email and blogs. The document then outlines an introduction to Django, why the author loves Django, its philosophies and major companies that use Django for their projects and applications.

Uploaded by

Eric Chua
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
100% found this document useful (1 vote)
175 views78 pages

Django Workshop 2013.06.22

This document provides information about Jon Danao, an expert developer in the Philippines. It introduces Danao as a 30-something head of development who has experience in various languages like HTML, PHP, Python and more. It provides contact information for Danao including his email and blogs. The document then outlines an introduction to Django, why the author loves Django, its philosophies and major companies that use Django for their projects and applications.

Uploaded by

Eric Chua
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/ 78

Jon Danao

Who is Jon Danao?


• 30-something jack-of-all-trades developer
• Head of Development for
Digital Brand Management @ ABS-CBN
• Ex Rock Star
• Award Winner (CMMA - Best Website 2001)
• Award Winner (Yahoo! Open Hack Day -
Best Social Hack 2009)
Who is Jon Danao?
• Speak several languages: English, Filipino,
Cebuano, Chavacano, HTML, ActionScript,
Java, PHP, SQL, Lua, Javascript, Objective-C
and Python
• Run a blog at danao.org
• Run another blog at silkroutes.com
• Email me at [email protected]
Who are you?
• Students?
• Teachers?
• Professional Developers?
• Managers?
• C/C++?
• PHP / ASP.NET / Ruby / Java?
• PYTHON???
Outline
1. Introduction
2. The Project
3. Dev Machine
4. Flow
5. Dive into Django
Introduction
What is Django?
• Shiny Python web framework
• Encourages RAD and clean design
• Enforces MVC
• Focuses on automation and DRY
• Like Ruby on Rails, Code Igniter (PHP),
ASP.NET MVC
Why do I ♥ Django?
Philosophies
Philosophies
• Loose coupling = Flexibility
• KISS = Clarity
• RAD = Agility
• DRY = Reusability
• Consistency = Predictability
• “For perfectionists with deadlines”
Who uses Django?
Who uses Django?
• All Mozilla sites are
now built with Django
• Firefox add-ons site:
- 150M views/month
- 500M API hits/day
Who uses Django?
• 25k requests/sec
• 700k websites
• 20M page views/day
• 30M profiles
• 170M comments
• 500M unique visitors
Who uses Django?
• 3M users
• 18M visitors/month
• 80M objects in S3
• 500M pins
• 2.5B page views/month
• 1.6B follower rows
Who uses Django?
• 90M monthly active users
• 40M photo uploads/day
• 8500 likes/second
• 1000 comments/second
• 1B push notifications
• $1B
The Surf Magazine
Project
UI Design
URL Design
website.com/

website.com/category/
website.com/category/id/article-slug/

website.com/api/category.json
website.com/api/category/id.json
URL Examples
website.com/

website.com/sports/
website.com/sports/123/ufc-champion/

website.com/api/sports.json
website.com/api/sports/123.json
URL Design
Dev Machine
1. Python
http://www.python.org/getit

2. Pip
sudo easy_install pip

3. VirtualEnv
sudo pip install virtualenv

4. Git
http://git-scm.com/downloads

5. SQLite Manager (optional)


Flow
Concept

Hands-on Walkthrough
Code of Conduct

• Be welcoming, friendly and patient


• Be considerate
• Be respectful
• Be careful in the words that you choose
• Be constructive than destructive
speakup.io/coc.html & djangoproject.com/conduct
Dive into Django
Pip
• Python CLI package management system
• Easy to install a package
$ pip install package-name

• Easy to uninstall a package


$ pip uninstall package-name

• Easy to list all installed packages


$ pip freeze > requirements.txt

• Easy to install package list


$ pip install -r requirements.txt
Git
• DVCS or SCM
• Developed by Linus Torvalds
• Fast, simple, non-linear, work offline
• Practice:
$ git init
http://www.atlassian.com/git/
$ git status
$ git add
$ git commit
VirtualEnv

• Creates isolated Python environments


• Dependencies between projects don’t mix
• Like having multiple XAMPP installations
VirtualEnv
python.ph pycon.ph

python 2.7 python 3.3

django 1.4 django 1.5

mysql-python 1.2.3 pymysql 0.5

(python-env) (pycon-env)
Walkthrough 1
Project

• Project is a collection of apps and site


configurations
• Can be created via command line
• Auto-generates some code - init, settings,
urls, wsgi
Walkthrough 2
Database

• No point of using Django if site is static


• Support for PostgreSQL, SQLite3, MySQL,
Oracle
• GIS works really well with PostgreSQL
Walkthrough 3
Project Structure
website.com
!"" apps
!"" db
!"" media
!"" project
# !"" __init__.py
# !"" settings.py
# !"" urls.py
# $"" wsgi.py
!"" static
!"" templates
!"" venv
!"" .gitignore
!"" manage.py
!"" README.md
$"" requirements.txt
Settings

• Handling file paths is difficult


• Root of your machine != root of server
• Hardcoding paths is bad
• Configure all necessary options
Walkthrough 4
Best Practice
Always pip freeze after installing new packages
Admin Site

• Automatic creation of admin interfaces for


models
• Pseudo CMS for CRUD operations
• Models can opt to hook into the admin site
Philosophy
Writing admin interfaces is boring and repetitive.
Walkthrough 5
Best Practice
Always syncdb after activating new apps
MVC
Model

• Class that represents objects in db


• Defines structure of data
• Class = Table / Property = Column
• Talks to the ORM that talks to the db
• ORM eliminates writing of SQL
Example

• Article as our model


• It has properties like title, category, author,
content, tags, published date
• This will be translated into a db table
Philosophy
Explicit is better than implicit.
Template

• Renders HTML
• Uses custom pseudo programming syntax
• Very designer friendly
Philosophies
Discourage redundancy.
Be decoupled from HTML.
XML should not be used a template language.
View

• Handles request passed on via the


URLConf
• Gets data from the model and hands them
over to the template for rendering
• Determines WHAT data the user should
see, not HOW data should be rendered
Philosophies
Simplicity.
Loose coupling.
App
• Small library designed to represent a single aspect
of a project (module/package/app)
• A piece of functionality like articles, comments,
ratings, products, polls, events
• App = Django / Module = Python
• A project can have multiple apps. An app can be in
multiple projects.
• In Python, to convert a folder into module, just add
__init__.py
Philosophies
Write programs that do one thing and do it well.
If an app can’t be explained in a single sentence,
it should be broken up.
Should be reusable, pluggable, distributable.
Walkthrough 6
Best Practices
Your app’s name should be the
plural version of its main model
Keep apps small, maximum of 5 models
Admin.py

• Create admin.py inside app folder if


you want to your models to appear in
admin site
• Register the models you want to be
editable
Walkthrough 7
Django Flow
Django Flow
Client 1 Client requests a page via a URL

Django checks URLConf for URL


1 2 patterns and executes view
function to handle request

3 View requests data from model


URL 7
Model queries the database and
4
returns data to the view
2
5 View passes the data to template

View Template renders data and


6
returns HTML to the view
3 6
View returns HTML to the
7
browser
4 5

Model Tpl
URLConf
• Hooks a particular URL pattern to a view
function
• Uses regex for maximum flexibility
• Table of contents for site or app
urlpatterns = patterns('',
url(r'^articles/(\d{4})/$', 'news.views.year_archive'),
url(r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
url(r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
)
Philosophies
Loose coupling.
Infinite flexibility.
Definite URLs.
Walkthrough 8
Querying the Model
• Retrieve all objects (aka SELECT *)
all_articles = Article.objects.all()

• Retrieve specific objects with filters (aka


WHERE clause)
draft_articles = Article.objects.filter(status=1)
published_articles = Article.objects.exclude(status=1)

• Chaining filters (aka AND operator in where)


latest_paquiao_articles =
Article.objects.
filter(status=1).
exclude(title=‘Manny Villar Wins!’)
Querying the Model

• Limiting and offsetting results


articles = Article.objects.all()[:5]
articles = Article.objects.all()[5:10]

• Sorting objects
articles = Article.objects.all().order_by(‘title’)
articles = Article.objects.all().order_by(‘-title’)

• Retrieving single object


article = Article.objects.get(id=1)
Dunder Methods

• __init__, __file__, __unicode__

• Pythonic, common and idiomatic methods


• Used as field lookups in , ,
filter() exclude() get()

• Extremely powerful and intuitive


Field Lookups
• Basic model lookups
syntax: field__lookuptype = value

Article.objects.filter(title__exact=‘Django is my Pony’)
Article.objects.filter(title=‘Django is my Pony’)
Article.objects.filter(title__contains=‘Python’)
Article.objects.filter(title__startswith=‘Django’)
Article.objects.filter(pub_date__gte=‘2013-02-01’)

• Model relationship lookups


syntax: field__foreignfield__lookuptype = value

Article.objects.filter(category__slug__contains=‘global’)
Walkthrough 9
Template Engine
• Renders HTML, CSV, JSON, XML... any text format,
just specify content-type
• Uses basic programming constructs
• Call function or do logic:
{% ... %}
• Print variable:
{{ foo }}
• Filters:
{{ foo|bar }}
Walkthrough 10
Template Engine
• {% load %} - loads custom template tag

• {% block %} - defines a block that can be overridden by


child templates. Blocks are placeholders
• {% extends %} - inherits from a parent or base template
aka Template Inheritance
• includes vs extends:
• extends is the “inside-out” version of server-side includes
• includes: define sections that are common
• extends: define sections that are unique
Includes: define sections that are common
Header

Content

Footer

Extends: define sections that are unique


Header

Content

Footer
Walkthrough 11
Recap
• What is Django?
• What is MTV?
• What is Loose Coupling?
• What is KISS?
• What is RAD?
• What is DRY?
Recap
• What is the advantage of using VirtualEnv?
• After installing a new package, what do you do
next?
• What is an app?
• How do you create a Python module?
• After activating new apps in settings, what do
you do next?
Recap
• What is the Admin site?
• What do you do if you want your models to
appear in the Admin site?
• Write a query that gets 5 articles by a certain
author and sort them alphabetically.
• What is the use of dunder methods in queries?
• What is template inheritance?
Maraming Salamat!
Bonus: Deploy to
Heroku
• Heroku is PaaS on top of AWS (IaaS)
• Installs necessary dependencies by reading the
requirements.txt
• In Procfile we declare our manage.py
runserver command
• Easy deployment using git push!
Walkthrough 12

You might also like