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

What's hot (12)

GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6
jimbojsb
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
Jussi Pohjolainen
 
WordPress Themes 101 - HighEdWeb New England 2013
WordPress Themes 101 - HighEdWeb New England 2013WordPress Themes 101 - HighEdWeb New England 2013
WordPress Themes 101 - HighEdWeb New England 2013
Curtiss Grymala
 
Eurydike: Schemaless Object Relational SQL Mapper
Eurydike: Schemaless Object Relational SQL MapperEurydike: Schemaless Object Relational SQL Mapper
Eurydike: Schemaless Object Relational SQL Mapper
ESUG
 
Json - ideal for data interchange
Json - ideal for data interchangeJson - ideal for data interchange
Json - ideal for data interchange
Christoph Santschi
 
PHP - Introduction to PHP Date and Time Functions
PHP -  Introduction to  PHP Date and Time FunctionsPHP -  Introduction to  PHP Date and Time Functions
PHP - Introduction to PHP Date and Time Functions
Vibrant Technologies & Computers
 
Php Basics
Php BasicsPhp Basics
Php Basics
Shaheed Udham Singh College of engg. n Tech.,Tangori,Mohali
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
Toni Kolev
 
Java XML Parsing
Java XML ParsingJava XML Parsing
Java XML Parsing
srinivasanjayakumar
 
JS Essence
JS EssenceJS Essence
JS Essence
Uladzimir Piatryka
 
WordPress Themes 101 - dotEduGuru Summit 2013
WordPress Themes 101 - dotEduGuru Summit 2013WordPress Themes 101 - dotEduGuru Summit 2013
WordPress Themes 101 - dotEduGuru Summit 2013
Curtiss Grymala
 
Apache Velocity
Apache Velocity Apache Velocity
Apache Velocity
yesprakash
 

Viewers also liked (12)

Recent resume
Recent resumeRecent resume
Recent resume
Sudharson M R
 
Saurav Srivastava CV..
Saurav Srivastava CV..Saurav Srivastava CV..
Saurav Srivastava CV..
Saurav srivastava
 
Resume
ResumeResume
Resume
Srinivas N
 
django
djangodjango
django
webuploader
 
CV(Arpit_Singh)
CV(Arpit_Singh)CV(Arpit_Singh)
CV(Arpit_Singh)
Arpit Singh
 
socialpref
socialprefsocialpref
socialpref
webuploader
 
Wipro resume
Wipro resumeWipro resume
Wipro resume
Kapil Chaudhary
 
Archana Jaiswal Resume
Archana Jaiswal ResumeArchana Jaiswal Resume
Archana Jaiswal Resume
Archana Jaiswal
 
Resume-Python-Developer-ZachLiu
Resume-Python-Developer-ZachLiuResume-Python-Developer-ZachLiu
Resume-Python-Developer-ZachLiu
Zhiqiang Liu
 
Python/Django Training
Python/Django TrainingPython/Django Training
Python/Django Training
University of Technology
 
Resume
ResumeResume
Resume
narsglance
 
Dana resume1
Dana resume1Dana resume1
Dana resume1
Ma.Danna Inigo
 
Ad

Similar to Introduction to Python and Django (20)

Django
DjangoDjango
Django
Narcisse Siewe
 
Intro to Web Development Using Python and Django
Intro to Web Development Using Python and DjangoIntro to Web Development Using Python and Django
Intro to Web Development Using Python and Django
Chariza Pladin
 
Django Documentation
Django DocumentationDjango Documentation
Django Documentation
Ying wei (Joe) Chou
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
MoniaJ
 
CCCDjango2010.pdf
CCCDjango2010.pdfCCCDjango2010.pdf
CCCDjango2010.pdf
jayarao21
 
Tango with django
Tango with djangoTango with django
Tango with django
Rajan Kumar Upadhyay
 
Akash rajguru project report sem v
Akash rajguru project report sem vAkash rajguru project report sem v
Akash rajguru project report sem v
Akash Rajguru
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
Shrinath Shenoy
 
1-_Introduction_To_Django_Model_and_Database (1).pptx
1-_Introduction_To_Django_Model_and_Database (1).pptx1-_Introduction_To_Django_Model_and_Database (1).pptx
1-_Introduction_To_Django_Model_and_Database (1).pptx
TamilGamers4
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Ahmed Salama
 
Basic Python Django
Basic Python DjangoBasic Python Django
Basic Python Django
Kaleem Ullah Mangrio
 
An Introduction to Django Web Framework
An Introduction to Django Web FrameworkAn Introduction to Django Web Framework
An Introduction to Django Web Framework
David Gibbons
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
Vlad Voskoboynik
 
Introduce Django
Introduce DjangoIntroduce Django
Introduce Django
Chui-Wen Chiu
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Jagdeep Singh Malhi
 
dJango
dJangodJango
dJango
Bob Chao
 
Django Introdcution
Django IntrodcutionDjango Introdcution
Django Introdcution
Nagi Annapureddy
 
Introduction to Django Course For Newbie - Advance
Introduction to Django Course For Newbie - AdvanceIntroduction to Django Course For Newbie - Advance
Introduction to Django Course For Newbie - Advance
yusufvabdullah001
 
Django Girls Tutorial
Django Girls TutorialDjango Girls Tutorial
Django Girls Tutorial
Kishimi Ibrahim Ishaq
 
Django course summary
Django course summaryDjango course summary
Django course summary
Udi Bauman
 
Intro to Web Development Using Python and Django
Intro to Web Development Using Python and DjangoIntro to Web Development Using Python and Django
Intro to Web Development Using Python and Django
Chariza Pladin
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
MoniaJ
 
CCCDjango2010.pdf
CCCDjango2010.pdfCCCDjango2010.pdf
CCCDjango2010.pdf
jayarao21
 
Akash rajguru project report sem v
Akash rajguru project report sem vAkash rajguru project report sem v
Akash rajguru project report sem v
Akash Rajguru
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
Shrinath Shenoy
 
1-_Introduction_To_Django_Model_and_Database (1).pptx
1-_Introduction_To_Django_Model_and_Database (1).pptx1-_Introduction_To_Django_Model_and_Database (1).pptx
1-_Introduction_To_Django_Model_and_Database (1).pptx
TamilGamers4
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Ahmed Salama
 
An Introduction to Django Web Framework
An Introduction to Django Web FrameworkAn Introduction to Django Web Framework
An Introduction to Django Web Framework
David Gibbons
 
Introduction to Django Course For Newbie - Advance
Introduction to Django Course For Newbie - AdvanceIntroduction to Django Course For Newbie - Advance
Introduction to Django Course For Newbie - Advance
yusufvabdullah001
 
Django course summary
Django course summaryDjango course summary
Django course summary
Udi Bauman
 
Ad

Recently uploaded (20)

Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : IntroductionJira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Microsoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentationMicrosoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentation
Digitalmara
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
New Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDBNew Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDB
ScyllaDB
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
Grannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI ExperiencesGrannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI Experiences
Lauren Parr
 
Maxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing placeMaxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing place
usersalmanrazdelhi
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure ModesCognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Dr. Tathagat Varma
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : IntroductionJira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Microsoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentationMicrosoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentation
Digitalmara
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
New Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDBNew Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDB
ScyllaDB
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
Grannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI ExperiencesGrannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI Experiences
Lauren Parr
 
Maxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing placeMaxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing place
usersalmanrazdelhi
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure ModesCognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Dr. Tathagat Varma
 

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/)