Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Django Workshop at PyCon PH 2014

Sponsored · SiteGround - Reliable hosting with speed, security, and support you can count on. →
Jon Danao
February 16, 2014

Django Workshop at PyCon PH 2014

Jon Danao

February 16, 2014

Transcript

81 slides
  1. Who is Jon Danao? • Mid-30‘s jack-of-all-trades developer • Head

    of Technology, Innovations @ ABS-CBN’s Digital Media Division • Award Winner (CMMA, 2001) • Award Winner (Yahoo! Hack Day, 2009)
  2. Who is Jon Danao? • Speaks several languages: English, Filipino,

    Cebuano, Chavacano, HTML, ActionScript, Java, PHP, SQL, Lua, Javascript, Objective-C and Python • Find me • twitter.com/jondanao • facebook.com/jondanao • github.com/jondanao • [email protected]
  3. Who are you? • Students? • Teachers? • Managers? •

    Developers? • PHP / Ruby / Node.js / Java? • Python? Django? • Non-developers?
  4. What is Django? • Python web framework • Similar to

    Ruby on Rails, Code Igniter, Play Framework, Meteor • Encourages rapid development • Clean and pragmatic design • Uses shared-nothing architecture • Uses MVC pattern
  5. Philosophies Loose Coupling Flexibility KISS Clarity RAD DRY Consistency “For

    perfectionists with deadlines” Agility Reusability Predictability
  6. Who uses Django? • All Mozilla sites migrated from CakePHP

    to Django • Firefox add-ons site: • 250k add-ons • 150M views/month • 500M API hits/day Source: http://www.slideshare.net/andymckay/anatomy-of-a-large-django-site-7590098
  7. Who uses Django? Source: http://blog.disqus.com/post/62187806135/scaling-django-to-8-billion-page-views • 700k websites • 30M

    profiles • 170M comments • 500M unique visitors • 45k requests/sec • 8B page views/day
  8. Who uses Django? Source: http://expandedramblings.com/index.php/important-instagram-stats/ • 150M monthly active users

    • 55M photo uploads/day • 13k likes/second • 1k comments/second • 16B photos shared • 35M selfies
  9. Dev Machine 1. Python 2.6, 2.7, 3.2, 3.3 http://www.python.org/getit $

    python --version 2. Pip $ [sudo] easy_install pip $ pip --version 3. VirtualEnv $ [sudo] pip install virtualenv $ virtualenv --version 4. Git http://git-scm.com/downloads $ git --version 5. SQLite Browser (optional)
  10. 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
  11. Topics 1. Setup How to start a project 2. Models

    How to define your data 3. URLs and Views How to access your data 4. Templates How to render your data
  12. 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
  13. VirtualEnv • Creates isolated Python environments • Dependencies between projects

    don’t mix • Like having multiple XAMPP installations
  14. Git • Distribute Version Control System • Developed by Linus

    Torvalds • Fast, simple, non-linear, work offline • Practice: http://www.atlassian.com/git/ • $ git init • $ git status • $ git add • $ git commit
  15. Project • In Django, a “project” is a collection of

    apps and site configurations • Can be created via command line • Auto-generates some code - init, settings, urls, wsgi
  16. Database • No point of using Django if site is

    static • Support for PostgreSQL, SQLite3, MySQL, Oracle • GeoDjango works really well with PostgreSQL
  17. Summary • Pip - package manager • VirtualEnv - isolated

    environments • Git - version control • Project - collection of apps • Database - supports SQLite, MySQL, PostgreSQL and Oracle
  18. Topics 1. Setup How to start a project 2. Models

    How to define your data 3. URLs and Views How to access your data 4. Templates How to render your data ✓
  19. App • A piece of functionality like articles, comments, ratings,

    products in the form of a Python package • App : Django : : Package : Python • A project can have multiple apps. An app can be in multiple projects. • Can be created via command line • To convert a folder into package, add __init__.py
  20. App 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. • Write reusable, pluggable, distributable apps
  21. Model • Class that represents objects in db • Defines

    structure of data • Class : Table : : Property : Field • Model talks to the ORM that talks to the db • ORM eliminates writing of SQL
  22. Model Example • Article as our model • It has

    properties like: - title - category - author - body - published date • This will be translated into a db table via the command “syncdb”
  23. App Best Practices • Your app’s name should be the

    plural version of its main model • Keep apps small, maximum of 5 models
  24. Admin Site • Pseudo CMS for CRUD operations • Automatic

    creation of interfaces for models • Register the models you want to be editable in admin.py
  25. Summary • App - piece of functionality • Model -

    a class representation of db table • Admin Site - pseudo CMS
  26. Topics 1. Setup How to start a project 2. Models

    How to define your data 3. URLs and Views How to access your data 4. Templates How to render your data ✓ ✓
  27. URLConf • Routes a URL pattern to a view •

    Uses regex for maximum flexibility • Table of contents for site urlpatterns = patterns('', url(r'^articles/(\d{4})/$', views.year_archive), url(r'^articles/(\d{4})/(\d{2})/$', views.month_archive), url(r'^articles/(\d{4})/(\d{2})/(\d+)/$', views.article_detail), )
  28. Views • Again, views do not render HTML! • Handles

    requests passed on via the URLConf • Gets data from the model and passes them to the template for rendering • Determines WHAT data the user should see, not HOW data should be rendered
  29. Querying the Model • Retrieve all objects (aka SELECT *)

    all_articles = Article.objects.all() • Retrieve 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!’)
  30. 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)
  31. Dunder Methods • __init__, __file__, __unicode__ • Pythonic, common and

    idiomatic methods • Used as field lookups in filter(), exclude(), get() • Extremely powerful and intuitive
  32. Field Lookups • Basic model lookups syntax: field__lookuptype=value 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=‘2014-02-23’) • Model relationship lookups syntax: field__foreignfield__lookuptype=value Article.objects.filter(category__slug__contains=‘pony’)
  33. Summary • URLConf - routes URL patterns to views •

    View - handles requests from URLConf • Dunder Methods - used for filtering queries
  34. Topics 1. Setup How to start a project 2. Models

    How to define your data 3. URLs and Views How to access your data 4. Templates How to render your data ✓ ✓ ✓
  35. Templates • Renders HTML and other formats like XML, CSV

    and JSON • Uses custom pseudo programming syntax • Call function or do logic: {% ... %} • Print variable: {{ variable }} • Filters: {{ variable|filter }}
  36. Django Flow Client URL View Model Tpl 1 Client requests

    a page via a URL 1 2 Django checks URLConf for URL patterns and executes view function to handle request 2 3 View requests data from model 3 4 Model queries the database and returns data to the view 4 5 View passes the data to template 5 6 Template renders data and returns HTML to the view 6 7 View returns HTML to the browser 7
  37. Template Tags • {% load %} - loads custom template

    tag • {% extends %} - inherits from parent or base template • {% block %} - defines a placeholder that can be overridden by child templates • 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
  38. Includes: define sections that are common Header Footer Extends: define

    sections that are unique Content Header Footer Content
  39. Template Philosophies • Discourage redundancy. • Be decoupled from HTML.

    • XML should not be used as a template language.
  40. Summary • Templates - render HTML and other formats •

    load - loads template tags from other libraries • extends - inherits from base template • block - defines placeholder in templates
  41. Topics 1. Setup How to start a project 2. Models

    How to define your data 3. URLs and Views How to access your data 4. Templates How to render your data ✓ ✓ ✓ ✓
  42. Recap • What is Django? • What is MTV? •

    What is Loose Coupling? • What is KISS? • What is RAD? • What is DRY?
  43. Recap • What is the advantage of using VirtualEnv? •

    After installing a new package, what is the best thing to do next? • What is an app? • How do you convert a folder into a Python package? • After activating new apps in settings, what is the best thing to do next?
  44. Recap • What is the Admin site? • What do

    you do if you want your models to appear in the Admin site? • What is the use of dunder methods in queries? • How does template inheritance work?

More Decks by Jon Danao

Other Decks in Programming