Slide 1

Slide 1 text

Intro to Python and Django Ken Cochrane 1 Tuesday, February 19, 13

Slide 2

Slide 2 text

Welcome • Introduction • Python tutorial • Django tutorial • Questions 2 Tuesday, February 19, 13

Slide 3

Slide 3 text

Warning • These were slides I made for a presentation • Viewed by themselves without the talk might make some of the slides less clear. 3 Tuesday, February 19, 13

Slide 4

Slide 4 text

Intro • About Ken • Django Maine • Sponsors • Food • Raffle 4 Tuesday, February 19, 13

Slide 5

Slide 5 text

Ken Cochrane • Twitter: @KenCochrane • Blog: http://KenCochrane.net • Work: http://dotCloud.com • Using python/django for about 5 years 5 Tuesday, February 19, 13

Slide 6

Slide 6 text

DjangoMaine • Started over a year ago • Meets once a month • http://www.DjangoMaine.com 6 Tuesday, February 19, 13

Slide 7

Slide 7 text

Sponsors • Base36 - Providing the food + Swag • dotCloud - Swag for raffle 7 Tuesday, February 19, 13

Slide 8

Slide 8 text

Questions • How many people have used python before? • How many people have used Django before? 8 Tuesday, February 19, 13

Slide 9

Slide 9 text

Python 9 Tuesday, February 19, 13

Slide 10

Slide 10 text

Python • Created 1991 • Guido van Rossum • http://python.org • Current versions: 2.7.3, 3.3.0 10 Tuesday, February 19, 13

Slide 11

Slide 11 text

What is python? • General purpose, high-level scripting language • Clear syntax and is expressive • Batteries included • Supports object oriented and functional programming 11 Tuesday, February 19, 13

Slide 12

Slide 12 text

Implementations • CPython (c) (most common) • PyPy (python) • Jython (Java) • IronPython (.NET) 12 Tuesday, February 19, 13

Slide 13

Slide 13 text

Python 2 or 3? • Python 2 is the status quo. (use 2.7.x) • Python 3.x is the present and the future • If you can use 3, do it. If not use 2.7.x with 3 in mind. 13 Tuesday, February 19, 13

Slide 14

Slide 14 text

