KEMBAR78
Introduction to Python and Django | PDF
Introduction to
(Python and)
the Django Framework
Prashant Punjabi
Solution Street
9/26/2014
Python
!
• Created by Guido van Rossum
in the late 1980s
!
• Named after ‘Monty Python’s
Flying Circus’
!
• Python 2.0 was released on 16
October 2000
!
• Python 3.0 a major,
backwards-incompatible
release, was released on 3
December 2008
!
• Guido is the BDFL
Python
• General Purpose, high-level programming language
• Supports multiple programming paradigms
• object-oriented, functional, structured, imperative(?)
• Dynamically typed
• Many implementations
• CPython (reference)
• Jython
• IronPython .. and many more
The Zen of Python
• “Core philosophy”
• Beautiful is better than ugly
• Explicit is better than implicit
• Simple is better than complex
• Complex is better than complicated
• Readability counts
• >>> import this
Data Types
• Numbers
• int, float, long (and complex)
• Strings
• str, unicode
• Sequence Types
• str, unicode, lists, tuples (and bytearrays, buffers, xrange)
• strings, tuples are ‘immutable’
• lists are mutable
• Mapping Types
• dict
Functions
• Defined using the keyword.. def
• Followed by the function name and the parenthesized list of formal parameters.
• The statements that form the body of the function start at the next line,
• and must be indented (just like this line)
• The first statement of the function body can optionally be a string literal
• this string literal is the function’s documentation string, or docstring.
• Arguments are passed using call by value (where the value is always an object
reference, not the value of the object)
• Functions always return a value
• If not return is explicitly defined, the function returns None
Control Flow
• if
• if…elif…else
• for
• range
• break, continue, else
• while
Truthi-nessTM
• An empty list ([])
• An empty tuple (())
• An empty dictionary ({})
• An empty string ('')
• Zero (0)
• The special object None
• The object False (obviously)
• Custom objects that define their own Boolean context behavior (this is
advanced Python usage)
Modules and Packages
• A module is a file containing Python definitions and statements.
• The file name is the module name with the suffix .py appended.
• Within a module, the module’s name (as a string) is available as the value of the
global variable __name__
• Modules can be executed as a script
• python module.py [args]
• __name__ is set to __main__
• Packages are a way of structuring Python’s module namespace by using “dotted
module names”
• The __init__.py file is required to make Python treat a directory as containing
packages
Classes
• Python’s class mechanism adds classes with a minimum of new syntax and
semantics
• Python classes provide all the standard features of Object Oriented
Programming
• multiple base classes
• a derived class can override any methods of its base class or classes
• a method can call the method of a base class with the same name
• Objects can contain arbitrary amounts and kinds of data
• Class and Instance Variables
• Static Methods
Standard Library
• Operating System Interface
• File handling
• String pattern matching
• Regular expressions
• Mathematics
• Internet Access
• Dates and Times
• Collections
• Unit Tests
Batteries Included
Django
Django
• Django grew organically from real-world applications
• Born in the fall of 2003, in Lawrence, Kansas, USA
• Adrian Holovaty and Simon Willison - web
programmers at the Lawrence Journal-World
newspaper
• Released it in July 2005 and named it Django, after the
jazz guitarist Django Reinhard
• “For Perfectionists with Deadlines”
Getting Started
• Installation
• pip install Django
• ¯_(ツ)_/¯
• Creating a Django project
• django-admin.py startproject django_example
• Adding an ‘app’ to your Django project
• python manage.py startapp music
MVC - Separation of Concerns
• models.py
• description of the database table, represented by a Python class, called a model
• create, retrieve, update and delete records in your database using simple Python code
• views.py
• contains the business logic for the page
• contains functions, each of which are called a view functions or simply views
• urls.py
• file specifies which view is called for a given URL pattern
• Templates
• describes the design of the page
• uses a template language with basic logic statements
models.py
• Each model is represented by a class that subclasses django.db.models.Model
• Class variables represents a database fields in the model
• A field is represented by an instance of a Field class eg CharField,
DateTimeField
• The name of each Field instance is used by the database as the column name
• Some Field classes have required arguments, others have optional arguments
• CharField, for example, requires that you give it a max_length
• default is an optional argument for many Field classes
• ForeignKey field is used to define relationships
• Django supports many-to-one, many-to-many and one-to-one
Queries
• Each model has at least one Manager, and it’s called objects by default.
• Managers are accessible only via model classes
• Enforce a separation between “table-level” operations and “record-
level” operations.
• A QuerySet represents a collection of objects from your database
• It can have zero, one or many filters
• A QuerySet equates to a SELECT statement, and a filter is a limiting
clause such as WHERE or LIMIT.
• Example
Migrations
• New in Django 1.7
• Previously accomplished by an external package called south
• Keeps the database in sync with the model objects
• Commands
• migrate
• makemigrations
• sqlmigrate
• squashmigrations
• Data Migrations
• python manage.py makemigrations --empty music
urls.py
• Django lets you design URLs however you want, with no
framework limitations.
• “Cool URIs don’t change”
• URL configuration module (URLconf)
• simple mapping between URL patterns (regular expressions)
to Python functions (views)
• capture parts of URL as parameters to view function (named
groups)
• can be constructed dynamically
views.py
• A Python function that takes a Web request and returns a Web response
• HTML contents of a Web page,
• a redirect, or a 404 error,
• an XML document,
• an image
• . . . or anything
• The convention is to put views in a file called views.py
• but it can be pretty much anywhere on your python path
• ‘Django Shortcuts’
• redirect, reverse, render_to_response,
Templates
• Designed to strike a balance between power and ease
• A template is simply a text file. It can generate any text-based format (HTML, XML,
CSV, etc.).
• Variables - {{ variable }}
• Replaced with values when the template is evaluated
• Use a dot (.) to access attributes of a variable
• Dictionary lookup, attribute or method lookup or numeric index lookup
• {{ person.name }} or {{ person.get_full_name }} or {{ books.
1 }}
• Filters can be used to modify variables for display
• {{ name|lower }}
Templates
• Tags control the logic of the template
• {% tag %}
• Commonly used tags
• for
• if, elif and else
• block and extends - Template inheritance
Template Inheritance
• Most powerful part of Django’s template engine
• Build a base “skeleton” template that contains all the
common elements of your site and defines blocks that
child templates can override.
• {% extends %} must be the first template tag in that
template.
• More {% block %} tags in your base templates are
better
• Child templates don’t have to define all parent blocks
Forms
• Django handles three distinct parts of the work involved in forms
• preparing and restructuring data ready for rendering
• creating HTML forms for the data
• receiving and processing submitted forms and data from the client
• The Django Form class
• Form class’ fields map to HTML form <input> elements
• Fields manage form data and perform validation when a form is submitted
• Fields are represented to a user in the browser as HTML “widgets”
• Each field type has an appropriate default Widget class, but these can be
overridden as required.
Batteries (still) included
• Authentication and Authorization
• Emails
• File Uploads
• Session
• Caching
• Transactions
• .. and so on
See also..
• The Django ‘admin’ app
• django-admin.py and manage.py
• ModelForms
• Generic Views or Class based views
• Static File deployment
• Settings
• Middleware
• Similar to Servlet Filters in Java
References
• Python - Wikipedia page (http://en.wikipedia.org/wiki/
Python_(programming_language))
• The Python Tutorial (https://docs.python.org/2/tutorial/
index.html)
• The Django Project (https://www.djangoproject.com/)
• The Django Book (http://www.djangobook.com/en/2.0/
index.html)
• The Django Documentation (https://
docs.djangoproject.com/en/1.7/)
Questions?
Thank you!

Introduction to Python and Django

  • 1.
    Introduction to (Python and) theDjango Framework Prashant Punjabi Solution Street 9/26/2014
  • 2.
    Python ! • Created byGuido van Rossum in the late 1980s ! • Named after ‘Monty Python’s Flying Circus’ ! • Python 2.0 was released on 16 October 2000 ! • Python 3.0 a major, backwards-incompatible release, was released on 3 December 2008 ! • Guido is the BDFL
  • 3.
    Python • General Purpose,high-level programming language • Supports multiple programming paradigms • object-oriented, functional, structured, imperative(?) • Dynamically typed • Many implementations • CPython (reference) • Jython • IronPython .. and many more
  • 4.
    The Zen ofPython • “Core philosophy” • Beautiful is better than ugly • Explicit is better than implicit • Simple is better than complex • Complex is better than complicated • Readability counts • >>> import this
  • 5.
    Data Types • Numbers •int, float, long (and complex) • Strings • str, unicode • Sequence Types • str, unicode, lists, tuples (and bytearrays, buffers, xrange) • strings, tuples are ‘immutable’ • lists are mutable • Mapping Types • dict
  • 6.
    Functions • Defined usingthe keyword.. def • Followed by the function name and the parenthesized list of formal parameters. • The statements that form the body of the function start at the next line, • and must be indented (just like this line) • The first statement of the function body can optionally be a string literal • this string literal is the function’s documentation string, or docstring. • Arguments are passed using call by value (where the value is always an object reference, not the value of the object) • Functions always return a value • If not return is explicitly defined, the function returns None
  • 7.
    Control Flow • if •if…elif…else • for • range • break, continue, else • while
  • 8.
    Truthi-nessTM • An emptylist ([]) • An empty tuple (()) • An empty dictionary ({}) • An empty string ('') • Zero (0) • The special object None • The object False (obviously) • Custom objects that define their own Boolean context behavior (this is advanced Python usage)
  • 9.
    Modules and Packages •A module is a file containing Python definitions and statements. • The file name is the module name with the suffix .py appended. • Within a module, the module’s name (as a string) is available as the value of the global variable __name__ • Modules can be executed as a script • python module.py [args] • __name__ is set to __main__ • Packages are a way of structuring Python’s module namespace by using “dotted module names” • The __init__.py file is required to make Python treat a directory as containing packages
  • 10.
    Classes • Python’s classmechanism adds classes with a minimum of new syntax and semantics • Python classes provide all the standard features of Object Oriented Programming • multiple base classes • a derived class can override any methods of its base class or classes • a method can call the method of a base class with the same name • Objects can contain arbitrary amounts and kinds of data • Class and Instance Variables • Static Methods
  • 11.
    Standard Library • OperatingSystem Interface • File handling • String pattern matching • Regular expressions • Mathematics • Internet Access • Dates and Times • Collections • Unit Tests
  • 12.
  • 13.
  • 14.
    Django • Django greworganically from real-world applications • Born in the fall of 2003, in Lawrence, Kansas, USA • Adrian Holovaty and Simon Willison - web programmers at the Lawrence Journal-World newspaper • Released it in July 2005 and named it Django, after the jazz guitarist Django Reinhard • “For Perfectionists with Deadlines”
  • 15.
    Getting Started • Installation •pip install Django • ¯_(ツ)_/¯ • Creating a Django project • django-admin.py startproject django_example • Adding an ‘app’ to your Django project • python manage.py startapp music
  • 16.
    MVC - Separationof Concerns • models.py • description of the database table, represented by a Python class, called a model • create, retrieve, update and delete records in your database using simple Python code • views.py • contains the business logic for the page • contains functions, each of which are called a view functions or simply views • urls.py • file specifies which view is called for a given URL pattern • Templates • describes the design of the page • uses a template language with basic logic statements
  • 17.
    models.py • Each modelis represented by a class that subclasses django.db.models.Model • Class variables represents a database fields in the model • A field is represented by an instance of a Field class eg CharField, DateTimeField • The name of each Field instance is used by the database as the column name • Some Field classes have required arguments, others have optional arguments • CharField, for example, requires that you give it a max_length • default is an optional argument for many Field classes • ForeignKey field is used to define relationships • Django supports many-to-one, many-to-many and one-to-one
  • 18.
    Queries • Each modelhas at least one Manager, and it’s called objects by default. • Managers are accessible only via model classes • Enforce a separation between “table-level” operations and “record- level” operations. • A QuerySet represents a collection of objects from your database • It can have zero, one or many filters • A QuerySet equates to a SELECT statement, and a filter is a limiting clause such as WHERE or LIMIT. • Example
  • 19.
    Migrations • New inDjango 1.7 • Previously accomplished by an external package called south • Keeps the database in sync with the model objects • Commands • migrate • makemigrations • sqlmigrate • squashmigrations • Data Migrations • python manage.py makemigrations --empty music
  • 20.
    urls.py • Django letsyou design URLs however you want, with no framework limitations. • “Cool URIs don’t change” • URL configuration module (URLconf) • simple mapping between URL patterns (regular expressions) to Python functions (views) • capture parts of URL as parameters to view function (named groups) • can be constructed dynamically
  • 21.
    views.py • A Pythonfunction that takes a Web request and returns a Web response • HTML contents of a Web page, • a redirect, or a 404 error, • an XML document, • an image • . . . or anything • The convention is to put views in a file called views.py • but it can be pretty much anywhere on your python path • ‘Django Shortcuts’ • redirect, reverse, render_to_response,
  • 22.
    Templates • Designed tostrike a balance between power and ease • A template is simply a text file. It can generate any text-based format (HTML, XML, CSV, etc.). • Variables - {{ variable }} • Replaced with values when the template is evaluated • Use a dot (.) to access attributes of a variable • Dictionary lookup, attribute or method lookup or numeric index lookup • {{ person.name }} or {{ person.get_full_name }} or {{ books. 1 }} • Filters can be used to modify variables for display • {{ name|lower }}
  • 23.
    Templates • Tags controlthe logic of the template • {% tag %} • Commonly used tags • for • if, elif and else • block and extends - Template inheritance
  • 24.
    Template Inheritance • Mostpowerful part of Django’s template engine • Build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. • {% extends %} must be the first template tag in that template. • More {% block %} tags in your base templates are better • Child templates don’t have to define all parent blocks
  • 25.
    Forms • Django handlesthree distinct parts of the work involved in forms • preparing and restructuring data ready for rendering • creating HTML forms for the data • receiving and processing submitted forms and data from the client • The Django Form class • Form class’ fields map to HTML form <input> elements • Fields manage form data and perform validation when a form is submitted • Fields are represented to a user in the browser as HTML “widgets” • Each field type has an appropriate default Widget class, but these can be overridden as required.
  • 26.
    Batteries (still) included •Authentication and Authorization • Emails • File Uploads • Session • Caching • Transactions • .. and so on
  • 27.
    See also.. • TheDjango ‘admin’ app • django-admin.py and manage.py • ModelForms • Generic Views or Class based views • Static File deployment • Settings • Middleware • Similar to Servlet Filters in Java
  • 28.
    References • Python -Wikipedia page (http://en.wikipedia.org/wiki/ Python_(programming_language)) • The Python Tutorial (https://docs.python.org/2/tutorial/ index.html) • The Django Project (https://www.djangoproject.com/) • The Django Book (http://www.djangobook.com/en/2.0/ index.html) • The Django Documentation (https:// docs.djangoproject.com/en/1.7/)
  • 29.
  • 30.