Introduction to Django - OSCON 2012 - Cdn.

39
Introduction to Django - OSCON 2012 Jacob Kaplan-Moss, Revolution Systems Copyright © 2012 Revolution Systems, LLC. All rights reserved.

Transcript of Introduction to Django - OSCON 2012 - Cdn.

Page 1: Introduction to Django - OSCON 2012 - Cdn.

Introduction to Django - OSCON 2012

Jacob Kaplan-Moss, Revolution Systems

Copyright © 2012 Revolution Systems, LLC.All rights reserved.

www.princexml.com
Prince - Non-commercial License
This document was created with Prince, a great way of getting web content onto paper.
Page 2: Introduction to Django - OSCON 2012 - Cdn.

Table of Contents1. Introduction

4Which Django version should I use? .................5Installing Python “right” .....................................6Installing Django ................................................7“Projects”...........................................................8First steps ..........................................................

2. Apps, models, and the admin2“App” .................................................................3“Model”..............................................................

12Modeling in SQL ..............................................13Why Django models in Python ........................14Models in Python.............................................15Defining Models...............................................17All about syncdb..............................................18Model metadata...............................................19Playing with models at the shell ......................20Playing with models at the shell ......................23Slidebar: what's a slug? ..................................24Django’s admin interface.................................25Activating the admin ........................................

3. Introduction to views2Views..................................................................3URLs ..................................................................4URL design ........................................................5URLs in Django ..................................................6Regex crash course ...........................................9Dissecting a request ..........................................

11django.shortcuts.render...................................12django.shortcuts.get_object_or_404 ...............13Templates ........................................................14What’s a template? ..........................................15Where do templates go?..................................16Variables ..........................................................17The magic dot ..................................................18Filters ...............................................................19Filters ...............................................................20Tags .................................................................21Tags .................................................................22Template inheritance........................................23“base template” ...............................................24“child template” ...............................................26Inheritance tips.................................................

Page 3: Introduction to Django - OSCON 2012 - Cdn.

Django Training

Section 1: Introduction to Django

1

“”

Django is a high-level Python web framework that encourages rapid

development and clean, pragmatic design.

2

Page 4: Introduction to Django - OSCON 2012 - Cdn.

Documentationhttp://django.me/design

http://www.djangobook.com/en/2.0/chapter01/

3

Which Django version should I use?

4

• If possible, use the latest (Django 1.4).•At the very least, upgrade to the latest minor

release (1.3.1).•“All the cool stuff’s on dev” (and it’s quite stable).

Page 5: Introduction to Django - OSCON 2012 - Cdn.

Installing Python “right”

•Django — the ecosystem and deployment in particular — work best if you have a “modern” Python kit.

• Installation guides:OSX: http://bit.ly/python-osxWindows: http://bit.ly/python-windowsLinux: http://bit.ly/python-linux

5

Installing Django

6

•pip#install#Django is the one true way.(if that doesn’t work, learn about pip: http://pip.rtfd.org/)

•easy_install#Django is acceptable… for now.

•Dev install: pip#install#git+https://github.com/django/django.git

•Preferably in a virtualenv.http://virtualenv.rtfd.org/

Page 6: Introduction to Django - OSCON 2012 - Cdn.

“Projects”

7

•A collection of settings for a single instance of Django.

•Usually, one project == one site.For example: djangoproject.com is one project; people.djangoproject.com is another; docs.djangoproject.com is a third.

First steps•Create a project:

mkdir#<mysite>

django8admin.py#startproject#<projectname>0<mysite>

•Run the dev server:cd#<mysite>

python#manage.py#runserver

•Set up your database (<projectname>/settings.py)• Initial syncdb:

python#manage.py#syncdb

8

Page 7: Introduction to Django - OSCON 2012 - Cdn.

http://django.me/about-settings

http://django.me/settings

http://django.me/manage.py

Documentation

9

Exercise 1“it worked!”

10

Page 8: Introduction to Django - OSCON 2012 - Cdn.

Django Training

Introduction to apps, models, and the admin

1

“App”

2

A reusable collection of data and code

making up a logical unit.

Page 9: Introduction to Django - OSCON 2012 - Cdn.

“Model”

3

•The definitive source of data about your data.•Where your “business logic” lives.•The “M” in MVC (Model-View-Controller).

(sort of)

•Django’s ORM (Object-Relational Mapper).(kinda)

•Modeling data is hard, and even harder to explain succinctly. We’ll work through an example:

