SlideShare a Scribd company logo
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!

More Related Content

PPTX
Page Fragments как развитие идеи Page Object паттерна
PDF
ERRest: the Basics
PPTX
PHP Starter Application
PPT
Power of introspection
PPT
Chelberg ptcuser 2010
PPT
Helberg acl-final
Page Fragments как развитие идеи Page Object паттерна
ERRest: the Basics
PHP Starter Application
Power of introspection
Chelberg ptcuser 2010
Helberg acl-final

What's hot (12)

KEY
GeekAustin PHP Class - Session 6
PDF
PPTX
WordPress Themes 101 - HighEdWeb New England 2013
PPTX
Eurydike: Schemaless Object Relational SQL Mapper
PPT
Json - ideal for data interchange
PPT
PHP - Introduction to PHP Date and Time Functions
PPTX
FFW Gabrovo PMG - PHP OOP Part 3
PPT
Java XML Parsing
PPTX
JS Essence
PPTX
WordPress Themes 101 - dotEduGuru Summit 2013
PPT
Apache Velocity
GeekAustin PHP Class - Session 6
WordPress Themes 101 - HighEdWeb New England 2013
Eurydike: Schemaless Object Relational SQL Mapper
Json - ideal for data interchange
PHP - Introduction to PHP Date and Time Functions
FFW Gabrovo PMG - PHP OOP Part 3
Java XML Parsing
JS Essence
WordPress Themes 101 - dotEduGuru Summit 2013
Apache Velocity
Ad

Viewers also liked (12)

DOCX
Recent resume
PDF
Saurav Srivastava CV..
DOC
Resume
PDF
django
PDF
CV(Arpit_Singh)
PDF
socialpref
DOCX
Wipro resume
DOC
Archana Jaiswal Resume
PDF
Resume-Python-Developer-ZachLiu
PDF
Python/Django Training
DOC
Resume
DOC
Dana resume1
Recent resume
Saurav Srivastava CV..
Resume
django
CV(Arpit_Singh)
socialpref
Wipro resume
Archana Jaiswal Resume
Resume-Python-Developer-ZachLiu
Python/Django Training
Resume
Dana resume1
Ad

Similar to Introduction to Python and Django (20)

PDF
GDG Addis - An Introduction to Django and App Engine
PPTX
Python Tutorial Part 2
PPTX
AI - PYTHON PROGRAMMING BASICS II.pptx
PPTX
Best Python Online Training with Live Project by Expert
PDF
Python-Magnitia-ToC.pdf
PPTX
Introduction_to_Python.pptx
PDF
PyCaret_PedramJahangiryTUTORIALPYTHON.pdf
PPTX
Software Programming with Python II.pptx
PDF
Advanced guide to develop ajax applications using dojo
KEY
QueryPath, Mash-ups, and Web Services
PDF
Python Programming - VI. Classes and Objects
PDF
Web development django.pdf
PDF
Python indroduction
 
PDF
Beyond Domino Designer
PPTX
Tango with django
PPTX
Introduction to java
PDF
Integrating the Solr search engine
KEY
Modules Building Presentation
PDF
Your first d8 module
PDF
A peek into Python's Metaclass and Bytecode from a Smalltalk User
GDG Addis - An Introduction to Django and App Engine
Python Tutorial Part 2
AI - PYTHON PROGRAMMING BASICS II.pptx
Best Python Online Training with Live Project by Expert
Python-Magnitia-ToC.pdf
Introduction_to_Python.pptx
PyCaret_PedramJahangiryTUTORIALPYTHON.pdf
Software Programming with Python II.pptx
Advanced guide to develop ajax applications using dojo
QueryPath, Mash-ups, and Web Services
Python Programming - VI. Classes and Objects
Web development django.pdf
Python indroduction
 
Beyond Domino Designer
Tango with django
Introduction to java
Integrating the Solr search engine
Modules Building Presentation
Your first d8 module
A peek into Python's Metaclass and Bytecode from a Smalltalk User

Recently uploaded (20)

PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
cuic standard and advanced reporting.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Encapsulation theory and applications.pdf
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Cloud computing and distributed systems.
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Approach and Philosophy of On baking technology
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Spectral efficient network and resource selection model in 5G networks
cuic standard and advanced reporting.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Encapsulation theory and applications.pdf
Machine learning based COVID-19 study performance prediction
Understanding_Digital_Forensics_Presentation.pptx
Encapsulation_ Review paper, used for researhc scholars
Cloud computing and distributed systems.
Building Integrated photovoltaic BIPV_UPV.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Approach and Philosophy of On baking technology
“AI and Expert System Decision Support & Business Intelligence Systems”
Network Security Unit 5.pdf for BCA BBA.
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Dropbox Q2 2025 Financial Results & Investor Presentation

Introduction to Python and Django

  • 1. Introduction to (Python and) the Django Framework Prashant Punjabi Solution Street 9/26/2014
  • 2. 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
  • 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 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
  • 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 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
  • 7. Control Flow • if • if…elif…else • for • range • break, continue, else • while
  • 8. 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)
  • 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 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
  • 11. Standard Library • Operating System Interface • File handling • String pattern matching • Regular expressions • Mathematics • Internet Access • Dates and Times • Collections • Unit Tests
  • 14. 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”
  • 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 - 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
  • 17. 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
  • 18. 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
  • 19. 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
  • 20. 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
  • 21. 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,
  • 22. 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 }}
  • 23. Templates • Tags control the logic of the template • {% tag %} • Commonly used tags • for • if, elif and else • block and extends - Template inheritance
  • 24. 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
  • 25. 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.
  • 26. Batteries (still) included • Authentication and Authorization • Emails • File Uploads • Session • Caching • Transactions • .. and so on
  • 27. 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
  • 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/)