Interpreters • python (comes standard) • Ipython (http://ipython.org) • Bpython (http://bpython-interpreter.org) 14 Tuesday, February 19, 13

Slide 15

Slide 15 text

Code Formatting • Formatting matters • No useless curly braces • No tabs, all spaces • use 4 spaces instead of 1 tab • Tip: Turn on hidden symbols in editor 15 Tuesday, February 19, 13

Slide 16

Slide 16 text

Editors • TextMate (OS X) • SublimeText • TextPad, notepad++(windows) • Vi, Emacs • many many more 16 Tuesday, February 19, 13

Slide 17

Slide 17 text

IDEs • PyCharm • Komodo • Wing IDE • many more 17 Tuesday, February 19, 13

Slide 18

Slide 18 text

Hello Name >>> def hello(name): ... print("Hello {0}".format(name)) ... >>> hello('ken') Hello ken Simple python example 18 Tuesday, February 19, 13

Slide 19

Slide 19 text

Common DataTypes • String • int • float • long • boolean • dict • list • set 19 Tuesday, February 19, 13

Slide 20

Slide 20 text

Data type Examples >>> string_variable = "string" >>> int_variable = 24 >>> float_variable = 2.4 >>> list_variable = [1, 2, 3, 4] >>> dict_variable = {'a':1, 2:'b', 'c':'c'} >>> tuple_variable = (1, 2) >>> boolean_variable = True 20 Tuesday, February 19, 13

Slide 21

Slide 21 text

String >>> a = "String Sentence!" >>> a 'String Sentence!' >>> a.upper() 'STRING SENTENCE!' >>> a.lower() 'string sentence!' >>> a.split(" ") ['String', 'Sentence!'] 21 Tuesday, February 19, 13

Slide 22

Slide 22 text

String cont. >>> a.strip() 'String Sentence!' >>> a.replace('!','?') 'String Sentence?' >>> a.startswith('Str') True >>> len(a) 16 >>> b = " other sentence" >>> a + b 'String Sentence! other sentence' 22 Tuesday, February 19, 13

Slide 23

Slide 23 text

String formatting >>> "Cat in the %s" % ('hat') 'Cat in the hat' >>> "Cat in the {0}".format("hat") 'Cat in the hat' >>> "Cat in the {0} knows nothing about {1}".format("Hat", "That") 'Cat in the Hat knows nothing about That' >>> "Cat in the {thing}".format(thing='hat') 'Cat in the hat' >>> "Cat in the {thing}, where is my {thing}".format(thing='hat') 'Cat in the hat, where is my hat' 23 Tuesday, February 19, 13

Slide 24

Slide 24 text

Numbers and Math • + plus • - minus • / slash • * asterisk • % percent • < less-than • > greater-than • <= less-than or equal • >= greater-than or equal • == equal • != not equal 24 Tuesday, February 19, 13

Slide 25

Slide 25 text

Math Examples >>> a = 5 >>> a 5 >>> a + 5 10 >>> a - 6 -1 >>> a = a + 5 >>> a 10 >>> a += 1 >>> a 11 >>> a / 2 5 >>> a / 2.0 5.5 >>> 5 % 2 1 >>> 5 / 2 2 25 Tuesday, February 19, 13

Slide 26

Slide 26 text

lists >>> l = [1, 2, 3] >>> l.append(4) >>> l [1, 2, 3, 4] >>> l.pop() 4 >>> l [1, 2, 3] >>> l.reverse() >>> l [3, 2, 1] >>> l.count(1) 1 >>> l.remove(2) >>> l [3, 1] >>> l.sort() >>> l [1, 3] >>> l2 = ['a', 'b'] >>> l + l2 [1, 3, 'a', 'b'] 26 Tuesday, February 19, 13

Slide 27

Slide 27 text

Dictionaries >>> d = {'a':1, 'b':2, 3:3, 'c':'c'} >>> d {'a': 1, 3: 3, 'c': 'c', 'b': 2} >>> 'a' in d True >>> 'z' in d False >>> d['d'] = 'd' >>> d {'a': 1, 3: 3, 'c': 'c', 'b': 2, 'd': 'd'} >>> e = {'e':'e'} >>> d.update(e) >>> d {'a': 1, 'c': 'c', 3: 3, 'e': 'e', 'd': 'd', 'b': 2} 27 Tuesday, February 19, 13

Slide 28

Slide 28 text

Conditional Logic • < less-than • > greater-than • <= less-than or equal • >= greater-than or equal • == equal • != not equal • “is” object identity • “is not” negated object identity 28 Tuesday, February 19, 13

Slide 29

Slide 29 text

If statements >>> a = 8 >>> if a > 10: ... print("a is bigger than 10") ... elif a > 5: ... print("a is bigger than 5") ... else: ... print("a is <= 5") ... a is bigger than 5 Example of a simple if else statement 29 Tuesday, February 19, 13

Slide 30

Slide 30 text

For Loop # loop 1 to 3 >>> for x in range(1, 4): ... print(x) 1 2 3 >>> a = [1, 2, 3] >>> for x in a: ... print(x) 1 2 3 30 Tuesday, February 19, 13

Slide 31

Slide 31 text

While Loop >>> count = 0 >>> while count < 4: ... print(count) ... count += 1 0 1 2 3 31 Tuesday, February 19, 13

Slide 32

Slide 32 text

Functions >>> def hello(name='fish'): ... print("hello {0}".format(name)) ... ... >>> hello() hello fish >>> hello("ken") hello ken >>> hello(name="kenny") hello kenny 32 Tuesday, February 19, 13

Slide 33

Slide 33 text

Functions cont. >>> def hello(first, last='Smith'): ... print("hello {0} {1}".format(first, last)) ... >>> hello("ken", "cochrane") hello ken cochrane >>> hello("ken") hello ken Smith >>> hello("ken", last="cochrane") hello ken cochrane >>> hello() Traceback (most recent call last): File "", line 1, in TypeError: hello() takes at least 1 argument (0 given) >>> hello(last="cochrane", "ken") File "", line 1 SyntaxError: non-keyword arg after keyword arg 33 Tuesday, February 19, 13

Slide 34

Slide 34 text

Functions Cont. 2 >>> def adder(a, b): ... return a + b ... >>> adder(1, 2) 3 >>> def joiner(a, b): ... return a, b ... >>> joiner(1, 2) (1, 2) 34 Tuesday, February 19, 13

Slide 35

Slide 35 text

Classes >>> class myclass(object): ... ... def __init__(self, first, last): ... self.first = first ... self.last = last ... self.status = "NEW" ... ... def __repr__(self): ... return u"{0} class".format(self.full_name) ... ... def change_status(self, status): ... self.status = status ... ... @property ... def full_name(self): ... return “{0} {1}”.format(self.first, self.last) ... 35 Tuesday, February 19, 13

Slide 36

Slide 36 text

Classes Cont. >>> my = myclass("joe", "smith") >>> my joe smith class >>> my.first 'joe' >>> my.last 'smith' >>> my.full_name 'joe smith' >>> my.status 'NEW' >>> my.change_status("OLD") >>> my.status 'OLD' 36 Tuesday, February 19, 13

Slide 37

Slide 37 text

Exceptions >>> def div(a, b): ... try: ... return a / b ... except ZeroDivisionError as exp: ... return 0 ... >>> div(2,1) 2 >>> div(2,0) 0 37 Tuesday, February 19, 13

Slide 38

Slide 38 text

Exceptions Cont. >>> def div(a, b): ... try: ... return a / b ... except ZeroDivisionError as exc: ... raise Exception("Wha? Div by zero yo!") ... >>> div(2,0) Traceback (most recent call last): File "", line 1, in File "", line 5, in div Exception: Wha? Div by zero yo! 38 Tuesday, February 19, 13

Slide 39

Slide 39 text

Python resources • http://python.org • http://LearnPythonTheHardway.org • http://www.CodeCademy.com That was a very quick overview, look at these resources to learn more about python 39 Tuesday, February 19, 13

Slide 40

Slide 40 text

Django Tutorial 40 Tuesday, February 19, 13

Slide 41

Slide 41 text

Django Tutorial • Guided tour using the Official Django tutorial • https://docs.djangoproject.com/en/ 1.4/intro/tutorial01/ • There isn’t enough time to go over everything, so I skipped some parts. 41 Tuesday, February 19, 13

Slide 42

Slide 42 text

Before we get started • Django Intro • Installing python packages • Install Django 42 Tuesday, February 19, 13

Slide 43

Slide 43 text

What is django? • Django is a High-level Python web framework that encourages rapid development and clean, pragmatic design. • MVT - Model , View, Template 43 Tuesday, February 19, 13

Slide 44

Slide 44 text

Who uses Django? • Disqus • Instagram • Pinterest • Mozilla • Rdio • Open Stack 44 Tuesday, February 19, 13

Slide 45

Slide 45 text

Batteries included • ORM • Templates • Admin site • Authentication/ Authorization • I18N • Forms • Validators • Caching • Comments • GeoDjango • CSRF protection • Sites • testing • Dev server • Elegant URL design 45 Tuesday, February 19, 13

Slide 46

Slide 46 text

Installing Django • Today’s Requirements: • Python 2.6.x+ (ideally 2.7.x) • distribute or setup tools • pip • virtualenv • virtualenv wrapper 46 Tuesday, February 19, 13

Slide 47

Slide 47 text

Pip + Distribute • Tools for installing and managing python packages • Pip requires Distribute 47 Tuesday, February 19, 13

Slide 48

Slide 48 text

Install Distribute $ curl -O http://python-distribute.org/ distribute_setup.py $ python distribute_setup.py Or if you have easy_install you can run this: $ easy_install distribute 48 Tuesday, February 19, 13

Slide 49

Slide 49 text

Install PIP $ curl -O https://raw.github.com/pypa/pip/ master/contrib/get-pip.py $ [sudo] python get-pip.py 49 Tuesday, February 19, 13

Slide 50

Slide 50 text

Virtualenv • Python Virtual Environments make it easier for you to manage multiple projects’ dependencies on your machine at once • http://www.virtualenv.org 50 Tuesday, February 19, 13

Slide 51

Slide 51 text

Install virtualenv $ [sudo] pip install virtualenv 51 Tuesday, February 19, 13

Slide 52

Slide 52 text

Virtualenv wrapper • Dealing with all of your virtualenv’s can become a pain. • Install Virtualenv Wrapper to help manage them. • http://virtualenvwrapper.readthedocs.org 52 Tuesday, February 19, 13

Slide 53

Slide 53 text

Install Virtualenv Wrapper $ pip install virtualenvwrapper Edit your shell startup script to include source /usr/local/bin/virtualenvwrapper.sh 53 Tuesday, February 19, 13

Slide 54

Slide 54 text

Create a virtualenv $ mkvirtualenv tutorial # it should automatically switch, but if not run $ workon tutorial 54 Tuesday, February 19, 13

Slide 55

Slide 55 text

install Django $ pip install django==1.4.3 55 Tuesday, February 19, 13

Slide 56

Slide 56 text

django-admin.py • django-admin.py is Django’s command-line utility for admin tasks • Use it to start new projects • https://docs.djangoproject.com/en/1.4/ref/django-admin/ 56 Tuesday, February 19, 13

Slide 57

Slide 57 text

Create a new project Create a projects directory somewhere on your computer $ mkdir -p ~/projects $ cd ~/projects $ django-admin.py startproject mysite 57 Tuesday, February 19, 13

Slide 58

Slide 58 text

Project directory mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py 58 Tuesday, February 19, 13

Slide 59

Slide 59 text

Verify project • Let’s make sure your django project is configured correctly. • Best to do this now before you make any changes. • $ python manage.py runserver • Should have started with no errors. • I’ll come back to runserver a little later 59 Tuesday, February 19, 13

Slide 60

Slide 60 text

settings.py • This is where you configure your Django application • Lots of sane defaults • Many more advanced ways of configuring settings, avoid for now 60 Tuesday, February 19, 13

Slide 61

Slide 61 text

Settings.py Cont. • Common things you need to change • DEBUG • ADMINS • DATABASES • TIME_ZONE • MEDIA_ROOT and STATIC_ROOT • INSTALLED_APPS • MIDDLEWARE • LOGGING 61 Tuesday, February 19, 13

Slide 62

Slide 62 text

Settings.py Cont. 2 • For simplicity we will mostly keep the settings the way they are for now. • Let’s use SQLite for a database • Change DATABASES.default.ENGINE to 'django.db.backends.sqlite3' • Change DATABASES.default.NAME to ‘tutorial.db’ 62 Tuesday, February 19, 13

Slide 63

Slide 63 text

Syncdb Command • The syncdb command looks at the INSTALLED_APPS setting and creates the needed database tables for the apps listed • Creates superuser if one doesn’t exist. • $ python manage.py syncdb 63 Tuesday, February 19, 13

Slide 64

Slide 64 text

Add an App • A Django project consists of Django apps • $ python manage.py startapp polls 64 Tuesday, February 19, 13

Slide 65

Slide 65 text

polls app layout polls/ __init__.py models.py tests.py views.py 65 Tuesday, February 19, 13

Slide 66

Slide 66 text

Django Models • A Model is a normal python file, usually named models.py • Contains the essential fields and behaviors of the data you’re storing. • Generally, each model maps to a single database table 66 Tuesday, February 19, 13

Slide 67

Slide 67 text

Django Models Cont. • Each model is a Python class that subclasses django.db.models.Model • Each attribute of the model represents a database field. • With all of this, Django gives you an automatically-generated database-access API. • Creates the initial database tables for you. 67 Tuesday, February 19, 13

Slide 68

Slide 68 text

Model Fields • AutoField • BigIntegerField • BooleanField • CharField • CommaSeperatedIntegerField • DateField • DateTimeField • DecimalField • EmailField • FileField • FilePathField • FloatField • ImageField • IntegerField • IPAddressField • GenericIPAddressField • NullBooleanField • PositiveIntegerField • SlugField • SmallIntegerField • TextField • TimeField • URLField 68 Tuesday, February 19, 13

Slide 69

Slide 69 text

Model field options • null • blank • choices • db_column • db_index • db_tablespace • default • editable • error_messages • help_text • primary_key • unique • unique_for_date • unique_for_month • unique_for_year • verbose_name • validators 69 Tuesday, February 19, 13

Slide 70

Slide 70 text

Model Relationships • Foreign Key • Many To Many • One to One 70 Tuesday, February 19, 13

Slide 71

Slide 71 text

Polls/models.py from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField() Add the following to your polls/models.py 71 Tuesday, February 19, 13

Slide 72

Slide 72 text

Activating models • Adding that small bit of code allows Django to do the following: • Builds the “Create table” sql statement • Creates a python db api for accessing those db tables 72 Tuesday, February 19, 13

Slide 73

Slide 73 text

Activating Models Cont. • In order for Django to know about our new app, we need to add our app to our INSTALLED_APPS setting in our Settings.py INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: # 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'polls', # <---- We added it here ) 73 Tuesday, February 19, 13

Slide 74

Slide 74 text

Generated Model sql • If you want to know what SQL will be run when you kick off syncdb, you can use the “sql” command • $ python manage.py sql polls BEGIN; CREATE TABLE "polls_poll" ( "id" serial NOT NULL PRIMARY KEY, "question" varchar(200) NOT NULL, "pub_date" timestamp with time zone NOT NULL ); CREATE TABLE "polls_choice" ( "id" serial NOT NULL PRIMARY KEY, "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id") DEFERRABLE INITIALLY DEFERRED, "choice" varchar(200) NOT NULL, "votes" integer NOT NULL ); COMMIT; 74 Tuesday, February 19, 13

