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

Django Workshop at PythonPH Meetup (June 2013)

Django Workshop at PythonPH Meetup (June 2013)

Download companion files here: http://github.com/jondanao/Surf-Magazine-Template

Many thanks to the Django community especially @pydanny and @audreyr who wrote Two Scoops of Django book. https://django.2scoops.org

https://twitter.com/jondanao
https://github.com/jondanao
http://danao.org/

Jon Danao

June 22, 2013
Tweet

More Decks by Jon Danao

Other Decks in Programming

Transcript

  1. 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)
  2. 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]
  3. Who are you? • Students? • Teachers? • Professional Developers?

    • Managers? • C/C++? • PHP / ASP.NET / Ruby / Java? • PYTHON???
  4. 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
  5. Philosophies • Loose coupling = Flexibility • KISS = Clarity

    • RAD = Agility • DRY = Reusability • Consistency = Predictability • “For perfectionists with deadlines”
  6. Who uses Django? • All Mozilla sites are now built

    with Django • Firefox add-ons site: - 150M views/month - 500M API hits/day
  7. Who uses Django? • 25k requests/sec • 700k websites •

    20M page views/day • 30M profiles • 170M comments • 500M unique visitors
  8. Who uses Django? • 3M users • 18M visitors/month •

    80M objects in S3 • 500M pins • 2.5B page views/month • 1.6B follower rows
  9. Who uses Django? • 90M monthly active users • 40M

    photo uploads/day • 8500 likes/second • 1000 comments/second • 1B push notifications • $1B
  10. 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)
  11. 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
  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. Git • DVCS or SCM • Developed by Linus Torvalds

    • Fast, simple, non-linear, work offline • Practice: http://www.atlassian.com/git/ $ git init $ git status $ git add $ git commit
  14. VirtualEnv • Creates isolated Python environments • Dependencies between projects

    don’t mix • Like having multiple XAMPP installations
  15. 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)
  16. Project • Project is a collection of apps and site

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

    static • Support for PostgreSQL, SQLite3, MySQL, Oracle • GIS works really well with PostgreSQL
  18. 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
  19. Settings • Handling file paths is difficult • Root of

    your machine != root of server • Hardcoding paths is bad • Configure all necessary options
  20. Admin Site • Automatic creation of admin interfaces for models

    • Pseudo CMS for CRUD operations • Models can opt to hook into the admin site
  21. MVC

  22. 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
  23. Example • Article as our model • It has properties

    like title, category, author, content, tags, published date • This will be translated into a db table
  24. 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
  25. 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
  26. 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.
  27. Best Practices Your app’s name should be the plural version

    of its main model Keep apps small, maximum of 5 models
  28. 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
  29. 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
  30. 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'), )
  31. 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!’)
  32. 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)
  33. Dunder Methods • __init__, __file__, __unicode__ • Pythonic, common and

    idiomatic methods • Used as field lookups in filter() , exclude() , get() • Extremely powerful and intuitive
  34. 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’)
  35. 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 }}
  36. 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
  37. Includes: define sections that are common Header Footer Extends: define

    sections that are unique Content Header Footer Content
  38. Recap • What is Django? • What is MTV? •

    What is Loose Coupling? • What is KISS? • What is RAD? • What is DRY?
  39. 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?
  40. 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?
  41. 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!