4

Blog

Page 10: Introduction to Django - OSCON 2012 - Cdn.

5

Blog

Entry

Author

Photo

Comment

Tag

Gallery

6

Blog

Entry

Author Photo

Comment

Tag

Gallery

Page 11: Introduction to Django - OSCON 2012 - Cdn.

7

Blog

Entry

Author Photo

Comment Tag

Gallery

8

Blog

Author

Photo

Gallery

Comment Tag

Entry

Page 12: Introduction to Django - OSCON 2012 - Cdn.

9

Blog

Author

Photo

Gallery

Comment Tag

EntryProject

10

Blog

Author

Photo

Gallery

Comment Tag

EntryApps

Page 13: Introduction to Django - OSCON 2012 - Cdn.

11

Blog

Author

Photo

Gallery

Comment Tag

EntryModels

CREATE&TABLE&"entries_entry"&(&&&&"id"&integer&NOT&NULL&PRIMARY&KEY,&&&&"author_id"&integer&NOT&NULL,&&&&"pub_date"&datetime&NOT&NULL,&&&&"headline"&varchar(200)&NOT&NULL,&&&&"slug"&varchar(50)&NOT&NULL&UNIQUE,&&&&"summary"&text&NOT&NULL,&&&&"body"&text&NOT&NULL)

12

Modeling in SQL

Page 14: Introduction to Django - OSCON 2012 - Cdn.

•SQL is tough.•SQL knows no version control.•DRY.•Python is fun!

Why Django models in Python

13

from&django.db&import&models

class&Author(models.Model):&&&&first_name&=&models.CharField(max_length=200)&&&&last_name&=&models.CharField(max_length=200)&&&&bio&=&models.TextField(blank=True)

14

Models in Python

Page 15: Introduction to Django - OSCON 2012 - Cdn.

Defining Models

15

• Create an “app”:python&manage.py&startapp&<appname>

• “Install” your app in settings.py:INSTALLED_APPS&=&(

&&&&"django.contrib.auth",

&&&&...

&&&&"<appname>"

)

• Define the model in <appname>/models.py.• Install the app in the database:

python&manage.py&syncdb

Exercise 1

16

Page 16: Introduction to Django - OSCON 2012 - Cdn.

All about syncdb

17

•Examines all INSTALLED_APPS, looking for models that are defined but not in the database. Those models are created (using SQL generated by manage.py&sqlall).

•Not very smart: won’t update existing models; won’t remove removed models.

• In development, you can use manage.py&reset to drop an app and start over, but this causes data loss!

•In the real world, you’ll need a schema migration tool (South; covered later in the class).

Model metadata

18

• Models are more than just fields; you can use them to define some useful metadata. For example:

• __unicode__ converts models to strings:class&Author(models.Model):

&&&&...

""""def"__unicode__(self):

""""""""return"self.first_name"+"'"'"+"self.last_name

• Inner Meta class can provide more options, like “human” names and control over database tables:

class&Person(models.Model):

&&&&...

""""class"Meta(object):

""""""""verbose_name_plural"=""people"

""""""""db_table"=""people_table"

Page 17: Introduction to Django - OSCON 2012 - Cdn.

Playing with models at the shell

•Django takes a bit of bootstrapping, so to play with your models interactively, use the shell command:

python&manage.py&shell

•This is just the Python shell, but with Django all set up and “scoped” into your project.

19

Playing with models at the shell>>>&from"authors.models"import"Author

>>>&Author.objects.all()[]