Slide 75

Slide 75 text

Other Helpful commands • validate - Checks for any errors in your models • sqlcustom - Outputs any custom sql statements that are defined for the app • sqlclear - Outputs the necessary drop table statements for the app. • sqlindexes - Outputs the create index statements • sqlall - Outputs all sql (creates, custom, index, etc) for these models 75 Tuesday, February 19, 13

Slide 76

Slide 76 text

Running syncdb • Run syncdb to create the new tables for your polls app • $ python manage.py syncdb 76 Tuesday, February 19, 13

Slide 77

Slide 77 text

Django Shell • One of the cooler features of Django is the shell • $ python manage.py shell • Starts an interactive python shell that lets you play around with your app form the command line. • Install Bpython or Ipython for more features 77 Tuesday, February 19, 13

Slide 78

Slide 78 text

Fire up the shell • $ python manage.py shell # Import the model classes we just wrote. >>> from polls.models import Poll, Choice >>> Poll.objects.all() [] # No polls are in the system yet. >>> from django.utils import timezone >>> p = Poll(question="What's new?", pub_date=timezone.now()) # Save the object into the database. You have to call save() explicitly. >>> p.save() >>> p.id 1 78 Tuesday, February 19, 13

Slide 79

Slide 79 text

Shell cont. # Access database columns via Python attributes. >>> p.question "What's new?" >>> p.pub_date datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=) # Change values by changing the attributes, then calling save(). >>> p.question = "What's up?" >>> p.save() # objects.all() displays all the polls in the database. >>> Poll.objects.all() [] # count all of objects in database >>> Poll.objects.count() 1 79 Tuesday, February 19, 13

