552
dm H H H H B H i |''дь< .;io>

Головатый А., Каплан-Мосс Дж. - Подробное руководство (2-е издание)(High Tech) - 2010

Embed Size (px)

DESCRIPTION

Эта книга посвящена Django 1.1 - последней версии фреймворка для разработки веб-приложений, который позволяет создавать и поддерживать сложные и высококачественные веб-ресурсы с минимальными усилиями. Django - это тот инструмент, который превращает работу в увлекательный творческий процесс, сводя рутину к минимуму. Данный фреймворк предоставляет общеупотребительные шаблоны веб-разработки высокого уровня абстракции, инструменты для быстрого выполнения часто встречающихся задач программирования и четкие соглашения о способах решения проблем.

Citation preview

dmH H H H B Hi

|''

The Definitive Guide to

Dj angoSecond Edition

Adrian Holovaty, Jacob Kaplan-Moss

Apress*

H I G H

T E C H

Django

, -

Caubu- Tlemej)^jf)i 2 0 W

High tech

, -

Django. , 2- . . . . 27. . 20. . .

., - . Django. , 2- . - . . - .: , 2010. - 560 ., . ISBN 978-5-93286-187-5 Django 1.1 - -, - . Django - , , . - , . Django , . Django - , PDF RSS, , . , Python -.

ISBN 978-5-93286-187-5 ISBN 978-1-4302-1936-1 ()

-, 2010 Authorized translation of the English edition 2009 Apress Inc. This translation is published and sold by permission of Apress Inc., the owner of all rights to publish and sell the same. , . , , .

-. 199034, -, 16 , 7, . (812) 324-5353, www.symbol.ru. N 000054 25.12.98. 29.04.2010. 70x100 l/ie. . 35 . . 1500 . 217 199034, -, 9 , 12.

Django

................................................................................................. 13 ..................................................................................................... 14 ........................................................................................................ 15 I. ................................................................................ 17 1. D jango................................................................................... 19 -?...................................................................... 19 .............................................................. 22 Django....................................................................... 24 ............................................................................... 25 ..............................................................................27 ?...............................................................................................27 2. ................................................................................ 28 P y th o n .................................................................................... 28 D jango.................................................................................... 29 Django................................................................... 32 ..........................................................................33 ......................................................................................35 ?...............................................................................................38 3. URL..................................... 39 , Django: Hello W o rld ......................... 39 Django .......................................................... 47 : .......................... 48 URL .......................................... 51 : URL-.......................... 51 Django...............56 ?...............................................................................................59 4. .................................................................................................... 60 .................................................61 ....................................................... 62 .................................................. 72 ......................................................................79

8

...................................... 81 .................................................................................. 82 ......................................................................... 89 ?.............................................................................................. 93 5. ...................................................................................................... 94 ...........................................................95 MTV ( )..........................................96 ......................................................................... 97 .................................................................... 100 Python............................................ 102 ........................................................................ 103 ................................................................................. 105 .................................................................... 108 .............................109 ............................................................ 112 ................................................................................. 113 ................................................................................119 ?............................................................................................120 6. D jan g o ....................................... 121 django.contrib......................................................................... 122 ................................... 122 ......................................123 .......128 .................................. 129 .................................................... 130 .......................................................................132 ModelAdmin.................................................... 133 , ............................................... 142 ..........................................................144 ?............................................................................................146 7. .....................................................................................................147 ............................................ 147 .................................................... 150 ........................... 154 ...................................................................156 .................................................... 158 .................................................................... 163 ?............................................................................................172

9

II. .............................................. 173 8. URL........................................................................... 175 URL: ............................................175 U RL............................................194 ?............................................................................................ 197 9. .................................................. 198 ..........................................................................198 RequestContext .......................199 H TM L............................................205 - ................................................208 .........................................................209 ................................................... 221 ...................................................... 223 ?............................................................................................ 223 10. ................................................... 224 ............................................................................... 224 .......................................................... 226 ............................................................................................. 230 .......................................................................................233 SQL-.....................................................234 ?............................................................................................ 235 11. .......................................................... 236 ....................................237 .............................................. 238 .........................................240 ?............................................................................................ 246 12. D jango......................................................................247 ......................................................................247 .......................... 250 DJANGOSETTINGSM ODULE.................................. 252 Django Apache m od_python............253 Django FastCGI..................................... 258 ..................................................................................264 ................................................... 270 ?............................................................................................ 271

10

III. D ja n g o ..........................................................273 13. , HTML...... 275 : MIME..............................................275 CSV..........................................................276 PD F.......................................................278 .................................................................... . 280 ..................................................281 ............................................................................................. 288 ?............................................................................................293 14. , ........................................ 294 Cookies..................................................................................................... 294 D jango............................................................. 298 ......................................................304 , .................................................... 316 ?............................................................................................318 15. ...................................................................................... 319 ....................................................................................320 ............................................................ 324 ........................................... 325 ................................................... 327 API ..................................................328 ......................................................................... 330 Vary...................................................................................... 330 : ..............................................332 ............................................................................334 MIDDLEW ARECLASSES.................................... 334 ?............................................................................................334 16. d jan g o .c o n trib .......................................................................................335 Django........................................................ 335 ...................................................................................................... 337 ................................................................................ 343 .......................................................................................347 CSRF............................................................................ 349 .................................................................... 352 ................................................................................ 353 ?............................................................................................353 17. ....................................................... 354 ?........................................... 355 .........................................356 ..............................................356

11

........................................359 ?............................................................................................ 362 18. ................................................................................ 363 .................................. 363 ......................................... 365 -....................368 ?............................................................................................ 369 19. .....................................................................370 ................................................372 .........................................................378 Django ............................381 ......... 383 set_language............................................................... 385 JavaS cript..........................................................................385 , g e tte x t.......................388 gettext Windows..............................................................................388 ?.......................................................................................... 389 20. ....................................................................................... 390 ..............................................................................390 SQL................. ..................................................................... 391 (XSS).......................................................... 393 HTTP-.....................................................................395 ....................................................................... 395 ...................................... 397 .................................................................................... 398 ...................................................... 399 .............................................. 400 ?............................................................................................ 400 IV. ...........................................................................................401 A. ................................................................... 403 ......................................................................................................... 403 ....................................................... 410 ............................................................................................. 415 ..............................................................................418 B. API ................................. 422 ................................................................................ 423 .....................................................425 ..................................................................................426 QuerySet .....................................................427

12

...........................................................................427 ..................................................................................... 436 Q-.............................. 441 ...............................................................................442 ................................................................................447 ................................................................ 447 SQL ........................................................................ 448 C. .........................449 , ............449 ............................................... 450 /................. 452 .................. 456 D. .......................................................................467 ............................................................ 467 : DJANGOSETTINGSJMODULE......................................................... 469 DJANGOSETTINGSJMODULE.................................. 470 .................................................... 472 E. .....................................485 ......................................................485 ..............................................499 F. d ja n g o -a d m in ........................................................................512 ..................................................................................... 513 .......................................................................................... 513 ...................................................................524 ...................................................................525 G. ................................................................ 526 H ttpR equest................................................................................526 HttpResponse...............................................................................532 ......................................................................... 537

Django. , Django Book! , Django. - , Django 1.0. 1.0, , , , , . , Django 1.1, - . , , http://djangobook.com/ , . . , ! , Django

(A drian Holovaty) - Django. - EveryBlock. , . - (Jacob Kaplan-Moss) - Django. Revolution System s, . Lawrence Journal-W orld, , , Django. Ellington, .

(Sean Legassick) 15 . Chisimba . MobGeo, . .

, , Apress .

- - . HTML-; . , , , , . NCSA ( , Mosaic) , - , HTML. , Common Gateway Interface, CGI ( ), . , CGI: HTML- , , . CGI -. CGI . CGI- , , . , . . (ASP, JS P . .). : - HTML. HTML . . , , . , , , .

16

, Django Ruby on R ails, . - : - . Django . , , . Django , , , . - , . Django , . , , Django -. , . , , , , . . , http://djangobook.com/ , . . , [email protected]. ! , , , Django , .