>>>&Author.objects.create(first_name='Miguel',"last_name='de"Cervantes')<Author:&Miguel&de&Cervantes>

>>>&Author.objects.all()[<Author:&Miguel&de&Cervantes>]

>>>&a"="Author.objects.all()[0]>>>&a.last_nameu'de&Cervantes'

>>>&a.last_name"=""Smith">>>&a.save()>>>&Author.objects.all()[<Author:&Miguel&Smith>]

20

Page 18: Introduction to Django - OSCON 2012 - Cdn.

http://django.me/models

http://www.djangobook.com/en/2.0/chapter05/

Documentation

21

Exercise 2

22

Page 19: Introduction to Django - OSCON 2012 - Cdn.

http://ljworld.com/news/2011/sep/30/bankHamericaHstartHchargingHdebitHcardHfees/

http://pypi.python.org/pypi/Django/1.3.1

http://amazon.com/KindleHTouchHWiHFiHInkHDisplay/dp/B005890G8Y/

Slidebar: what's a slug?

23

Django’s admin interface

24

•“A Web-based interface, limited to trusted site administrators, that enables the adding, editing and deletion of site content.”

•Not exactly a CMS, but the starting point for one, perhaps.

Page 20: Introduction to Django - OSCON 2012 - Cdn.

Activating the admin•Un-comment a line in <project>/settings.py,

three lines in <project>/urls.py.

•Run manage.py&syncdb.•Create an admin definition in <app>/admin.py:

from&django.contrib&import&adminfrom&.models&import&Author

class&AuthorAdmin(admin.ModelAdmin):&&&&pass

admin.site.register(Author,&AuthorAdmin)

25

from&django.contrib&import&adminfrom&yabl.authors.models&import&Author

admin.site.register(Author)

26

Page 21: Introduction to Django - OSCON 2012 - Cdn.

INSTALLED_APPS&=&(&&&&'django.contrib.auth',&&&&'django.contrib.contenttypes',&&&&'django.contrib.sessions',&&&&'django.contrib.sites',""""'django.contrib.admin',

&&&&'yabl.authors',&&&&'yabl.entries',)

27

$&python"manage.py"syncdbCreating&table&django_admin_logInstalling&index&for&admin.LogEntry&model

28

Page 22: Introduction to Django - OSCON 2012 - Cdn.

from&django.conf.urls.defaults&import&*

#&Uncomment&the&next&two&lines&to&enable&the&admin:from"django.contrib"import"admin

admin.autodiscover()

urlpatterns"="patterns('',

&&&&#&Example:&&&&#&(r'^yabl/',&include('yabl.foo.urls')),

&&&&#&Uncomment&the&admin/doc&line&below&and&add&'django.contrib.admindocs'&&&&&#&to&INSTALLED_APPS&to&enable&admin&documentation:&&&&#&(r'^admin/doc/',&include('django.contrib.admindocs.urls')),

&&&&#&Uncomment&the&next&line&to&enable&the&admin:""""(r'^admin/',"include(admin.site.urls)),

)

29

30

Page 23: Introduction to Django - OSCON 2012 - Cdn.

31

32

Page 24: Introduction to Django - OSCON 2012 - Cdn.

33

from&django.contrib&import&adminfrom&yabl.authors.models&import&Author

class"AuthorAdmin(admin.ModelAdmin):