Slide 80

Slide 80 text

Models Cont. • Human readable object names class Poll(models.Model): # ... def __unicode__(self): return self.question class Choice(models.Model): # ... def __unicode__(self): return self.choice 80 Tuesday, February 19, 13

Slide 81

Slide 81 text

Custom model methods • You can add your own methods to make your live easier. import datetime from django.utils import timezone # ... class Poll(models.Model): # ... def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) 81 Tuesday, February 19, 13

Slide 82

Slide 82 text

Django Admin site • Another powerful part of Django is the automatic admin interface. • It reads the metadata in your model to provide a powerful, production ready interface • It is disabled by default 82 Tuesday, February 19, 13

Slide 83

Slide 83 text

ACTIVATING DJANGO ADMIN • settings.py • Uncomment “django.contrib.admin” in INSTALLED_APPS setting. • urls.py • Uncomment the 3 lines shown in the comments, to be for admin. • Run syncdb to create table 83 Tuesday, February 19, 13

Slide 84

Slide 84 text

urls.py • The urls.py is a way to map application urls to django application views. • We will go into more detail in a little bit 84 Tuesday, February 19, 13

Slide 85

Slide 85 text

Activating Django Admin Cont. • mysite/urls.py when finished from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', '{{ project_name }}.views.home', name='home'), # url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), ) 85 Tuesday, February 19, 13