I

1

Django Django - -, - . Django, . - - , , . Django - -, . - , . Django . - Django. . -, , Django -. , , , , : ?. , -, .

-?Django - - . ?

20

1. Django

- , Python . : , , , . (, , , , . - , , , -.) - Python - Common Gateway Interface (CGI), 1998 . , , : Python, HTML, - .cgi1 . . CGI- Python, . , , 2:#!/usr/bin/env python import MySQLdb print print print print print "Content-Type: text/html\n" "KHHrH " " "

  • connection = MySQLdb.connect(user=me, passwd=letmein', db=my_db) cursor = connection.cursor() cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10") for row in cursor.fetchall(): print "

  • %s

% row[0] print "

1

.cg i, cgi-bin chmod + . - , , - . - .

. .2 , , UTF-8, ( ) :*# -*- coding, utf-8 . . .

-?print "" connection.close()

21

, CGI, Content-Type, - . HTML-, , , . , HTML- . HTML-, . , . - , , . , - . : .cgi, - . . . , ? , , , CGI. . ContentType ? . - .

, ? , . -, Python, ? - . - - HTML-, , . -. , , . , , Django .

22

1. Django

MVC , . , , Django. , , Python- (models., views., urls.py) HTML- (latest_books. html):# models. ( )from django.db import models

class Book(models.Model): name = models.CharField(max_length=50) pub_date = models.DateField() # views. (-) from django.shortcuts import render_to_response from models import Bookdef latest_books(request):

book_list = Book.objects.order_by(-pub_date')[:10] return rendcr_to_response(latest_books.html, {book_list: book_list}) # urls.py ( URL) from django.conf.urls.defaults import * import views urlpatterns = patternsC', (r~latest/$, views. latest_books),

)it latest_books.html () KHH /t itlex/head>

KHnrn

  • {% for book in book_list %}
  • {{ book.name }}

{% endfor %}

He ; - . - . models, , Python. . , ,

MVC

23

, Python SQL-. views. - . latest_books() . u r ls . , URL, . URL, /latest/, latest_books(). , example.com, URL http://example.com/latest/ latest_books(). latest_books.html - HTML-, . , , {%for book inbook_list %}.

1 -- (Model-View-Controller - ). , - , () (), , , (). ( 5.) , . -, Django, , . , URL , . HTML , Python. - , . . 3 , 4 - , 5 - .

1

, Django (View), Django (Template). - Django - (). - . . .

24

1. Django

Django , Django. , , , , . , Django, , Django , . - , , CGI-. - : 1. - . 2. - . 3. , - . 4. , . 5. 2 -4 . 6. , . Django! Django , - , , . 2003 , , Lawrence JournalWorld, (A drian Holovaty) (Simon W illison), Python. World Online, , , , . ( ) , , LJW orld.com, Lawrence.com KUsports.com , , . - . , -, , - . 2005 , , W orld Online, , - (Jacob Kaplan-Moss), .

25

2005 Django (Django R einhardt). , , Django , . World Online ( ) - , . , . - Django. Django , (, , 6), , Amazon.com, C raigslist The W ashington Post, , . - Django , . ( - .) , , - Django . Django , , , -, - - . Django . , , , Django , , , . , . ( , .)

, , , . , - Django, , , , Django. ( , , .)

26

1. Django

1 12 . Django; , , . 1-7 , 8-11 Django, 12 . , 13 20, Django - . . , http:// www.djangoproject.com/ , Django.

: (, if, while, for), (, / ), , . -, , , . , , -.

Python Django - , Python. Django Python, . , Django : Python Django. Python, Django . Django ( , ). Django API, . Python, . , - ! Python, , . Python, http://docs.python.org/tut/.

27

(Mark Pilgrim ) Dive Into Python (Apress, 2004)1, http://www.diveintopython.org/ Apress.

Django Django 1.1. Django . , , Django 1.1, 1.2, 1.3, 1.9 , 1.. 2.0 , , ; , 2.0 . , 1.0 . ( Python: , Python 2.0, Python 2.6, Python 3.0.) Django 1.1, .

Django - . Django - , , , - . Django - , . http://www.djangoproject.eom/r/django-users. IRC- Django - , . , #django IRC- Freenode.

? Django, .

1

: http://ru.diveinto-

python.org/toc.htmL - . . .

2 - , Django . , , . Django Python, , , ! Django , / . ( 12) , Django .

Python Django Python, Python.

Python Django Python 2.3 2.6 , () 2.4 2.6. , P ython , , 2.x, 2.6. Django 2.3 2.6, Python , . , ,

Django

29

Django, Python , 2.3, , , .

Django Python 3.0 Python 3.0, Django . , Python 3.0, , , , Python, . Python , 2.x 3.x, - Python 2.x.

Linux Mac OS X, , , Python . ( OS X - //) python. ( ), , Python :Python 2.4.1 (#2, 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin Type "help, copyright", "credits or "license for more information.

> Python. ; http://www.python.org/download/.

Django Django: (trunk). , . , Django , , , , Django? , . , ,

30

2.

.

1.0.3 1.1, http://www. djangoproject.com/download/. Linux, Django, . . , . , : Django-1.0.2-final.tar.gz. ( , ; Django .) setup, , Python-. UNIX-: 1. tar xzvf Django-1.0.2-final.tar.gz 2. cd Django-* 3. sudo python setup.py in s ta ll tar.gz- Windows 7-Zip (http://www.djangoproject.eom/r/7zip/). , , , Django-: python setu p . in s ta ll , , , Django site-packages Python - Python . /usr/lib/python2.4/sitepackages.

Django, , Subversion Django. , Django . Subversion - . Django Django. , - Subversion.

Django

31

Django , , Django. , , . , , Django , . Django, : 1. , Subversion. http://subversion.tigris.org/, http://svnbook.redbean.com/. , OS X 10.5 , - Subversion . , svn --version . 2. , svn http://code.djangoproject.com/svn/django/trunk djtrunk.

3. Python site-packages; /usr/lib/thon2.4/site-packages. , :python - import sys, pprint; pprint.pprint(sys.path)

, , site-packages. site-packages django.pth dj trunk. , :/home/me/code/dj t runk

4. djtrunk/django/bin PATH. , djangoadmin.py.

---------------------------------------------------------------------------------------------------------------

pth-, http://www.djangoproject.eom/r/python/site-module/.

Subversion , python setup. - !

32

2.

Django , . , svn update, djtrunk. Subversion http://code.djangoproject. , , - , , . . , , , . , . ( ). , svn info, dj trunk, , Revision. Django, , , -. Django : Django [- ].

Django , , . , - , django, Python, python. , django: > import django > django.VERSION (1, 1, 0, 'final* , 1)

Python - , Python. , python. Python. >, . , .

33

, , (...), : > print .. ... , ... ... , . > def my_function(value): print value > my_function( ')

Python, . , . , .

- Django, - Python. , , - , . Django, , , . Django : PostgreSQL (http://www.postgresql.org/) SQLite 3 (http://www.sqlite.org/) MySQL (http://www.mysql.com/) Oracle (http://www.oracle.com/)

Django. ( , PostgreSQL.) - , PostgreSQL, , , .

34

2.

. 1. -, . , . ( , , , .) 2. -, Python . , Python . , . Django , SQLite. , Python 2.5 . , Python 2.5 . Windows . , Python 2.5 SQLite.

Django PostgreSQL PostgreSQL psycopg psycopg2 http://www.djangoproject.eom/r/python-pgsql/ . psycopg2, , . , - 1 2, . PostgreSQL Windows, http://www.djangoproject.eom/r/python-pgsql/windows/ psycopg. Linux , python-psycopg2, psycopg2-python, thon-postgresql - .

Django SQLite 3 P ython 2.5 , , ; , Python SQLite. . Python 2.4 SQLite 3 - 2 - http://www.djangoproject.eom/r/sqlite/ pysqlite http://www.djangoproject.eom/r/python~ sqlite/. pysqlite 2.0.3.

35

Windows ( SQLite), pysqlite. Linux , python-sqlite3, sqlite-python, pysqlite .

Django MySQL Django MySQL 4.0 . 3.x SQL. , MySQLdb http:// www.djangoproject.com/r/python-mysql/. Linux , python-mysql, python-mysqldb, pysqlite, mysql-python .

Django OracleDjango Oracle Database Server 9i . Oracle cx_0racle http://cx-oracle.sourceforge.net/. 4.3.1 , 5.0, .

Django , Django . . , , Django, , , , . ( , , .)

Python, Django () , Django. . Django, , . Django - . , , , /home/username/djcode/.

36

2.

? , , , ( , /var/www). Django . Python - , . . , . django-admin.py startproject mysite. mysite . ---------------------------------------------------------------------------------------------------- Django setup, , django-admin.py . djtrunk/django/bin. django-admin.py , . UNIX /us/ local/bin sudo In -s /path/to/django/bin/django-admin. py /usr/local/bin/django-admin.py. Windows PATH. Django , Linux, django-admin.py django-admin.

django-admin.py startproject perm ission denied, . , django-admin.py (, cd /usr/local/bin), chmod + django-admin.py.

mysite/

startproject

:

__init__ . manage. settings. urls.

: __init__ .:

, Python mysite ( P ython-). , , , .

37

manage.: Django. , , python manage.. , . settings.: Django. , , . urls.py: URL- Django. . .

, Django.

, , Django , . Django - -, . Django , , (, Apache) , . , . , (cd mysite), , :python manage. runserver

:Validating models.. . errors found. Django version 1.0, using settings 'mysite.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with C0NTR0L-C.

, 8000 . URL http://127.0.0.1:8000/ . Welcome to Django . ! , . , , .

38

2.

. , 12, Django.

runserver 8000 . , :python manage. runserver 8080

IP -, . , . 1- 0.0.0 0 :python manage. runserver 0.0.0.0:8000

Django-, IP - (, http://192.168.1.103:8000/). , . UNIX ifconfig, Windows - ipconfig.

?, , Django -.

3

URL , Django . - Django.

, Django: Hello World -, Hello world. -, Hello world , hello.html - -. , : ( Hello world) URL (http://www.example.com/hello. htm l , , http://www.example.com /files/hello.htm l, ). Django , -. , a URL URL. .

mysite, django-admin.py , views.. Python , . , views. - , Django , , views., , , , .

40

3. URL

Hello world . , views.:from django.http import HttpResponse def he1lo(request): return HttpResponse("Hello world)

. HttpResponse, django.http. , . hello. , request. , -, ; django.http. HttpRequest. request, . , , Django - . hello , , hello_wonderful_beautiful_world -. , Django . : HttpResponse, Hello world.

, - Python, HttpRequest HttpResponse. Python , . ( , .)

URL python manage. runserver, Welcome to Django Hello world. , mysite hello; Django, URL . ( HTML-, , .) URL, Django URL.

, Django: Hello World

41

, URL - -, Django. , URL , URL. Django: URL , - . , URL /foo/ foo_view(), Python- views, . django-admin.py startproject URL: urls. . :from django.conf.urls.defaults import *tt tt : tt from django.contrib import admin tt admin.autodiscover()

urlpatterns = patternsC, tt : tt (r* "mysite/' , include(mysite. foo. urls )),tt tt tt tt

admin/doc 'django.contrib.admindocs' INSTALLED_APPS : ('~admin/doc/, include( django.contrib.admindocs. urls' )), '

tt tt : tt ("admin/', include(admin. site, urls)) ,

) URL Django , . , URL :from django.conf.urls.defaults import * urlpatterns = patternsC',

) : django.conf. urls.defaults URL. , patterns. patterns, urlpatterns. patterns - . (

42

3. URL

, 8.) - urlpatterns, Django URL. URL . URL , Django - . ---------------------------------------------------------------------------------------------------- Django Welcome to Django . URL , Django , , .

URL URL, , URL- . hello:from django.conf.urls.defaults import * from mysite.views import hello urlpatterns = patternsC, ('~hello/$, hello),

) ---------------------------------------------------------------------------------------------------- . , , .

: -, hello , , - mysite/views.py, , P ython, mysite. views. ( , mysite/views.py , Python ; . .) urlpatterns (~hello/$\ hello). URL. Python, - ( , ), - , .

Django, URL /hello/ hello.

, Django: Hello World

43

Python Python - , Python , import. , Python: [", /usr/lib/python2.4/ site-packages , /home/username/djcode] . from foo import bar Python foo. . ( - , .) P ython /usr/lib/thon2.4/site-packages/foo.. , /home/username/djcode/ foo py. , , Python ImportError. , Python, Python :>>> import sys >>> print sys.path

- Python Django . ( Python - manage, .) URL, . URL /hello/, . . Django URL URL. . ( , , , , URL . 8.) (") ($). : , , - . . "'hello/ ( ), URL, /hello/ (, /hello/foo /hello/bar,

44

3. URL

/hello/). , (, hello/S , URL, ) hello/, , /foo/bar/hello/. hello/ , URL, hello/, , /foo/hello/bar). - , URL /hello/ . , URL , , . , URL /hello ( )? URL , URL . URL, URL , URL, . ( Django APPEND_SLASH, D.) URL- ( Django), URL True APPEND_SLASH. URL-, , URL , APPEND_SLASH False , .

, URL, : hello , . Python ( ): - , . , ? URL, Django, 2, python manage. runserver. ( , . , Python , .) http://127.0.0.1:8000/, http://127.0.0.1:8000/hello/. Hello world - . ! - Django.

, Django: Hello World

45

. URL URL , . . . () \d [A-Z] [a-z] [A-Za-z] + Z () z () z ( ) (, \d+ ) , (, \d? , ) (, \d* , ) (, \d {1,3} , )

[71+ ?

{1,3}

. http://www.djangoproject.eom/r/python/re-module/ .

404 URL URL - URL /hello/. , - URL? , Django , , http://127.0.0.1:8000/goodbye/,

46

3. URL

http://127.0.0.1:8000/hello/subdirectory/ http://127.0.0.1:8000/ ( ). Page not found ( ) (. . 3.1). Django URL, . 404. , URL , URL. , , URL 404. , , . , . Page not found , Django . , . , Django , , 404 .

Page not found )Request Method: GETRequest U RL: http://127.0.0.1:8000/

Using the URLconf defined in

1 * o /$ . ov

. u ris, Django tried these URL patterns, in this order:

The current URL, / didn't match any of these. , You're seeing this error because you have o e b u c standard 404 page.- ?ru

in your Django settings tile. Change that to F a i a * , and Django will display a

A . 3.1. Django 404

, http://127.0.0.1:8000/ 404.

Django

47

Django ; URL - . URL URL URL. URL, , , . , ''S, , :from mysite.views import hello, my_homepagc_view urlpatterns = patternsC, (~$\ my_homepage_view),tt . . .

)

Django , , Django. , , , Hello world URL- http://127.0.0.1:8000/hello/ . . python manage. runserver settings. , manage, . Django, : TEMPLATE_DIRS, DATABASE_NAME .. R00TJJRLC0NF. Django, P ython- URL . , django-admin.py startproject : settings. urls.py. settings, R00TJJRLC0NF urls.py. settings. ; :ROOTJJRLCONF = mysite.urls

mysite/urls py. URL - /hello/, - Django URL , R00T_URLC0NF. URL, , URL, . , Django , , HttpRequest. ( HttpRequest .)

48

3. URL

, HttpResponse. A Django : Python - ( -). : 1. URL /hello/. 2. Django URL, ROOTJJRLCONF. 3. Django URL URL, , URL /hello/. 4. , . 5. HttpResponse. 6. Django HttpResponse HTTP-, -. Django. : URL- URL.

: Hello world Django, -, . URL /hello/ ; HTML-. , . , , ; . Hello world, . : HttpResponse. Python, datetime, . :>>> import datetime >>> now = datetime.datetime.now() >>> now

: datetime.datetime(2008, 12, 13, 14, 9, 39, 2731) > print now 2008-12-13 14:09:39.002731

49

Django. Python. ( , Python , Django. Django, Python, Django.) Django, , datetime.datetime.nowO HttpResponse. :from django.http import HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() html = " %s. % now return HttpResponse(html)

, hello, views.. hello, views, :from django.http import HttpResponse import datetime def hello(request): return HttpResponse(Hello world) def current_datetime(request): now = datetime.datetime.now() html = "Cefi4ac %s." % now return HttpResponse(html)

---------------------------------------------------------------------------------------------------- , . , , .

, views. current_datetime. import datetime, . current_datetime datetime.datetime now.

50

3. URL

HTML- Python . %s - , %s now. now - datetime.datetime, , %s , : 2008-12-13 14:09:39.002731. HTML- 2008-12-13 14:09:39.002731..

, HTML- , , . , HttpResponse, , - , hello.

views., URL urls.py, Django , URL . URL /time/ :from django.conf.urls.defaults import * from mysite.views import hello, current_datetime urlpatterns = patterns(\ (~hello/$, hello), ("time/S, current_datetime),

) , . -, current_datetime. -, , URL, URL /time/ . ? , URL , runserver http://127.0.0.1:8000/time/ . .

Django . , Django . (- , .) , , , settings, . .

URL

51

URL , URL Django , - . , - , . , . URL Django - . Django URL , , URL , . , . , , current_datetime. URL , , /time/ / rent-time/, URL, . , - , , URL, . URL, URL, . current_datetime URL-. , , :urlpatterns = patte rns(, (~hello/$', hello), (~time/$\ current_datetime), (''another-time-page/S', current_datetime),

) URL - . .

: URL- current_datetime - , URL- (/time/) . - URL ,

52

3. URL

. , - URL (, /books/243/ /books/81196/). , . - , /time/plus/1/ , , /time/plus/2/ - , , /time/plus// - , , . . , , . URL:urlpatterns = patte rns(, (~time/$\ current_datetime), (~time/plus/1/$' one_hour_ahead), , (~time/plus/2/$, two_hours_ahead), ( ~time/plus/3/$, three_hours_ahead), ' (~time/plus/4/$, four_hours_ahead),

) , . , : - , , . , URL , . - .

URL- - - , Java, - - /time/plus?hours=3, hours URL- ( ?). Django ( , , 8), Django , URL- . URL /time/ plus// , - , , . URL - -. URL Django URL- , , .

: URL-

53

, ? , URL (wildcard U R Lpatterns). , URL - , \d+:urlpatterns = patte rns(.

U ...('~time/plus/\d+/$. hours_ahead),

# ... ) ( tt ... , URL, .) URL URL /time/plus/2/, /time/ plus/25/ /time/plus//. 99 . , . \d{1,2}:(r~time/plus/\d{1,2}/$, hours_ahead),

---------------------------------------------------------------------------------------------------- - , . , 99 .

. Python, r -, . ; , \ , . , Python , \ : . Python , r -. URL -. , URL; - , . URL, . , URL, \d {1,2}:

54

3. URL(r~time/plus/(\d{1,2})/$', hours_ahead),

, ; (capture) , . URL :from django.conf.urls.defaults import * from mysite.views import hello, current_datetime, hours_ahead urlpatterns = patternsC', (r~hello/$, hello), (r~time/$\ current_datetime), (r*~time/plus/(\d{1,2})/$, hours_ahead),

) , hours_ahead.

URL, , . ? . , , , URL , . , , , . , , , , URL. . - , . .

hours_ahead current_datetime, : . :from django.http import Http404, HttpResponse import datetime def hours_ahead(request, offset): try: offset = int(offset)

: URL-except ValueError: raise Http404()

55

dt = datetime.datetime.now() + datetime.timedelta(hours=offset) html = 4epe3 %s %s. % (offset, dt)

return HttpResponse(html)

.

hours_ahead : request offset.request - HttpRequest, hello current_datetime. : HttpRequest. offset - , URL. , URL /time/plus// offset 3 URL /time/plus/21/ . offset 21'. ,

- , , , , , 21 . ---------------------------------------------------------------------------------------------------- , Unicode- , Python, .

offset, , , Python. , , request. ( URL , , 8.) int() offset, . int() ( , f*) , Python ValueError. ValueError django.http.Http404, , , 404 Page not found. , , ValueError, (\d{1,2}) URL , , , offset , . - , URL , . ValueError ,

56

3. URL

- . , . . . datetime.datetime.now() current_datetime, , datetime.timedelta datetime.datetime. dt. , int() offset, - datetime.timedelta , hours . HTML-, , - , current_datetime. , %s . , (offset, dt), . HttpResponse, HTML-. .

, URL, Django ( ) http://127.0.0.1:8000/time/plus/3/, , . http://127.0.0.1:8000/ tim e/plus/5/, http://127.0.0.1:8000/tim e/plus/2 4 / http://127.0.0.1:8000/tim e/plus/100/, , URL . Django Page not found - , 404 . URL http://127.0.0.1:8000/tim e/plus/ ( ) 404.

Django - , ! views, , hours_ahead:def hours_ahead(request, offset): tt try: tt offset = int(offset) tt except ValueError:

Django# raise Http404()

57

dt = datetime.datetime.now() + datetime.timedelta(hours=offset) html = "4epe3 %s %s. % (offset, dt)

return HttpResponse(html)

URL /time/plus//. , , : unsupported type for timedelta hours component: Unicode ( timedelta hours: Unicode). ? , datetime.timedelta , hours - , , offset . datetime.timedelta . , . , Django. . . : , ( unsupported type), , , , . . , Python, . () Django , , . (- ), - , . Local vars ( ), , . . Switch to -and-paste view ( -) Traceback (). , , . , -, , , IRC- Django Django. Share this traceback or. a public Web site ( -), -

58

3. URL

. , http://www.dpaste.com/. URL, . Request information ( ) -, : GET POST, cookie , , CGI. G , . Request information Settings ( ), Django. ( R00T_URLC0NF Django. D.)

Django , , . , Django. , offset = int(offset), . , print, ? Django, print. assert False, . . , hours_ahead:def hours_ahead(request, try: offset):

offset = int(offset) except ValueError: raise Http404() dt = datetime.datetime.now() + datetime.timedelta(hours=offset) assert Falsehtml = 4epe3 %s %s. % (offset, dt) return HttpResponse(html)

, , Django. . - . Django 0, . ,

?

59

12. , Django . ( ? Page not found, , .)

? , HTML Python. , , . Django , , . Django.

4, , . HTML- Python, :def current_datetime(request): now = datetime.datetime.now() html = "Cei/i4ac %s. " % now return HttpResponse(html)

, , , , , HTML- - . . Python. , , , . Python HTML - , , -, ( ). HTML/ CSS Python. , , - , , - , Python, .

Python. Django, , .

61

Django , . ( ), . HTML-, Django . . Django HTML-, , . , .

H3Bemei-me 3aKa3e

() {{ person_name }}! , {{ company }}. {{ ship_date|date:"F j, Y" }}. :

  • {% for item in item_list %}
  • {{ item }}

{% endfor %}

{% if ordered_warranty %} . {% else %} , , . {% endif %} ,
{{ company }}

, HTML-, . . , (, { person_name }}) - . , { . ? .

62

4.

( , { if ordered_warranty % - . % }) : , . for ({% for item in item_list %})HTerif ({% if ordered_warranty % }). Ter for for Python, . if, , if. , ordered_warranty True. , { if ordered_warranty % { else % , % } % }. { else % { endif % , % } % }. { else % . % } - . : { ship_date|date:F j, Y }}. { ship_date date F j, . date , . (|), UNIX.

Django , . F , , , . , 9.

, . - , Django. ( , , , - Python, , Django.) Django Python: 1. Template, . 2. renderQ Template (). , .

63

: > from django import template > t = template.Template( {{ name }}.) > = template. Context( {name: }) > print t. render(c) . > = template. Context({ name: }) > print t .render(c) .

.

Template Template . Template django.template, - . Python , . mysite, django-admin. startproject (. 2), python manage. shell, .

Python Python , , python manage, shell, python. , manage, shell : Django , . Django, , , , , . , , , . Django DJANGO_SETTINGS_MODULE, settings, . , DJANGO_SETTINGS_MODULE mysite. settings , mysite Python. python manage, shell, DJANGO_SETTINGS_MODULE. manage. shell, .

64

4.

Django, , , manage. shell DJANGO_SETTINGS_MODULE .bash_ profile - .

.> from django. template Import Template > t = Template(My name is {{ name }}.') > print t

, :

0xb7d5f24c , ( Template, ). Template , . , TemplateO TemplateSyntaxError: > from django. template import Template > t = Template({% notatag %}) Traceback (most recent call last): File ,1 line 1, in ? , django.template.TemplateSyntaxError: Invalid block tag: notatag

block tag ( ) { notatag % % }. - . TemplateSyntaxError : ( )

65

Template . . , . Django Context, django.template. - , . renderQ Template, : > from django.template import Context, Template > t = Template(' {{ name }}.') > = Context( { name : }) ' > t. render(c) u .'

, t. render(c) Unicode, Python. . Unicode Django. , , Django , , . , ; , Unicode Django , .

Python . Context , , 9.

(A-Z a-z) , , . ( - , .) . , , . > from django.template import Template, Context > raw_template = .. () {{ person_name }},

. 217

66

4. ... , {{ company }}. ... {{ ship_date|date:F j, Y }}. ... ... ... .. . {% if ordered_warranty %} . {% else %} , , . ... {% endi f %} ... > > > ,
{{ company }}.. t = Template(raw_template) import datetime = Context( {person_name : , company: Outdoor Equipment' , ship_date: datetime.date(2009, 4, 2), ordered_warranty: False}) > t .render(c) u () ,\n\n , Outdoor Equipment. \ April 2, 2009.\n\n\n , \ , .\\\ ,
0utdoor Equipment

: 1. django.template Template Context. 2. rawjtemplate. , , ; , , . 3. t, rawjtemplate Template. 4. datetime Python, . 5. Context. Context Python, . , , person_name company - , Outdoor Equipment . 6. , renderQ, . , .

67

, , ordered_warranty False. , April 2 2009 F j, , . ( date .) , Python, , , , , (\). Python: t.render(c) , , . , , print: print t.render(c). Django: , Template, Context render().

, Template . :> from django.template import Template, Context > t = Template(', {{ name }}) > print t .render(Context( { name : ''})) ' , > print t .render(Context( {name': ''})) , > print t. render(Context( {name: ''})) ,

, Template renderQ:# for name in (1, , ): t = Template(Hello, {{ name }}) print t.render(Context({'name: name})) # t = Template(Hello, {{ name }}) for name in (, ', ): print t.render(Context({name: name}))

Django . . XML, -

68

4.

XML Django.

- . , . Django (.). , , . . , , Python. , : > from django.template import Template, Context > person = {'name': Sally, age: 43} > t = Template({{ person.name }} is {{ person.age }} years old.) > = Context({person: person}) > t. render(c) u Sally is 43 years old.

. , datetime, date year, month day, Django , : > from django.template import Template, Context > import datetime > d = datetime.date(1993, 5, 2) > d.year 1993 > d.month 5 > d.day 2 > t = Template( {{ date.month }}, {{ date.year

}}') > = Context({date': d}) > t. render(c) u 5, 1993.

, : > from django.template import Template, Context > class Person(object): d e f _init__(self, first_name, last_name):

69

self.first_name, self.last_name = first_name, last_name > t = Template(, {{ person.first_name }} {{ person.last_name }}.') > = Context( { person : Person(', )}) ' > t .render(c) u, .'

. , Python upper() isdigit(), Django : > from django.template import Template, Context > t = Template({{ var }}-{{ var.upper }}-{{ var.isdigit }}) > t .render(Context( {var' : hello})) u hello-HELLO-False > t. render(Context({var: 123})) u123-123-T rue

, . , ; . ( , .) , : > from django.template import Template, Context > t = Template( 2 - {{ items. 2 }}.) > = Context({items': [1, , ]}) > t .render(c) u 2 - .

. , {{ items.-1 }} TemplateSyntaxError.

Python, Python 0. 0, - 1 . .

, : (, foo[bar]) (, foo. bar) (, foo.barQ) (, f[2])

, .

70

4.

. , {{ person.name.upper }} : (person[ name ]), - (()): > from django.template import Template, Context > person = {'name': Sally, age: 43} > t = Template({{ person.name.upper }} is {{ person.age }} years old.) > = Context({person : person}) >>> t .render(c) u SALLY is 43 years old.

, . , . , , - silent_variable_failure True. , , : > t = ( " {{ person. first_name }}.") > class PersonClass3: def first_name(self): raise AssertionError, "foo > p = PersonClass3() >>> t.render(Context({"person : p})) Traceback (most recent call last): AssertionError: foo > class SilentAssertionError(AssertionError): silent_variable_failure = True > class PersonClass4: def first_name(self) : raise SilentAssertionError > p = PersonClass4() > t. render(Context({"person : p})) u .

, . ( ). , , , , . , , BankAccount delete(). { account.delete }}, account {

71

BankAccount, ! , alters_data:def delete(self): # delete.alters_data = True

, . , } {{ account.delete } deleteO alters_data=True, deleteO . .

, , , . : > from django.template import Template, Context > t = Template( {{ name }}.') > t. render(ContextO) u' . ' > t .render(Context( {var: hello})) u' . ' > t. render(Context({'NAME: hello})) u . > t .render(Context( {Name: hello})) u .

, , . , . , - .

Context . Context , Python:>>> from django.template import Context > = Context({foo : "bar"}) > c[ foo] bar

72 > del [ foo] > [ foo] Traceback (most recent call last): KeyError: foo > c['newvariable'] = 'hello' > c['newvariable] hello'

4.

, . .

Django,

if/else { if % , True ( % } , False), , { if % {%endif % % } }, :{% if today_is_weekend %} ! {% endif %}

Python P ython Django False : ([]) (()) ({}) () (0) None False ( ) , . ( .)

True.

73

{% else % : }{% if today_is_weekend %} ! {% else %} . {% endif %}

{ if % and, or not % } , :{% if athlete_list and coach_list %} , . {% endif %} {% if not athlete_list %} . {% endif %} {% if athlete_list or coach_list %} . {% endif %} {% if not athlete_list or coach_list %} . {% endif %} {% if athlete_list and not coach_list %} . {% endif %}

and or {% if % }, . , :{% if athlete_list and coach_list or cheerleader_list %}

. , , , . { if % : % },{% if athlete_list %} {% if coach_list or cheerleader_list %} ! {% endif %} {% endif %}

, . , :{% if athlete_list or coach_list or parent_list or teacher_list %}

74

4.

{ elif % . % } { if % % }:{% if athlete_list %} : {{ athlete_list }}. {% else %} . {% if coach_list %} : {{ coach_list }}. {% endif %} {% endif %}

He {% if % } { endif % Django % }.TemplateSyntaxError.

for {% for % } . for Python: for X in Y, Y - , a X - , . {%for % { endfor % } % }. , , athleteJList:

  • {% for athlete in athlete_list %}
  • {{ athlete.name }}

{% endfor %}

reversed:{% for athlete in athlete_list reversed %} {% endfor %}

{% for % : }{% for athlete in athlete_list %} {{ athlete.name }}

  • {% for sport in athlete.sports_played %}
  • {{ sport }}

{% endfor %} {% endfor %}

, , - :

{% if athlete_list %} {% for athlete in athlete_list %} {{ athlete.name }} {% endfor %} {% else %} . . {% endif %}

75

, for { empty % % }, , , . :{% for athlete in athlete_list %} {{ athlete.name }} {% empty %} . . {% endfor %}

. , , , . continue, . (, , , .) { for % % } forloop. , : forloop.counter , . , forloop.counter 1. :{% for item in todo_list %} {{ forloop.counter }}: {{ item }} {% endfor %}

forloop.counterO forloop.counter , . 0. forloop. revcounter , . forloop. revcounter . 1. forloop. revcounterO forloop. revcounter ,

1, 0.

76

4. forloop.first - , True . :{% for object in objects %} {% if forloop. first %}{% else %}{% endif %} {{ object }} {% endfor %}

forloop.last - , True . :{% for link in links %} {{ link }} {% if not forloop.last %}

I{% endif %}{% endfor %}

:Linkl | Link2 | Link3 | Link4

- : : {% for in places %} {{ {% if not forloop.last %} {% endif %} {% endfor %}

forloop.parentloop - forloop , , :{% for country in countries %} {% for city in country.city_list %} CTpaHa #{{ forloop.parentloop.counter }} l~0 p0 A #{{ forloop.counter }} {{ city }} {% endfor %} {% endfor %}

forloop . {% endfor % forloop }, .

77

forloop {% for % } , forloop. Django forloop.parentloop. , for loop ( , ), { for % % } forloop.parentloop.

ifequal/ifnotequal Django , Python . ( . .) -, . Django {% ifequal %}.

{% ifequal % , , } , { ifequal % {%endifequal % % } }. user currentuser:{% ifequal user currentuser %} flo6po ! {% endifequal %}

, , :{% ifequal section sitenews %}

{% endifequal %} {% ifequal section community" %} C 006iuecTB0 {% endifequal %}

{% if % { ifequal % }, % } {% else % }:{% ifequal section sitenews1 %}

{% else %}

78 {% endifequal %}

4.

{% ifequal % } , , . :{% {% {% {% ifequal ifequal ifequal ifequal variable variable variable variable 1 %} 1.23 %} foo %} foo" %}

, , , , , {% ifequal % } . :{% ifequal variable True %} {% ifequal variable [1, 2, 3] %} {% ifequal variable {key: value} %}

, , {%if % {%ifequal % } }.

HTML Python, Django . {tt it}:{tt tt}

. . . , ( ): {# #} .

, {% comment % }:{% comment %} . {% endcomment %}

, . , :

{{ name|lower }}

79

{ name }}, { lower, . , . :{{ my_list|first|upper }}

. , :{{ bio|truncatewords:"30" }}

30 bio. . F. addslashes: : , , . , JavaS cript-. date: date datetime , , :{{ pub_date|date:F j , Y }}

F. length: . , - . ( Python , , , , _1__()).

, Django, , . , , , -, . , , Python. , , . ( , - Python! , , .)

80

4.

, , , Django . Django , , , - Python, . , , , Django . , Django. - World Online Django. : - . Django , , - . , . Python Django. , . , , Django Python, . H T M L /X M L . Django HTML-, , , . , XML, XML, Django . XML- . , , XML- , . , H T M L . WYSIWYG-, Dreamweaver. , , . Django , HTML- .

81

, P ython. , , , Python. , . Python. ( . 9.) . , , , , .

, . current_datetime mysite.views, . :from django.http import HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() html = CePi4ac %s. " % now return HttpResponse(html)

, Django. :from django.template import Template, Context from django.http import HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() t = TemplateC'chtmlxbody^efiMac {{ current_date }}.") html = t.render(Context({'current_date: now})) return HttpResponse(html)

, , , , . , Python, . , , . , , - - P ython , . ,

82

4.

/home/djangouser/templates/mytemplate.html, :from django.template import Template, Context from django.http import HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() tt . tt , , tt ! fp = open( /home/djangouser/templates/mytemplate.html*) t = Template(fp.read()) fp.close() html = t .render(Context({current_date: now})) return HttpResponse(html)

: , . mytemplate.html , () IOError. . , , ! . , open(), fp.read() nfp.close().

.

Django API . . API , , . settings., R00T_URLC0NF. , settings, TEMPLATE_DIRS. , :

TEMPLATE_DIRS = ( tt , , /home/html/django_templates tt C:/www/django/templates. tt , Windows, t , , t .

83

) Django, . , , TEMPLATE_DIRS:TEMPLATE_DIRS = ( /home/dj ango/mysite/templates,

) . , , -, . , , templates ( mysite, 2). TEMPLATE_DIRS , , ! :tt ! TEMPLATE_DIRS = ( /home/django/mysite/templates'

) :tt . TEMPLATE_DIRS = ( /home/dj ango/mysite/templates ,

) Python , . . Windows , :TEMPLATE_DIRS = ( C:/www/django/templates,

) ( ).

84

4.

, , Django - Python, TEM PLATE_DIRS , :import os.path TEMPLATE_DIRS = ( os.path.join(os.path.dirname(_file__) templates) , . replace(\ Y ,/ ) ,

) Python _file__, , Python-. , settings. (os.path.dirname), templates - (os.path, join), ( Windows). , , . - - Django-, , . TEMPLATE_DIRS, , . current_datetime :from django.template.loader import get_template from django.template import Context from django.http import HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() t = get_template(current_datetime.html) html = t .render(Context({current_date: now})) return HttpResponse(html)

, , django.template.loader.get_ template(). , , , Template. current_datetime.html, .html . .

85

, get_template() , TEMPLATE_DIRS, . , TEMPLATE_DIRS /home/ django/mysite/templates get_template() / ,home/django/mysite/templates/curent_datetime.html.

get_template() , TemplateDoesNotExist. , , Django python manage. runserver, . , current_datetime (, http://127.0.0.1:8000/tim e/). , DEBUG True current_datetime.html , Django, TemplateDoesNotExist (. 4.1)./ 0 0 0 . TemplateDoesNotExist at / time/ ^

currentdatetime.html

TemplateDoesNotExist at 1/Request Method: Request URL: Exception Typo: Exception Value: Exception Location: GET http'V/iocaihost:800Q/time/ TemplateDoesNotExist cufrentjdatetime.html /Users/jacob/Projects/Book/django/tempiate/loader, py in flr>dJemplate_sourcepline 72

I

j Template-loader postmortemDjango tried loading these templates, in this order: j:

: i ! _____ ..... *

Using loader django.template.looders.filesystem.load_.template_source: /Users/jacob/Projects/ftook/ch6/te from django.db import connection > cursor = connection.cursor()

, , . , . . 5.2 .

100

5.

5.2. You haven t set the DATABASE_ENGINE setting yet. ( DATABASE. ENGINE) Environm ent variable DJANGO_SETTINGS_ M D L is undefined. OUE (He DJANGO_SETTINGS_M ODULE) Error lo a d in g ______module: N o m odule n am ed ______. ( ____ : ______ ) .. (, psycopg M ySQLdb). Django, . DATABASE_ ENG INE . , ? DATABASE_ N M , A E , C EA DATABASE. R TE DATABASE_ USER, , . , DATABASE_H ST DATABASE_PO O RT , .

DATABASE_ENGINE . . 5.1.

python manage, , python.

______is n t an available database back-end. ( ____ ) D atab ase______does not ex ist ( ____ )

R o le ______does not ex ist ( ____ )

Could not connect to server (He )

, Django - , , Python . , . 2 ,

101

? , . - Django . : , , , TEMPLATE_DIRS . . - Django, , Python. Django , , . , .

, , . . , , , , , . , , . views, , URL . . : (), . , , . mysite, books:python manage. startapp books

, books mysite. , .books/ _init__. models. tests. views.

.

102

5.

models. views. . , models, . Django.

Python , Model. Django , Python. SQL- CREATE TABLE, SQL, Python, , . Django , SQL- Python, . , , SQL . , , : Python SQL? Django : . API , Django - , : Python . , , , , . -, () , , . -, . ( , , Django .) , - MySQL - . Python , , . , . SQL, Python, SQL, . , , . .

103

SQL . , URL. Django . . SQL . - Python, , CREATE TABLE MySQL, PostgreSQL SQLite.

: P ython . Django , . . , , Django . , .

18.

, , . , , SQL. , ! : , . , , , , . , ( -- ) ( -- , ).

Django - Python. models., startapp:from django.db import models class Publisher(models.Model):

104name = models.Cha rField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField()

5.

. , , , django.db.models.Model. Model , , , . , , , Django. , , - . , (, CharField) - (, varchar). , Publisher ( CREATE TABLE, PostgreSQL).CREATE TABLE books_publishern ( id serial NOT NULL PRIMARY KEY, name varchar(30) NOT NULL, address varchar(50) NOT NULL, "city varchar(60) NOT NULL, state_province varchar(30) NOT NULL, "country varchar(50) NOT NULL, "website varchar(200) NOT NULL

); Django, , CREATE TABLE . - , --. , Book authors ManyToManyField. , . Book authors. Django - -

105

--, - . . , , . , Django - id. Django .

, , . Django, books . settings, INSTALLED_APPS. Django, . :INSTALLED_APPS = ( 'django.contrib.auth, django.contrib.contenttypes, django.contrib.sessions, 'django.contrib.sites,

) , t. ( , , t .) MIDDLEWARE_CLASSES; . INSTALLED_APPS mysite.books . :MIDDLEWARE_CLASSES = ( tt django.middleware, common.CommonMiddleware, tt django.contrib.sessions.middleware.SessionMiddleware, tt django.contrib.auth.middleware.AuthenticationMiddleware,

)INSTALLED_APPS = ( tt django. contrib. auth, tt django.contrib.contenttypes, tt django.contrib. sessions, tt 'django. contrib. sites, mysite.books,

)

106

5.

, TEMPLATE_DIRS . INSTALLED_APPS, . ,

, . , . mysite.books books, . INSTALLED_APPS Python, . Django , . , :python manage. validate

validate . , 0 errors found ( 0 ). . , , . python manage. validate. . , , CREATE TABLE books ( U N I X ):python manage. sqlall books

books - , manage, startapp. :BEGIN; CREATE TABLE "books_publisher ( id serial NOT NULL PRIMARY KEY, "name" varchar(30) NOT NULL, "address" varchar(50) NOT NULL, "city varchar(60) NOT NULL, state_province varchar(30) NOT NULL, "country" varchar(50) NOT NULL, "website varchar(200) NOT NULL

)CREATE TABLE "books.author" ( "id" serial NOT NULL PRIMARY KEY, "first_name" varchar(30) NOT NULL,

"last_name varchar(40) NOT NULL, "email varchar(75) NOT NULL

107

)CREATE TABLE "books_book" ( "id serial NOT NULL PRIMARY KEY, "title varchar(IOO) NOT NULL, "publisher_id integer NOT NULL REFERENCES books_publisher ("id) DEFERRABLE INITIALLY DEFERRED, "publication_date date NOT NULL

)CREATE TABLE books_book_authors ( "id serial NOT NULL PRIMARY KEY, "book_id integer NOT NULL REFERENCES "books_book ("id) DEFERRABLE INITIALLY DEFERRED, "author_id integer NOT NULL REFERENCES "books_author ("id) DEFERRABLE INITIALLY DEFERRED, UNIQUE ("book_id, "author_id)

)CREATE INDEX "books_book_publisher_id ON "books_book (publisher_id) ; COMMIT;

: (books) , (Publisher, Book Author). , . , Django - id. . Django _id . , , , . REFERENCES. CREATE TABLE , , , auto_increment (MySQL), serial (PostgreSQL) integer primary key (SQLite), . , ( ). PostgreSQL.

sqlall , , Django , . SQL-

108

5.

UNIX (, python manage, sqlall books | psql mydb). Django - syncdb:python manage. syncdb

, :Creating table books_publisher Creating table books_author Creating table books_book Installing index for books.Book model

syncdb . , INSTALLED_APPS, , , . , syncdb , ; , syncdb, . ( .) python manage. syncdb, , books INSTALLED_APPS. , python manage. syncdb , . , , Django. (, psql PostgreSQL) python manage. dbshell, , DATABASE_SERVER. .

Django API Python. , python manage, shell : > from books.models import Publisher >>> p1 = Publisher(name=Apress, address=2855 Telegraph Avenue, city= Berkeley, state_province=CA, country^U.S.A., website=http://www.apress.com/) > p1.save() > p2 = Publisher(name=0 Reilly, address=10 Fawcett St., city=' Cambridge, state_province=MA, country^U.S.A., website='http://www.oreilly.com/') > p2.save()

> publisher_list = Publisher.objects.all() > publisher_list [, ]

109

, . . Publisher. , . Publisher, : name, address . .

, save(). Django SQL- INSERT. Publisher.objects, . Publisher.objects.all() Publisher . Django SQL SELECT.

, Django , save().1 = Publisher(...)tt 1 !

1.save()tt .

, create(). , : > 1 = Publisher.objects.create(name=Apress, address^2855 Telegraph Avenue, city=Berkeley, state_province=CA, country=U.S.A., website=http://www.apress.com/') > p2 = Publisher.objects.create(name=0'Reilly, address=10 Fawcett St., city=Cambridge, state_province=MA, country=U.S.A., website=http://www.oreilly.com/) > publisher_list = Publisher.objects.all() > publisher_list

, Django A PI , .

, Publisher :[, ]

110

5.

, Publisher _Unicode__ (). Unicode. , _Unicode__ ():from django.db import models class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() def __unicode__(self): return self.name class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() def __unicode__(self): return u %s %s % (self.first_name, self.last_name) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() def __unicode__(self): return self.title

, _Unicode__() , , . Publisher Book , Author __Unicode__ () , first_name last_name, . _Unicode__() , Unicode. - , , , Python coercing to Unicode: need strin g or buffer, in t found ( Unicode: , int). , _Unicode__(), , Python , python manage. shell. ( .) Publisher :

111

Unicode Unicode? , Python, : , , . Python , - , , ASCII, ISO-8859-1 UTF-8. ( , 128, ASCII, , , ), , , . , , , , . - , ??? ?????? . . Unicode , , Unicode. Unicode Python , , . Django Unicode . , , Unicode, Unicode, Unicode. , . , Unicode, , . http://www.joelonsoftware.com/ articles/Unicode.html

> from books.models import Publisher > publisher_list = Publisher.objects.all() > publisher_list [, ]

_Unicode__() , , Django .

112

5.

, , __unicode_() - . Django , , . _Unicode__() - : , .

, . , , , : > = Publisher(name=Apress, address=2855 Telegraph Ave., city=Berkeley, state_province=CA, country=U.S.A., website=http://www.apress.com/)

. , save(): > p.save()

SQL :INSERT INTO books_publisher (name, address, city, state_province, country, website) VALUES (Apress, 2855 Telegraph Ave., Berkeley, CA, U.S.A., http://www.apress.com/) ;

Publisher id, save() : , id :> p. id 52 tt

save() ( SQL- UPDATE, INSERT): > p.name = Apress Publishing > p.save()

saveQ SQL-:UPDATE books_publisher SET name = Apress Publishing, address = 2855 Telegraph Ave., city = Berkeley, state_province = CA, country = U.S.A.,

website = http://www.apress.com WHERE id = 52;

113

, , , . . , ( ) , . :UPDATE books_publisher SET name = Apress Publishing WHERE id=52;

, , , , , - , . , : > Publisher.objects.all() [/Publisher: Apress>, ]

SQL-:SELECT id, name, address, city, state_province, country, website FROM books_publisher;

-------------------------------------------------------------------------- Django SELECT *, . : SELECT * , ( ) Python: . Python , import this .1

Publisher.objects.all() . -, Publisher. : , . objects, . 10. , , - .

1

Python http://ru.wikipedia.org/wiki/Python. - . . .

114

5.

objects; . , 11(). objects, . , QuerySet . Query Set . , , , .

, .

, ; , - . Django API filterQ: > Publisher, objects, fi 1te(name= Apress) []

filterQ , WHERE SQL- SELECT, :SELECT id, name, address, city, state_province, country, website FROM books_publisher WHERE name = Apress;

, : > Publisher.objects.filter(country=U.S.., state_province=CA) [/Publisher: Apress>]

WHERE AND. , :SELECT id, name, address, city, state_province, country, website FROM books_publisher WHERE country = U.S.A. AND state_province = CA;

, SQL =, . : > Publisher.objects.filter(name_contains=press) []

115

name contains . Django, Python, , - _contains SQL- LIKE:SELECT id, name, address, city, state_province, country, website FROM books_publisher WHERE name LIKE *%press%;

, icontains (LIKE ), startswith (), endswith () range ( SQL BETWEEN). .

filterQ QuerySet, . . get() : > Publisher.objects.get(name=Apress)

(, QuerySet) . , , : > Publisher.objects.get(country=U. S. A. ) Traceback (most recent call last): MultipleObjectsReturned: get() returned more than one Publisher -it returned 2! Lookup parameters were {country: U.S.A.}

, , : > Publisher.objects.get(name=Penguin") Traceback (most recent call last): DoesNotExist: Publisher matching query does not exist.

DoesNotExist : Publisher. DoesNotExist. :try: = Publisher.objects.get(name=Apress) except Publisher.DoesNotExist: print Apress . else: print "Apress .

116

5.

, , . , ; , , , . Django , , - , , . order_by(): > Publisher.objects.order_by("name") [/Publisher: Apress>, ]

all() , SQL- :SELECT id, name, address, city, state_province, country, website FROM books_publisher ORDER BY name;

: > Publisher.objects.order_by(address) [/Publisher: O Reilly>, ] > Publisher.objects.order_by(state_provinee) [/Publisher: Apress>, ]

( , ), : > Publisher.objects.order_by(state_province, address) [/Publisher: Apress>, ]

, > Publisher.objects.order_by(-name) [/Publisher: 0 Rei1ly>, ]

, order_by() . , - . Django :class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField()

def _Unicode __(self): return self.name class Meta: ordering = [* name]

117

: class Meta. , Publisher ( , Publisher, ). Meta . Meta , ordering. Django, order_by(), Publisher, API , name.

, . . : > Publisher.objects.filter(country=U.S..").order_by("-name) [ Publisher.objects.order_by(-name)[0]

, save() . . , , Publisher, Apress Apress Publishing save() . :> = Publisher.objects.get(name=Apress) > p. name = Apress Publishing > p. save()

S Q L -:SELECT id, name, address, city, state_province, country, website FROM books_publisher WHERE name = Apress; UPDATE books_publisher SET name = 'Apress Publishing, address = 2855 Telegraph Ave., city = Berkeley, state_province = CA, country = U.S.A., website = http://www.apress.com WHERE id = 52;

--------------------------------------------------------------------- , (id) Apress 52.

119

, saveQ , name. - , , . updateQ QuerySet, : > Publisher.objects.filte(id=52).update(name=Apress Publishing)

SQL-, :UPDATE books_publisher SET name = Apress Publishing WHERE id = 52;

updateQ QuerySet, . , , country U.S.A. USA Publisher: > Publisher.objects.allQ.update(country=USA) 2

updateQ , . 2.

deleteQ: > = Publisher.objects.get(name="0Reilly) > p.deleteQ > Publisher.objects.al 1 () [/Publisher: Apress Publishing>]

, deleteQ QuerySet , updateQ : > Publisher.objects.filter(country=USA).delete() > Publisher.objects.all().delete() > Publisher.objects.allQ

[] ! Django 11(), . , : > Publisher.objects.deleteQ Traceback (most recent call last):

120File , line 1, in AttributeError: 'Manager' object has no attribute 'delete'

5.

, all(): > Publisher.objects.all().delete()

, 11() , : > Publisher.objects.fi1te(country='USA').delete()

? Django, , . 10 Django. . , 18 Django . , 7, , , . , - . Django, .

6 Django - -. -, , . : , ; , ; , - , . . , , - , . , , . . , . Django , ? - . Django, , . Django. , . , , . , Django , , Django .

122

. Django

django.contrib Django - , django.contrib. . django.contrib Python - , - . Django, . - django. contrib, ; , django.contrib.admin. django.contrib (django.contrib.auth), (django.contrib.sessions) (django.contrib.comments). Django , django.contrib, 16. , Django , django.contrib.

Django , . , . : 1. django.contrib.admin' INSTALLED_APPS. ( INSTALLED_APPS , , .) 2. , INSTALLED_APPS django.contrib.auth', django.contrib.contenttypes django.contrib.sessions'. Django. ( , 5. .) 3. , MIDDLEWARE_CLASSES django.middleware.common.CommonMiddleware , django.contrib.sessions.middleware. SessionMiddleware' django. contrib. auth. middleware. AuthenticationMiddleware ( 5 , .

.)

123

python manage. syncdb. , . INSTALLED_APPS django.contrib.auth syncdb , . , python manage. createsuperuser , . (: python manage. createsuperuser , INSTALLED_APPS django.contrib.auth) . URL URL (, urls.py). urls.py, django-admin.py startproject, , . , :# ... from django.contrib import admin admin.autodiscover()tt URL.. .

urlpatterns = patterns(\

# ...(r*"admin/1, include(admin.site.urls)),tt ...

) , Django . ( python manage, runserver, ) http://127.0.0.1:8000/a d m in/.

, , . . (. 6.1). , . , , , - python manage, createsuperuser.

(. 6.2). , -

124

. Django

. 6.1.

Go le ogDjango administrationSite administrationRA*'?s > Jsv?* S e le c t u s e r to ch an ge ^ ^ T .S e a a rrt ; Coi - mail address admta3pexatnple.c0m Tint nam last nam Stiff status

Weltorrw, *dmtn, O un $ p*ivord / 109 out

41ftftivr, Q :Q Username vadmin

0 1 1 1 1 By sta ff sU U i* I All YHO

;^ :

By su p eru ser statu * I uicr 1 ** Ye*

By activeYei

. 6.3.

Django administrationH n ' > u h >UfO > o * A t iik

lAwcom*, *dmln. Ouna password / I09 out

Change userUsrtwm; admin

1

tv . ?.? >joK V t i t i n g k feauworti fo r m

First name.L a st nam e:

t-i Staff status 3tsi'.*v v^tn-e ?* http://www.djangoproject.com/documentation/ weekly 0.5 http://www.djangoproject.com/documentation/0_90/ never 0.1

. http://www.sitemaps.org/.

289

Django X M L , Python. , Sitemap- U R L .

sitem ap, : 1. django.contrib.sitemaps INSTALLED_APPS. 2. , TEM TE_LO DERS PLA A django.template.loaders.app_directories.load_template_source. , , . 3. , (. 16). ---------------------------------------------------------------------------------------------------- sitemap . INSTALLED_APPS , load_template_source .

Django-, U R L :('"sitemap\.xml$, 'django.contrib.sitemaps.views.sitemap, {'sitemaps': sitemaps})

D ja n g o U R L /sitemap, xml. ( , sitemap, xml , .) , . U R L . , sitemap, xml , U R L . /content/sitemap.xml, U R L , /content/. {sitemaps: sitemaps}. , sitemaps - , (, blog news) Sitemap- (, BlogSitemap NewsSitemap). Sitemap (, BlogSitemap(some_var)).

290

13. , HTML

Sitemap-Sitemap- - Python, . , Sitemap- , - . sitemap, xml, , , (. ). Sitemap- django.contrib.sitemaps. Sitemap . , , Entry, - , . Sitemap-:from django.contrib.sitemaps import Sitemap from mysite.blog.models import Entry class BlogSitemap(Sitemap): changefreq = never priority = 0 . 5 def items(self): return Entry.objects.filtcr(is_draft=False) def lastmod(self, obj): return obj.pub_date

Sitemap- Feed-. . Feed-, Sitemap- , . , , . . Sitemap- : items (): . , , location(), lastmod(), changefreqO priorityQ . location (): URL . URL, , : : /foo/bar/ : example.com/foo/bar/

: http://example.com/foo/bar/ location get_absolute_url() , items().

291

lastmod (): Python datetime. changefreq (): . ( Sitemaps): 'always' 'hourly' 'daily' 'weekly' 'monthly' 'yearly' 'never'

priority (): , 0.0 1.0. 0.5; . http://www.sitemaps.org/.