""""pass

admin.site.register(Author,"AuthorAdmin)

34

Page 25: Introduction to Django - OSCON 2012 - Cdn.

Documentationhttp://django.me/admin

35

Exercise 3

36

Page 26: Introduction to Django - OSCON 2012 - Cdn.

Django Training

Introduction to URLs, views, and templates

1

Views

2

•A “type” of web page in your application: a homepage, an index of blog posts, an individual blog post, etc.

•Not exactly the “V” part of MVC: views contain all the logic for a given page, but do not specify the visual presentation of that page.

•Most of your time writing Django apps will be spent writing views, so Django gets out of your way here.

•This is where the fun begins!

Page 27: Introduction to Django - OSCON 2012 - Cdn.

URLs

3

•Wait, I thought we were talking about views?•Django makes designing URLs an explicit part of

application design; URLs are part of the UI of your web application.

URL design

4

•Bad URLs:page.php Why do I need to know you’re using PHP?

script.cgi?pageid=144 What’s at id=145?

StoryPage.aspx Hello, a security hole!

0,2097,1-1-30-72-407-4752,00.html wat

•Good URLs:/entries//entries/hello-world/

•See also: “Cool URIs don’t change”http://www.w3.org/Provider/Style/URI.html

Page 28: Introduction to Django - OSCON 2012 - Cdn.

URLs in Django•Each project has a URLconf (e.g. yabl/urls.py).•Serves as a sort of “table of contents” for your site.• Incoming URLs are matched against a regular

expression, and then dispatched to a view function.

urlpatterns*=*patterns('',

****...

****url(*r'^authors/(\d+)/$'*,*'authors.views.author_detail'*),

****...

)

5

regex view function

Regex crash coursea The letter “a”.a+ One or more “a”s.b? Zero or one “b”s.c{1,3} One, two, or three “c”s.. Any single character.[abc] Either an “a”, “b”, or “c”.[A6Z] Any character between “A” and “Z”.[A6Za6z069]? Zero or one letters “A-Z”, “a-z”, or “0-9”.(\d{3,4}) A group containing three or four digits.(\w*) A group containing zero or more word characters (letters/digits).[^/]+ One or more characters until (and not including) a forward slash.^(joe|bob) A string starting with “joe” or “bob”.(?P<id>\d+) A group named “id” containing one or more digits.article/$ A string ending with “article/”

6

Page 29: Introduction to Django - OSCON 2012 - Cdn.

Documentationhttp://django.me/urls

7

Exercise 1

8

Page 30: Introduction to Django - OSCON 2012 - Cdn.

•GETQ/authors/1/

•ROOT_URLCONF

•yabl.urls

•(r'^authors/$',Q'author_list')QQQQQQQQQQ(no match)

•(r'^authors/(\d+)/',Q'author_detail')QQQ(match!)

•author_detail(request,Q'1')

Dissecting a request

9

Exercise 2

10

Page 31: Introduction to Django - OSCON 2012 - Cdn.

fromQdjango.shortcutsQimportQrenderfrom.modelsQimportQAuthor

defQauthor_list(request):QQQQreturnQrender(request,QQQQQQQQQ"authors/index.html",QQQQQQQQQ{"authors"Q:QAuthor.objects.all()}QQQQ)

11

django.shortcuts.render

fromQdjangoQimportQtemplatefromQdjango.httpQimportQHttpResponsefrom.modelsQimportQAuthor

defQauthor_list(request):QQQQtQ=Qtemplate.loader.get_template("authors/index.html")QQQQcQ=Qtemplate.Context({"authors"Q:QAuthor.objects.all()})QQQQhtmlQ=Qt.render(c)QQQQreturnQHttpResponse(html)

fromQdjango.shortcutsQimportQrender,Qget_object_or_404fromQ.modelsQimportQAuthor

defQauthor_detail(request,Qauthor_id):QQQQauthorQ=Qget_object_or_404(Author,Qid=author_id)QQQQreturnQrender(request,Q'author_detail.html',Q{'author':Qauthor})

12

django.shortcuts.get_object_or_404

fromQdjango.shortcutsQimportQrenderfromQdjango.httpQimportQHttp404fromQ.modelsQimportQAuthor

defQauthor_detail(request,Qauthor_id):QQQQtry:QQQQQQQQauthorQ=QAuthor.objects.get(id=author_id)QQQQexceptQAuthor.DoesNotExist:QQQQQQQQraiseQHttp404()QQQQreturnQrender(request,Q'author_detail.html',Q{'author':Qauthor})

Page 32: Introduction to Django - OSCON 2012 - Cdn.

Templates

13

•A view describes what’s on a page; a template describes how it looks.

•Django’s not really MVC: it’s MTV (Model-View-Template); this more closely matches the real division of roles in a typical web project.

•Django’s template language is designed primarily for front-end developers; It’s not a real programming language, but instead designed to strike a balance between power and ease of use.

•Django’s templates are optional; they can easily be replaced (or not used at all).

<!DOCTYPEQHTMLQPUBLICQ"6//W3C//DTDQHTMLQ4.01//EN"><htmlQlang="en"><head><title>Authors</title></head><body>

<h1>AuthorsQ({{Qauthors|lengthQ}}Qtotal)</h1><ul>

{%QforQaQinQauthorsQ%}<li>

<aQhref="{{Qa.idQ}}/">{{Qa.nameQ}}</a></li>

{%QendforQ%}</ul>

</body></html>

14

What’s a template?

Page 33: Introduction to Django - OSCON 2012 - Cdn.

Where do templates go?

15

• In an app’s templates directory.

• In directories specified by settings.TEMPLATE_DIRS.

TEMPLATE_DIRSQ=Q[

QQQQ'/Users/jacob/Revsys/Training/mysite.com/templates/',

]

<!DOCTYPEQHTMLQPUBLICQ"6//W3C//DTDQHTMLQ4.01//EN"><htmlQlang="en"><head><title>Authors</title></head><body>

<h1>AuthorsQ({{Qauthors|lengthQ}}Qtotal)</h1><ul>

{%QforQaQinQauthorsQ%}<li>

<aQhref="{{"a.id"}}/">{{"a.name"}}</a></li>

{%QendforQ%}</ul>

</body></html>

16

Variables

Page 34: Introduction to Django - OSCON 2012 - Cdn.

•{{Qa.nameQ}} could mean:•a["name"]

•a.name

•a.name()

The magic dot

17

<!DOCTYPEQHTMLQPUBLICQ"6//W3C//DTDQHTMLQ4.01//EN"><htmlQlang="en"><head><title>Authors</title></head><body>

<h1>AuthorsQ({{"authors|length"}}Qtotal)</h1><ul>

{%QforQaQinQauthorsQ%}<li>

<aQhref="{{Qa.idQ}}/">{{Qa.nameQ}}</a></li>

{%QendforQ%}</ul>

</body></html>

18

Filters

Page 35: Introduction to Django - OSCON 2012 - Cdn.

Filters• Data comes in one side and out the other.

(think Unix pipes.)

• Some filters take no arguments:

{{Qauthors|lengthQ}}

• Some filters take arguments:

{{Qentry.body|truncatewords:"30"Q}}

• Filters can be chained:

{{Qentry.body|truncatewords:"30"|upperQ}}

• Built-in filters: http://django.me/filters19

<!DOCTYPEQHTMLQPUBLICQ"6//W3C//DTDQHTMLQ4.01//EN"><htmlQlang="en"><head><title>Authors</title></head><body>

<h1>AuthorsQ({{Qauthors|lengthQ}}Qtotal)</h1><ul>

{%"for"a"in"authors"%}<li>

<aQhref="{{Qa.idQ}}/">{{Qa.nameQ}}</a></li>

{%"endfor"%}</ul>

</body></html>

20

Tags

Page 36: Introduction to Django - OSCON 2012 - Cdn.

Tags• Do... more complicated things.• Control flow:

{%QforQxQinQcsQ%}Q...Q{%QendforQ%}

{%QifQyQ>Q10Q%}Q...Q{%QendifQ%}

• Mangle data:

{%QwithQx.y.zQasQzQ%}Q...Q{%QendwithQ%}

{%QregroupQpeopleQbyQgenderQasQgender_listQ%}

• Etc:

{%QnowQ"Y6m6d"Q%}

{%QspacelessQ%}Q...Q{%QendspacelessQ%}

• Built-in tags: http://django.me/tags21

Template inheritance

22

Page 37: Introduction to Django - OSCON 2012 - Cdn.

<!DOCTYPEQHTMLQPUBLICQ"6//W3C//DTDQHTMLQ4.01//EN"><htmlQlang="en"><head>

<title>{%"block"title"%}YABL{%"endblock"%}

</title></head><body>

<divQid="content">{%"block"content"%}{%"endblock"%}

</div><divQid="footer">

{%"block"footer"%}Copyright"blah..{%"endblock"%}</div>

</body></html>

23

“base template”

{%"extends""base.html""%}

{%"block"title"%}AuthorsQ|Q{{Qblock.superQ}}

{%QendblockQ%}

{%"block"content"%}<h1>AuthorsQ({{Qauthors|lengthQ}}Qtotal)</h1><ul>

{%QforQaQinQauthorsQ%}<li>

<aQhref="{{Qa.idQ}}/">{{Qa.nameQ}}</a></li>

{%QendforQ%}</ul>

{%QendblockQ%}

24

“child template”

Page 38: Introduction to Django - OSCON 2012 - Cdn.

25

section_index.html

{% extends "base_generic.html" %}

{% block title %}

  {{ section.title }}

{% endblock %}

{% block content %}

  <h2>{{ section.title }}</h2>

  {% for story in story_list %}

    <h3>{{ story.headline }}</h3>

    <p>{{ story.tease }}

  {% endfor %}

{% endblock %}

base_generic.html

{% extends "base.html" %}

{% block title %}

  LJWorld.com

{% endblock %}

{% block rail %}

  <ul>

    <li>Home</li>

    <li>Local news</li>

    ...

  </ul>

{% endblock %}

base.html

<html>

<head>

  <title>

    {% block title %}{% endblock %}

  </title>

</head>

<body>

  <div id="rail">

    {% block rail %}{% endblock %}

  </div>

  <div id="content">

    {% block content %}{% endblock %}

  </div>

</body>

</html>

➀ ➁

sports/base.html base.htmlsports/section.html

{%QextendsQ"sports/base.html"Q%}

Inheritance tips•{%QextendsQ%} must be the first thing in your

template.

•More {%QblockQ%}s are better.

• If you’re duplicating content, you’re missing a block.

• If you need it, you there’s {%QincludeQ%}… but usually you don’t need it.

•Use {{Qblock.superQ}} to get at the parent’s content.

26

Page 39: Introduction to Django - OSCON 2012 - Cdn.

Documentationhttp://django.me/templates

27

Exercise 3

28