Slide 86

Slide 86 text

Running django admin • $ python manage.py runserver • open browser, point to • http://localhost:8000 • Login with your admin user/password you created during first ‘syncdb’ 86 Tuesday, February 19, 13

Slide 87

Slide 87 text

Configuring Django Admin • Django admin needs to know about your application and it’s models before they will work in the admin • You do this by creating a / admin.py file and configure your models 87 Tuesday, February 19, 13

Slide 88

Slide 88 text

poll/admin.py • There are lots of different ways to configure your models to work in the admin, but we will just use the normal way for now. • Create a polls/admin.py and add the following from polls.models import Poll, Choice from django.contrib import admin admin.site.register(Poll) admin.site.register(Choice) 88 Tuesday, February 19, 13

Slide 89

Slide 89 text

Django Admin advanced • There are a lot of different ways to customize the django admin, we don’t have time today to go into all of them. • Follow the tutorial online to find out more. • https://docs.djangoproject.com/en/ 1.4/intro/tutorial02/ 89 Tuesday, February 19, 13

Slide 90

Slide 90 text

Views • 3 types of views • Generic views • Function based views • Class based views 90 Tuesday, February 19, 13

Slide 91

Slide 91 text

Function based views • The view is where the glue code lives. It ties your request, model, and template together. • Here is a very simple view from django.http import HttpResponse def index(request): return HttpResponse("Hello, world.") 91 Tuesday, February 19, 13

Slide 92

Slide 92 text

Views Cont. Add this to your mysite/views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the index.") def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id) def results(request, poll_id): return HttpResponse("results of poll %s." % poll_id) def vote(request, poll_id): return HttpResponse("You're voting on poll %s." % poll_id) 92 Tuesday, February 19, 13

Slide 93

Slide 93 text

urls.py • The urls.py allows you to decouple your business logic with your urls. You can change the url later on without changing the code. • Uses regular expressions to match urls to views • Allows you to create nice looking urls 93 Tuesday, February 19, 13

Slide 94

Slide 94 text

mysite/urls.py Change the mysite/urls.py to look like this from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^polls/$', 'polls.views.index'), url(r'^polls/(?P\d+)/$', 'polls.views.detail'), url(r'^polls/(?P\d+)/results/$', 'polls.views.results'), url(r'^polls/(?P\d+)/vote/$', 'polls.views.vote'), url(r'^admin/', include(admin.site.urls)), ) 94 Tuesday, February 19, 13

Slide 95

Slide 95 text

urls to views url(r'^polls/(?P\d+)/$', 'polls.views.detail'), def detail(request, poll_id): return HttpResponse("Poll %s." % poll_id) Notice how the variable in the url matches the parameter in the view 95 Tuesday, February 19, 13

Slide 96

Slide 96 text

More views • Those views didn’t do much, lets do some more. • Change the index view to this. from polls.models import Poll from django.http import HttpResponse def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] output = ', '.join([p.question for p in latest_poll_list]) return HttpResponse(output) 96 Tuesday, February 19, 13

Slide 97

Slide 97 text

Django Templates • Designed to strike a balance between power and ease. • Clear line between logic and presentation, no code allowed • Has a set of built in tags and filter • Ability to write custom tags and filters • Block based to support template inheritance 97 Tuesday, February 19, 13

Slide 98

Slide 98 text

Common template tags • block • for • if • include • url • extends 98 Tuesday, February 19, 13

Slide 99

Slide 99 text

Common template filters • date • default • linebreaksbr • pluralize • safe • truncatewords • upper • wordwrap • wordcount • yesno • length 99 Tuesday, February 19, 13

Slide 100

Slide 100 text

Template example {% extends "base_generic.html" %} {% block title %}{{ section.title }}{% endblock title %} {% block content %}

{{ section.title }}

{% for story in story_list %}

{{ story.headline|upper }}

{{ story.tease|truncatewords:"100" }}

{% endfor %} {% endblock content %} 100 Tuesday, February 19, 13

Slide 101

Slide 101 text

Lets add templates to our view • Our poll view is pretty basic, lets add a template to make it better. • create a ‘templates/polls’ directory under polls app. • create a file called index.html 101 Tuesday, February 19, 13

Slide 102

Slide 102 text

index.html {% if latest_poll_list %} {% else %}

No polls are available.

{% endif %} Put this in your index.html 102 Tuesday, February 19, 13

Slide 103

Slide 103 text

index view Now that we have a template we need to change our view, to use it. from django.template import Context, loader from polls.models import Poll from django.http import HttpResponse def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] t = loader.get_template('polls/index.html') c = Context({ 'latest_poll_list': latest_poll_list, }) return HttpResponse(t.render(c)) 103 Tuesday, February 19, 13

Slide 104

Slide 104 text

Django Forms • Forms are the glue that helps convert HTML form data into something useful for views • Also provides validation • 2 types of Django Forms • Model forms • Regular forms 104 Tuesday, February 19, 13

Slide 105

Slide 105 text

Forms • The Form classes look a lot like Models. They have fields with attributes, and widgets. • Widgets tell django what type of HTML field to map it too. • Django can create HTML forms for you from a form object. 105 Tuesday, February 19, 13

Slide 106

Slide 106 text

Form example from django import forms class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() cc_myself = forms.BooleanField(required=False) 106 Tuesday, February 19, 13

Slide 107

Slide 107 text

Using form in a view Example from django.shortcuts import render from django.http import HttpResponseRedirect def contact(request): if request.method == 'POST': # If the form has been submitted... form = ContactForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... return HttpResponseRedirect('/thanks/') # Redirect after POST else: form = ContactForm() # An unbound form return render(request, 'contact.html', { 'form': form, }) 107 Tuesday, February 19, 13

Slide 108

Slide 108 text

Display a form in a template example {% csrf_token %} {{ form.as_p }}

Subject:

Message:

Sender:

Cc myself:

Becomes 108 Tuesday, February 19, 13

Slide 109

Slide 109 text

Model Forms • Model Forms are just like regular forms, but they make it easier to get the form data into models. • Instead of having to move the data from the form to the model, it is done automatically, and saved to the db when save() is called. 109 Tuesday, February 19, 13

Slide 110

Slide 110 text

Model form example from django.db import models from django.forms import ModelForm, Textarea class Author(models.Model): name = models.CharField(max_length=100) title = models.CharField(max_length=3) birth_date = models.DateField(blank=True, null=True) def __unicode__(self): return self.name class AuthorForm(ModelForm): class Meta: model = Author fields = ('name', 'title', 'birth_date') widgets = { 'name': Textarea(attrs={'cols': 80, 'rows': 20}), } 110 Tuesday, February 19, 13

Slide 111

Slide 111 text

Free Django Hosting • If you want a place you can deploy your application for free, and play around with it. • Check out : http://www.dotCloud.com • Django Tutorial: http://docs.dotcloud.com/tutorials/python/django/ 111 Tuesday, February 19, 13

Slide 112

Slide 112 text

Django Resources • DjangoProject.com • DjangoBook.com • Two Scoops of Django ebook • gettingstartedwithdjango.com 112 Tuesday, February 19, 13

Slide 113

Slide 113 text

Too much to cover so little time • This was just a quick overview of Django and Python, there is way, way more then this, and I apologize if I skimmed over a part you really wanted to know more about. 113 Tuesday, February 19, 13

Slide 114

Slide 114 text

Thank you • If this was helpful, or if you have any suggestions on how to make it better, please contact me on twitter (@kencochrane) or send me an email [email protected] 114 Tuesday, February 19, 13