Вы находитесь на странице: 1из 552

dm

|''<

.;io>

The Definitive Guide to

Dj ango
Second 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

...................................... 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

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/ ,
.
.
,
feedback@djangobook.com.
!
, , ,
Django ,
.

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"
"<html><head><title>KHHrH</title></heacl>
"<body>
"<></>
"<ul>

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 "<li>%s</li> % row[0]
print "</ul>

.cg i,
cgi-bin
chmod + <_>. -

, ,
- . - .

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

. .

-?

21

print "</body></html>"
connection.close()

, 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 Book
def 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 ()
<html><head><title>KHH /t itlex/head>

<body>
<h1>KHnrn</h1>

<ul>
{% for book in book_list %}
<li>{{ book.name }}</li>
{% endfor %}
</ul>
</body></html>

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 in
book_list %}.


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

- ,
.

. 3 , 4 -
, 5 - .

,
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,
.

: 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 Oracle
Django 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/.

2.

36

?
, , ,

( , /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.

startproject

mysite/
__init__ .
manage.
settings.
urls.

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

__init__ .:

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
-.

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,

3. URL

44

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

Z ()

[a-z]

z ()

[A-Za-z]

z ( )


(, \d+
)

[71+


(, \d? ,
)


(, \d* ,
)

{1,3}


(, \d {1,3} ,
)

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

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

3. URL

46

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: GET
Request U RL: http://127.0.0.1:8000/

Using the URLconf defined in

1. *oov/$

. 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

49

datetime.datetime(2008, 12, 13, 14, 9, 39, 2731)


> print now
2008-12-13 14:09:39.002731

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 = "<11><> %s. </body></html> % 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 = "<html><body>Cefi4ac %s.</body></html>" % now
return HttpResponse(html)

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

, views.
current_datetime.

import datetime,
.

current_datetime
datetime.datetime
now.

3. URL

50

HTML-
Python .
%s - ,
%s
now.
now - datetime.datetime, ,
%s ,
: 2008-12-13 14:09:39.002731.
HTML- <1><^> 2008-12-13 14:09:39.002731.</
body></html>.

, 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
,

3. URL

52

. , -
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-

55

except ValueError:
raise Http404()
dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
html = <html><body>4epe3 %s %s.</body></html> % (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
#

57

raise Http404()

dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
html = "<html><body>4epe3 %s %s.</body></html> % (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 False
html = <html><body>4epe3 %s %s.</body></html> % (offset, dt)
return HttpResponse(html)

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

59

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

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

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

, , ,
, , HTML-
- . .


Python.
, ,
, .

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

,
, -
, , -
, Python, .


Python. Django,
, .

61


Django ,
.
(
), .
HTML-, Django
.
. Django
HTML-,
, . , .
<htm]>
<head><title>H3Bemei-me 3aKa3e</title></head>

<body>
<h1> </11>
<>() {{ person_name }}!</>
<>, {{ company }}.
{{ ship_date|date:"F j, Y" }}.</p>
<> :</>

<ul >
{% for item in item_list %}
<li>{{ item }}</li>
{% endfor %}
</ul>

{% if ordered_warranty %}
<> .</>
{% else %}
<> ,
, .</>
{% endif %}
<> ,<br />{{ company }}</>
</body>
</html>

, 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

,
:
<django.template.Template object at 0xb7d5f24c>

0xb7d5f24c ,
( Template,
).
Template
,
. ,
TemplateO TemplateSyntaxError:
> from django. template import Template
> t = Template({% notatag %})
Traceback (most recent call last):
File ,,<stdin>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 }},</p>

. 217

66

4.
... <>, {{ company }}.
... {{ ship_date|date:F j, Y }}.</p>
...
...
...
.. .

{% if ordered_warranty %}
<p> .</>
{% else %}
<> ,
, .</>
... {% endi f %}
...
>
>
>

<> ,<br />{{ 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<p> () ,</p>\n\n<p> ,
Outdoor Equipment. \ April 2, 2009.</p>\n\n\n<p>
, \
, .</>\\\<>
,<br />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

4.

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


,
.
.

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 %}

4.

74

{% elif %} .
{% if %}:
{% if athlete_list %}
<> : {{ athlete_list }}.</p>
{% else %}
<> .</p>
{% if coach_list %}
<> : {{ coach_list }}.</p>
{% endif %}
{% endif %}

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

for
{% for %}
. for Python: for X in
Y, Y - , a X - ,
.
{%for %} {%endfor %}.
, ,
athleteJList:
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>

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

{% for %} :
{% for athlete in athlete_list %}
<h1>{{ athlete.name }}</h1>
<ul>
{% for sport in athlete.sports_played %}
<li>{{ sport }}</li>
{% endfor %}
</ul>
{% endfor %}

,
, - :

75

{% if athlete_list %}
{% for athlete in athlete_list %}
<p>{{ athlete.name }}</p>
{% endfor %}
{% else %}
<> . .</>
{% endif %}

, for
{% empty %},
, , .
:
{% for athlete in athlete_list %}
<p>{{ athlete.name }}</p>
{% empty %}
<> . .</>
{% endfor %}


. ,
, ,
.
continue,
. (, , ,
.)
{% for %}
forloop. ,
:

forloop.counter ,
. ,
forloop.counter 1. :
{% for item in todo_list %}
<p>{{ forloop.counter }}: {{ item }}</p>
{% 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 %}<li class=first>{% else %}<li>{% endif %}
{{ object }}
</li>
{% 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 %}
<table>
{% for city in country.city_list %}
<tr>
<td>CTpaHa #{{ forloop.parentloop.counter }}</td>
<td>l~0 p0 A #{{ forloop.counter }}</td>
<td>{{ city }}</td>
</tr>
{% endfor %}
</table>
{% 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 %}
<h1>flo6po !</h1>
{% endifequal %}

,
,
:
{% ifequal section sitenews %}

<> </>
{% endifequal %}
{% ifequal section community" %}
<h 1 >C 006iuecTB0 </h 1 >
{% endifequal %}

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

<> </>
{% else %}

4.

78
<> </>
{% endifequal %}

{% 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 %}

,
.
, :

79

{{ name|lower }}

{{ 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! , ,
.)

4.

80

, , ,
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 = <html><body>CePi4ac %s. </body></html>" % 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 }}.</body></html>")
html = t.render(Context({'current_date: now}))
return HttpResponse(html)

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

4.

82

/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.
,
:

83

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

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

)
(
).

4.

84

,
, Django - Python,
TEMPLATE_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/

TemplateDoesNotExist at 1/

currentdatetime.html

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

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

j:

Using loader django.template.looders.filesystem.load_.template_source:


/Users/jacob/Projects/ftook/ch6/te<nplctes/current_datetime.hbnl (File does not exist)
Using loader django.template.loaders.app_dlrector\es.load..tefflplate..source:
/Users/jacob/Projects/Book/djcmgo/amtrib/admin/teinplates/current^datetime. html (File does not exist)
/Users/jacob/Projects/Book/ch6/te<nplates/current..datetiine.htl (Redoes not exist)

:i
! *_____ .....

...

. . .......... ...........

........

[
f

If I
O. J

. 4.1. , ,
3,
: Template-loader
postmortem ( ),
, Django
(, File does not exist (
)).
.
current_datetime.html
:
<htmlxbody>Cefi4ac {{ current_date }}. </body></html>

, .

86

4.

render_to_response()
, , (Context)
HttpResponse,
. ,
get_template() .
.
- , Django
, ,
HttpResponse .
render_to_response(),
django.shortcuts. ,
, Context
HttpResponse ,
.
current_datetime,
render_to_response():
from django.shortcuts import render_to_response
import datetime
def current_datetime(request):
now = datetime.datetime.now()
return render_to_response(current_datetime.html', {current_date: now})

, ! .

get_template, Template, Context,


HttpResponse. django.
shortcuts. render_to_response. import datetime .

current_datetime -
now, , ,
HttpResponse
render_to_response().
HttpResponse,
.

render_to_response()
. , ,
, .
, render_to_response()
.

locals()
current_datetime:
def current_datetime(request):
now = datetime.datetime.now()

87

return render_to_response('current_datetime.html, {current_date: now})

- ,
( now )
. ,
, , , .
.

, P ython
localsO ,
,
, .
:
def current_datetime(request):
current_date = datetime.datetime.now()
return render_to_response(current_datetime.html', localsO)

, ,
, localsO,
, .
now current_date,
. localsO
,
,
.
localsO ,
,
, . ,
request.
,
.

get_template()
.
,
.
; Django (,
, 11)
,
.
.
get_template()
, :
t = get_template(dateapp/current_datetime.html)

4.

88

render_to_response() - get_
template(), render_to_
response():
return render_to_response(,dateapp/current_datetime.htmr, {'current_date: now})

.
, .
---------------------------------------------------------------------------------------------------- Windows .
get_template() UNIX .

include
, ,
{% include %},
.
. ,

. ,
, ,
, {%include %}.
nav. html.
,
, :
{% include 'nav.html %}
{% include nav.html %}

includes/nav.
html:
{% include includes/nav.html %}

,
template_name:
{% include template_name %}

get_template(),
TEMPLATE_DIRS
.

. , , :
tt mypage.html

<html>
<body>
{% include includes/nav.html %}

89

<h1>{{ title }}</h1>


</body>
</html>
tt includes/nav. html

<div id=nav>
: {{ current_section }}
</div>

mypage.html ,
current_section,
.
, {%include %}, , Django
:

DEBUG True,
TemplateDoesNotExist;

DEBUG False, ,
.



HTML,
Django HTML-
. - :
, ,
?

, HTML- ,
. , Django
{% include %}.
,
.
,
-,
, .
, ,
current_datetime,
current_datetime.html:
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01//ENM>
<html lang=ru>
<head>
<1 > < >
</head>
<body>

4.

90
<h 1> </>
<> {{ current_date }}.</>
<hr>
<>, .</>
</body>
</html>

,
, , hours_ahead 3?
HTML-,
- :
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01//EN>
<html lang="ru">
<head>
<title>BpeMA < >
</head>
<body>
<> </11>
<> {{ hour_offset }} {{ next_time >}.</>
<hr>
<>, .</>
</body>
</html>

, HTML-
. ,
, , JavaS cript-
.
,
,

. , header,
html:
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01//EN">
<html lang=ruM>
<head>

, , footer.html:
<hr>
<>, .</>
</body>
</html>

.
.
- <h1 > </11>,
header.html , <title>
. <h1> header.html,

91

<title>,
. , ?
Django
. ,
. ,
.
- ,
.
:
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01//EN>
chtml lang="ru>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<1> </>
{% block content %}{% endblock %}
{% block footer %}
<hr>
<>, .</>
{% endblock %}
</body>
</html>

, base.html,
HTML-, .
,
. (
,
base.html.)

{%block %}.
,
.
,
current_datetime.html:
{% extends base.html %}
{% block title %} {% endblock %}
{% block content %}
<> {{ current_date }}.</p>
{% endblock %}

hours_ahead
3. ( hours_ahead
, HTML-
.) :

92

4.
{% extends "base.html %}
{% block title %} {% endblock %}
{% block content %}
<> {{ hour_offset }} {{ next_time >>.</p>
{% endblock %}

? ,
. .
, base.html,
.
, . rent_datetime.
html {%extends %}, ,
. -
base.html.
{%block %} base.html
. ,
, {% block title %}, ,
{%block content %}.
, footer,
.
{% block %} ,
.
.
,
, .
.
:
1. base.html, .
.
2. base_SECTION.html
(, base_photos.html base_forum.html).
base.html ,
.
3. , ,
.
.


, , .

.

93

{% extends %},
.
.

, {%block %} ,
. ,
,

, . ,
, .


{% block %}
.

,
{{ block.super }}.
.
,
, .

{%block %}
. , block
. , -
, , ,
.
{%block %},
, .

, {% extends %},
, get_template(),
, TEMPLATE_DIRS.

{% extends %} ,
,
.
.

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

3 -
Django: URL.
,
.
.
-
.
, .
.
. , Amazon,
com - , .

Amazon, HTML.
.
Django
,
Python.
Django.
---------------------------------------------------------------------------------------------------- Django
SQL, , ,
.
, ,
. , .

95



3
(
).
.
Python,
SQL- - .
MySQLdb (
http://www.djangoproject.com/rlpythonmysql/), MySQL,
-:
from django.shortcuts import render_to_response
import MySQLdb
def book_list(request):
db = MySQLdb.connect(user=me, db=mydb1.
passwd=secret, host='localhost)
cursor = db.cursor()
cursor.execute(1SELECT name FROM books ORDER BY name)
names = [row[0] for row in cursor.fetchall()]
db.close()
return render_to_response('book_list.html, {names: names})

, :

.
Django.

: ,
, .
, , .

MySQL.
MySQL PostgreSQL,
(psycopg MySQLdb), SQL- - ,
. ,
. (
, Django
,
.)

, , ,
Django .
,
Django API :

96

5.
from django.shortcuts import render_to_response
from mysite.books.models import Book
def book_list(request):
books = Book.objects.order_by(name)
return render_to_response('book_list.html', {'books: books})

, .
.

MTV ( MVC)
,
-, ,
Django.
, Django

.
, .
, , ,
-
. -
.
- , -
- ,
-- (Model-View-Con
troller - MVC). ,
- , ,
, - ,
,
, .

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

97

, V,
Django:
- , ;
Django; ;

V - , , ,
;

- ,
, ,
URL, ,
URL.

,
, ,
Django MTV-, :

Model (), .
:
, , ,
.

Template (), .
, :
- .

V View (), -.

( ). ,
.

MVC- -,
Ruby on R ails, , Django , Django - .

MVC. Django
, ;
, , ,
. , Ruby on R ails
, , ,
, ,
, .
.
, .


,
Django. -

98

5.

; Django,
.
, ,
(, CREATE DATABASE).
SQLite .
TEMPLATE_DIRS ,
Django,
settings, .
:
DATABASE_ENGINE = 1
DATABASE_NAME =
DATABASE_USER =
DATABASE,PASSWORD =
DATABASE_HOST - '
DATABASE_PORT = '

DATABASE_ENGINE Django,
. , . 5.1.

5.1. DATABASE ENGINE


Django

postgresql

PostgreSQL

psycopg 1.x, http://www.djangoproject.com/r/python-pgsql/1/

postgresql_psycopg2

PostgreSQL

psycopg 2.x, http://www.djangoproject.com/rlpython-pgsql/

mysql

MySQL

MySQLdb, http://www.djangoproject.eom/r/
python-mysql/

sqlite3

SQLite

Python 2 .5 + ,
. pysqlite. http://www.djangoproject.eom/r/
python-sqlite/

oracle

Oracle

cx_0racle, http://www.djangoproject.com/rl
python-oracle/

, , ,
.
,
. Linux, ,
, . (
, - python-postgresql pythonpsycopg.) :

99

DATABASE_ENGINE = 'postgresql_psycopg2

DATABASE_NAME Django ,
:
DATABASEJIAME = 'mydb'

SQLite ,
:
DATABASE_NAME = '/home/django/mydata.db

SQLite /home/
django, .

DATABASEJJSER Django ,
.
SQLite .

DATABASE_PASSWORD Django
. SQLite ,
, .

DATABASE_HOST Django .
, Django
( localhost), .
SQLite .
MySQL - .
(/ ) MySQL,
MySQL UNIX-,
:
DATABASE_HOST = '/var/run/mysql'

settings,
, .
python manage. shell,
mysite. ( ,
Python Django .
, Django ,
,
.)
,
:
> 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
.
. 5.1.

( DATABASE.
ENGINE)
Environm ent variable DJANGO_SETTINGS_
MODULE is undefined.

python manage,
, python.

(He
DJANGO_SETTINGS_MODULE)
Error lo a d in g ______module:
N o m odule n am ed ______.
( ____ :
______ ) ..

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


(, psycopg
MySQLdb).
Django,

.
DATABASE_
ENGINE
.
, ?
DATABASE_
NAME,
,

CREATE DATABASE.
DATABASE_
USER,
,

.
,
DATABASE_HOST DATABASE_PORT
,
.


,
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):

104

5.
name = 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()

. ,
, ,
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,

)
,
tt. ( , ,
.)
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,

107

"last_name varchar(40) NOT NULL,


"email varchar(75) NOT NULL

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

109

> publisher_list = Publisher.objects.all()


> publisher_list
[<Publisher: Publisher object>, <Publisher: Publisher object>]

, .
.

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 :
[<Publisher: Publisher object>, <Publisher: Publisher object>]

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
[<Publisher: Apress>, <Publisher: 0 Reilly>]

_Unicode__()
, , Django
.

5.

112

, , __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.,

113

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

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


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

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.
, ,
- .

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

114

5.

objects;
.

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

,
.


, ;
, - . Django API
filterQ:
> Publisher, objects, fi 1te(name= Apress)
[<Publisher: 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)
[<Publisher: Apress>]

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)
<Publisher: 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>, <Publisher: 0 Reilly>]

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: Apress>]
> Publisher.objects.order_by(state_provinee)
[/Publisher: Apress>, <Publisher: O Rei1ly>]

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

,

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

, 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()

117

def _Unicode __(self):


return self.name
class Meta:
ordering = [* name]

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


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

, SQL-,
- WHERE ORDER BY:
SELECT id, name, address, city, state_province, country, website
FROM books_publisher
WHERE country = U.S.A
ORDER BY name DESC;



. , ,
.
Python :
> Publisher, objects. order_by( *name)[0]
<Publisher: Apress>

SQL-:
SELECT id, name, address, city, state_province, country, website
FROM books_publisher
ORDER BY name
LIMIT 1;

5.

118
> Publisher, objects. order_by( name)[0:2]

,
:
SELECT id, name, address, city, state_province, country, website
FROM books_publisher
ORDER BY name
OFFSET 0 LIMIT 2;

, :
> Publisher.objects. order_by('name)[-1 ]
Traceback (most recent call last):
AssertionError: Negative indexing is not supported.

,
order_by():
> 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):

5.

120
File <console>, line 1, in <module>
AttributeError: 'Manager' object has no attribute 'delete'

, 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.

Google
Django administration

Welcome, admin, O w tg* password / Log out

Site administration
R<nt Action
Croup

Users

fyAd'J

My Actions
None available

Puc. 6.2.

125

.
, ,
(Groups) (Users).
.
Django
.
,
,
.



, ,
Django .
django.middleware.locale.LocaleMiddleware'
MIDDLEWARE_CLASSES django.contrib.sessions,
middleware. SessionMiddleware'.

.
, - Change Password
( ) Log Out () , Groups (
) Users () -
. Django
.
Django .
19.

Change () Users (),


(. 6.3).

; , SQL SELECT * FROM auth_user. ,
, ,
,
. ,
,
.
,
(. 6.4).

, , .
(,
Change Password Form ( ) -

6. Django

126

Django administration

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

Mm' >A*'?s > Jsv?*


S e le c t u s e r to

ch an ge

41

0 1 1 1 1

^ ^ T .S e a a rrt ;

;^ :

By sta ff sU U i*
ftftivr,
Q
:Q

Coi

Username v-

- mail address

admin

admta3pexatnple.c0m

Tint nam

last nam

I All
Y

Stiff status

HO

By su p eru ser statu *


1 **
Ye*

I uicr

By active
Yei

. 6.3.

Django administration

lAwcom*, *dmln. Ouna password / I09 out

Hon*' >Auth >UifiOk>

Change user
Usrtwm;

admin

tv . ?.? >joK V<! %

(f

(H> 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 ?*<* ;**r I*;-} iw tft* - <itr

Acttve
!

be sm ttft *:!:;

.ftis >tut*s < tfck tae .k;css.

Sut>erus<?r status____________________________________________________________________________________________________

Puc. 6.4.

127

, - .) ,

: - ,
- , - .
, Delete ()
.
,
, . (,
!)
, Add ()

. ,
.
,
.
;
(. 6.5).
.QQ

________ -

Changeuser f Django site admin

Django administration
>>>Ai.tH

CNwg* p*$swt>r<f / log ow

>><;>

ip w a

Change user
Ptease correct the error below.
A This field! <} required.

Username:

Passw ord:

shalS 7e57iba089224nebdlbcc5a34l

t-triiJii a d d re s s -

adrtiin$xam ple

Puc. 6.5.

History (). ,
, ,
(. 6.6).

. Django

128

Django administration

W tflcom ^adm lrt.C ham j* paJivrord / to g out

H w j ' p >. >U s m - >History

Change history: admin


O ate/iim e

Iteef

Action

Ju n e 9, 2 0 0 9 , 1 1 :2 3 a .m .

admtn

Changed emai*.

Puc. 6.6.



.
,
, , ,
,
. books 5
: Publisher, Author Book.
books (mysite/books) admin.
:
from django.contrib import admin
from mysite.books.models import Publisher, Author, Book
admin.site.register(Publisher)
admin.site.register(Author)
admin.site.register(Book)

Django,
.

(>http://127.0.0.1:8000/adm in/ ).

129

Books Authors, Books Publishers. (


, ,
.)

. !
,
.
5 Publisher (
), .
,
--;
Book. , :
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

Add Book (http://127.0.0.1:8000/admin/books/book/add/)


publisher ( ForeignKey) ,
authors ( ManyToManyField) -
. ,

. ,
Publisher, .

, Add Book. .


?
.
Django
URL urls.py, admin.autodiscover(),
.
INSTALLED_APPS admin..
, .
admin. books
admin.site.register()
. ,
, .

130

6. Django

django.contrib.auth admin., Users Groups.


django.
contrib, django.contrib.redirects,
Django, .
-
Django , ,
URL. ,
URL ,
. dj ango/cont rib/admin
Django, ,
URL , -
,
,
. ( -
, ,
, ,
, .)


,
-
,
. , ,
email Author .
.
email , Book (
, mysite/books/models.py)
email blank=True:
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField(blank=True)

Django,
.
blank=False, .
. -
_unicode__() -
, SQL- CREATE TABLE
Python. blank=True
.
,
Author. , email

131

VARCHAR, ,
Django, .
blank=True,
(http://127.0.0:8000/adm in/books/author/add/ ).
, - Email - .
, .
, , This field is
required ( ) .



,
blank=True .
, .
SQL -
NULL. .
SQL NULL ,
Python None

, (, VARCHAR)
NULL, .
:
NULL, - ?
- ?
: , , NULL ?
, Django
CREATE TABLE (. 5) NOT NULL
. , ,
Author 5:
CREATE TABLE "books_author (
"id" serial NOT NULL PRIMARY KEY,
"first_nane varchar(30) NOT NULL,
"last_nane varchar(40) NOT NULL,
"email varchar(75) NOT NULL

)

.
Django,
,
, NULL.
, , ,
.
, , ,

132

6. Django

, ,
. (PostgreSQL
; MySQL
, .)
NULL - .
Django , NULL ,
null=True.
,
(, IntegerField, DecimalField, FloatField) ,
(, DateField, TimeField, DateTimeField),
null=True blank=True.
Book ,
publication_date .
:
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField(blank=True, null=True)

null=True ,
blank=True, null=True
, CREATE TABLE
NOT NULL publication_date.
, .
Django
,
ALTER TABLE .
, manage, dbshell
. NOT NULL
:
ALTER TABLE books_book ALTER COLUMN publication_date DROP NOT NULL;

(, PostgreSQL.)
10.
, ,
Add Book
.



. :
Django

ModelAdmin

133

. , publication_date
Book Publication Date.

,
. verbose_name
.
, Author.email e-mail
:
class Author(nodels.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField(blank=True, verbose_name=e-mail)

, ,
.
,
verbose_name , (,
, USA state). Django
, , ,
verbose_name, , .
, , verbose_name
.
, :
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField('e-mail', blank=True)

ManyToManyField
ForeignKey,
.
verbose_name.

ModelAdmin
, , - blank=True, null=True
verbose_name - ,
. ,
, ;
.
Django
.
ModelAdmin,

.

134

6. Django


, ,
,
Author.
_Unicode__() . 5
__Unicode__ ( ) Author , :
class Author(models.Model):
first_nane = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField(blank=True, verbose_name=e-mail1)
def _unicode__(self):
return u %s %s % (self.first_name, self.last_name)

Author
, . 6.7.
1

Sfltct author to change [ Django site admin

Django administration

__________

Welcome,

___________

Change ! ftogoyt

Select author to change


f
0

............... c-

Author

H Adrian Holovatv

Puc. 6.7.
,
. ,

.

ModelAdmin

135

ModelAdmin Author.
,
-
. admin. :
from django.contrib import admin
from mysite.books.models import Publisher, Author, Book
class AuthorAdmin(admin.ModelAdmin):
list_display = (1f1 rst_name, last_name',

email)

admin.site.register(Pub!isher)
admin.site.register(Author, AuthorAdmin)
admin.site.register(Book)

, :

AuthorAdmin. django.
contrib.admin.ModelAdmin ,

.
list_display, , ,
. , ,
.

adm in.site.registerQ ,
AuthorAdmin Author. :
Author AuthorAdmin.
adm in.site.register() ModelAdmin
.
( Publisher Book),
, .

, ,
- , .
, ,
(. 6.8).
. AuthorAdmin
search_fields:
class AuthorAdmin(admin.ModelAdmin):
list_display = ('first_name', last_name\ email)
search_fields = (first_name, last_name)

,
(. 6.9).
,
first_name last_name. ,
,
B arney
Hobarson.

136

6. Django

to change

_____________

.* * + j 0 h tt p / / 12 7 0.0 1:3000/ad m in /b o o lt>/author/

C ^ Q T G o o g ic

Django administration

""

W*kom, dmin. ** password / to$

> Book* >A^Cb<>",

Select author to change


Avtu>:-

--------

CO;

first name

Las name

Lnuit

Adrian

Molovaty

adnan@example.com

Puc. 6.8.
list_display
*9 I Qj*no site admia j

Django administration

W*lcom, dmin. 0 i*n$ pi sword / Log

Hor1 8<JOK

Select author to change

0
<m
Ajdfi^f*

trridl)
adnar>$>oxamplc.com

Puc. 6.9.
search_fields

ModelAdmin

137

Book :
from django.contrib import admin
from mysite.books.models import Publisher, Author, Book
class AuthorAdmin(admin.ModelAdmin):
list_display = (first_name', ,last_name', email)
search_fields = (' first_name, last_name)
class BookAdmin(admin.ModelAdmin):
list_display = (title, publisher, publication_date)
1ist_fiIter = (publication_date,)
admin.site.register(Publisher)
admin.site.register(Author, AuthorAdmin)
admin.site. register(Book, BookAdmin)

,
ModelAdmin - BookAdmin.
list_display,
, list_f ilter
,
. Django
Today (), Past 7 days ( 7 ), This month
( ) This year ( ). Django
, . . 6.10
, .
list_filter ,
DateField. (, ,
BooleanField ForeignKey.) ,
.
-
date_hierarchy:
class BookAdmin(admin.ModelAdmin):
list_display = (title, publisher, publication_date)
1ist_fi1ter = (publication_date,)
date_hierarchy = publication_date

, ,
, . 6.11.
,
.
, date_hierarchy ,
,
.
, ,

.
ordering,

6. Django

138

Sriott book to chMQ I Dfrogo site admin

M : J . L E A * . 1 0 h t t p ./ / 1 2 7 .0 .0 .1 :8 0 0 0 / a d m in / b o o k s / b o o k /

Django administration

8<>ok$

. ,

.
J

W tkonw , *dm fn. Ch*r>g* f4t*sv*or<i / 109 out.

i
-$

Select book to change


A

v .a fei,

< (?1*

' <

................

Title

C'

T h e D efin itiv e Cuidte

Co;
Pubiisbe

to D ja n g o

By publication d ate

Publication d at

A preis Inc June 9. 2009

1bo<^4

Puc. 6.10. list_filter

h n p ://1 2 7 .0 .0 .1 :8 0 0 0 /ad m in /b o o k s/b o o k /

Django administration

0 jTQ*
Wlcom*. *d m in .

0*>9 p *iv * o n i / l o g a

Ifon* Sooki SiX-k


Select book to change


?
9
1

"

By publication d ate

Co

("} T itle
The D efin itiv e G u id e to D ja n g o

A ry tiUits

P ublisher

Publication cUte

Aj>res Inc June 9, 2009

I boo*

Puc. 6.11.
datejtiierarchy

ModelAdmin

139

Meta ( 5),
, .
class BookAdnin(adnin.ModelAdmin):
list_display = ('title', publisher
1ist_fiIter = ('publication_date,)
date_hierarchy = 'publication_date

*publication_date )

ordering = (1-publication_date,)

ordering ,
Meta, ,
.

,
.
, , .
, Publication Date
, ,
(. 6.12).
S elect b o o k to c h a n g e | D jan g o s ite a d m in

| , , ;
1 * 1

| H h ttp ://1 2 7 .0 .0 .1 :8 0 0 0 /a d m m /b o o k s/b o o k /

Django administration

. > :..... >,


%

I f f O r Cooyi*
Welcome, adm in. Change patswwrd / Log out

C O D

Select book to change

2009
By p u b licatio n d a le
Any OAU:
[J

TU*

Pubtivher

Put}iK<*tiop d ate -

t h e D e f in itiv e G m d e to Pjafi< jo

Aprcs Inc

June 9, 2009

Puc. 6.12. ordering


,
.
,
.

. Django

140


, ,
.
.
,
. fields
ModelAdmin:
class BookAdmin(admin.ModelAdmin):
list_display = ( ' title', publisher, 'publication_date)
1ist_fi1ter = (publication_date,)
date_hierarchy = publication_date'
ordering = (-publication_date,)
fields = (title* , authors, publisher, publication_date)


. ,
, . ,

. .
fields :
.
.
,
-
. ,
publication_date:
class BookAdmin(admin.ModelAdmin):
list_display = (title, publisher, publication_date)
1ist_filter = (publication_date,)
date_hierarchy = publication_date
ordering = (-publication_date,)
fields = (title, authors, publisher)

.
, , ,
(,
).

, Django publication_date None,
null=True.

--.
,
ManyToManyField
. , HTML,
, . -

141

ModelAdmin

, Control (
Command ).
, ,
, .

filter_horizontal. BookAdmin
, .
class BookAdmin(admin.ModelAdmin):
list_display = (title* , 'publisher, publication_date)
list_filter = (publication_date,)
date_hierarchy = publication_date
ordering = ('-publication_date, )
filter_horizontal = (authors,)

( ,
, fields,
.)
, ,
Authors ()
JavaScript ,
Available Authors (
) Chosen Authors ( ) .

Django administration
H ow

8om > Book* - 'Th;:

Change book
Title:

Otan$ password

out

;<:<;*>

231
The Definitive Guide to Django

P u b lis h e r

Apress Inc

P ublication
date:

2 00 9-0 6-09

Authors:

Available author*

->3y i vj

Choove at I

O t i all

Save and add another ; Save and continue editing

Puc. 6.13.
filter_horizontal

142

6. Django

filter_horizontal
, ManyToManyField
. , .
, , filter__horizontal
- .
ModelAdmin filter_vertical.
, filter_horizontal,
, . , .
filter_horizontal filter_vertical
ManyToManyField
ForeignKey. ForeignKey
<select>,
, ManyToManyField,
,
. ,
, Add Book
,
<select>.
raw_id_fields.
ForeignKey,

(<input type=text>), <select> (. 6.14).
class BookAdmin(admin.ModelAdmin):
list_display = (title, publisher, publication_date)
list_filter = (publication_date,)
date_hierarchy = publication_date
ordering = (-publication_date,)
filter_horizontal = (authors,)
raw_id_fields = (publisher,)

? .
,
-
, .

,
,
, . ,

- .
Django ,
,
.

,
)
' * 1 *

143

C h an g e b o o k j D jango site ad m in
+

i boogie

http ://1 2 7 .0 .0 .l:8 0 0 0 /a d m in /b o o k s /b o o k /l/

Django administration
>owe - - gookt - Tre

Weicofnc, *dmin. \ * password / toy out


Cukk i<;

Change book
Title:

The Dc<iniUv Guide to Django

Publisher.

Publication
date:

2009- 06-09 To*y

Authors:

AvaiiabU* author*

Apress Inc

i ; j

Adrian Holovaty

Delete

Chooso all

'v Clear all

Save and add another

Save and continue editing .

. 6.14.
raw_id_fields

,
,
, .
14 ,
.

, .
, User () Group
(). , , , ,
, ,
, .
-, :

active , .
, .

staff ,
(
).

6. Django

144

( )
(. 14),
.

superuser ,

. ,
( ) .

, ,
,
. ,
(, ,
), : , .

.
,
. ,
, . ,
, ,
, , ,
,
Apress. - ,
(
Django).
----------------------------------------------------------------------------------------------------
. -
, ,
!

.

. -
, .
,
.



, , ,
Django.
,
, .

145

Django ,
,
; .
, Django,
, ,
, :
1. , ,
.
2. Django, ,
.
3. ,
- ; ,
. , .
.
4. ,
.

( !).
, Django ,

.
, ,
.

. ,
.
.

. ,
(,
-),
. , ,
.

.

, ,
. ,
,
.
,
.

:
- - . ,

146

6. Django

,
.
,
. ,
, .
,
.

?

.
-: .

HTML- - -.
,
Google,
.
, Django ,
, - .
HttpRequest Form.


HttpRequest 3
,
. ,
HttpRequest , :
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello world)

HttpRequest, request,
,
, , .
(,
,
) .

URL
HttpRequest URL,
. 7.1.

7.

148
7.1. HttpRequest
/

request.path

,
,

/hello/

request.get_host()

"127. 0. 0.1:8000
www.example.com

request.get_full_path()

path

( )

,,/hello/?print=true

request.is_secure()

rue,

True False


HTTPS,
False

, . 7.1,
URL .
,
. :
# !
def current_url_view_bad(request):
return HttpResponse("Ao6po /current/)
tt

def current_url_view_good(request):
return HttpResponse(Ao6po %s" % request.path)


request. - Python, HTTP-
, IP -
( -). ,
, ,
, -.
:

HTTP_REFERER: URL, . (
REFERER.)

HTTP_USER_AGENT: (
). :
"Mozilla 5.0 (11; U; Linux i686) Gecko/20080829 Firefox/2.0.0.17

REM0TE_ADDR: IP - , 12.345.67.89. (
-, IP -,
, 12.345.67.89,23.456.78.90.)

149

, request. - Python,

Key Error. ( HTTP- - ,
, ,
,
,
.) try/except-,
get():
tt !

def ua_display_bad(request):
ua = request. META[ HTTP_USER_AGENT] tt KeyError!
return HttpResponse("Baiu %s" % ua)
tt ( 1)

def ua_display_good1(request):
try:
ua = request.META[HTTP_USER_AGENT]
except KeyError:
ua = unknown'
return HttpResponse("Baiu %s" % ua)
tt ( 2)

def ua_display_good2(request):
ua = request.META.get('HTTP_USER_AGENT', unknown)
return HttpResponse(Bauj %s % ua)

,
request., ,
. :
def display_meta(request):
values = request.META.items()
values.sort()
html = []
for k, v in values:
html.append( <trxtd>%s</td><td>%s</td></tr> % (k, v))
return HttpResponseC <table>%s</table> % \n.join(html))


Django, HTML- . ,
request, path
HttpRequest,
.


HttpRequest
,
: request.GET request. POST.

150

7.

, GET
POST.
POST- HTML- ( <form>), GET- - ,
.

,
, request.GET request.POST ,
,
Python, . ,
request.GET request.POST get(), keysQ values()
for key in request.GET.

, ,
? request.GET request.
POST , .
, , Python,
, readQ,
.


,
, , ,
.
, , :
HTML-
. ,
:
from django.shortcuts import render_to_response
def search_form(request):
return render_to_response(search_form.html)

3 ,
, Python.
books/views..

search_form.html :
<html>
<head>

<title>floncK</title>

151

</head>
<body>
<form action=,7search/M method="get">
<input type="text name="q>
<input type="submit" 1=">

</form>
</body>
</html>

URL urls.py:
from mysite.books import views

urlpatterns = patternsC',
tt ...

(r* "search-f rm/$', views. search_form),

...

)
, views ,
from mysite.views import search_form, .
8.

http://127.0.0.1:8000/search-form/ , .
.
, Django 404.
URL /search/, .
, :
tt urls.

urlpatterns = patternsC',

...

(' ~search-form/$', views. search_form),


(r'~search/$', views.search),
tt ...

)
tt views, py

def search(request):
if q ' in request.GET:
message = : %r % request.GET['q']
else:
message = .'
return HttpResponse(message)


, , Django ,

152

7.

,
. :
1. HTML- <form> q.
q GET (method-get) URL
/search/.

2. Django, URL /search/


(search()), q GET-.
, q request.
GET. , ,
, ,
. ,
Key Error.
tt !

def bad_search(request):
tt KeyError,
tt q ' !
message = : % ' % request.GET[q']
return HttpResponse(message)


GET- (,
/search/?q=django),
request.GET. 3,

URL,
URL Django URL,
PH P/Java, /time/plus?hours=3, ,
7 , .
,
( hours=3)
request.GET.

POST- , GET-,
request.GET request. POST.
GET POST? GET ,
- - , POST -
- -
, ,
, .
GET,
. ( GET POST,
http://www.w3.org/2001/tag/doc/whenToUseGet.
h tm l.)

153

, request.GET ,

( views, ):
from django.http import HttpResponse
from django.shortcuts import render_to_response
from mysite.books.models import Book
def search(request):
if q in request.GET and request.GET['q']:
q = request.GET[q' ]
books = Book.objects.filter(title_icontains=q)
return render_to_response(search_results.html',
{books': books, 'query': q})
else:
return HttpResponse( .)

, .

, ,
q request.GET,
.

Book, objects.f ilter(title_icontains=q),


,
, icontains - (
5 ),
: , q
.
.
icontains
, . (
-
. open-source full-text
search ( ),
.)

books Book .
search_results.html :
<> : <strong>{{ query }}</strongx/p>
{% if books %}
<> {{ books|length }} {{ books|pluralize }}.</p>
<ul>
{% for book in books %}
<li>{{ book.title }}</li>
{% endfor %}
</ul>
{% else %}

154

7.
<>, , .</>
{% endif %}

pluralize,
V 1, .2



, .
, .
-, search()
-
, .
, ,
, Django.
,
, -
. :
from django.http import HttpResponse
from django.shortcuts import render_to_response
from mysite.books.models import Book
def search_form(request):
return render_to_response('search_form.html)
def search(request):
if q ' in request.GET and request.GET['q']:
q = request.GET[q 1]
books = Book.objects.filter(title__icontains=q)
return render_to_response(search_results.html,
{books': books, 'query': q})
else:
return render_to_response(search_form.html', {'error': True})

( search_form(),
.)
search(),
search_form.html, .
, -

, V ,
pluralize, , . - . .

pluralize
: h t t p : / / v a s 3 k . r u / w o r k / d j a n g o _ r u _ p l u r a l i z e . - . . .

155

. search_form.html ,
error.
<html>
<head>
<title>floMCK</title>

</head>
<body>
{% if error %}
<p style="color: red;"> .</p>
{% endif %}
<form actions'/search/" method=get">
<input type="text" name="q">
<input type=submit 1="">
</form>
</body>
</html>


search_form(), search_form() error
, , .
, :
search_form()?
URL /search/ ( GET-)
( ).
search_form() URL ,
search() , URL /search/
:
def search(request):
error = False
if q ' in request.GET:
q = request.GET['q']
if not q:
error = True
else:
books = Book.objects.filter(title__icontains=q)
return render_to_response(search_results.html',
{'books': books, 'query': q})
return render_to_response(1search_form.html',
{'error': error})

, URL /search/ ,
.
q , ,
. ,
q .
, , .

156

7.

( URL) , /search/
, ,
URL HTML- <form> search_
form.html.
<form actions'/search/" method=get">

:
<form action=" method=;,,getM>

action^" URL
. action,
search() URL.


,
; , .
HTML- .
:

, foo -
.

,
. 123 .

...

8
.

JavaScript
JavaS cript-
, ,
, .
-
. JavaScript,


.
,
(
Django).
JavaS cript ,
,
.

157

search() ,
20 . ( ,
.)
?
:
def search(request):
error = False
if 1q in request.GET:
q = request.GET['q']
if not q:
error = True
elif len(q) > 20:
error = True
else:
books = Book, objects.filter(title__icontains=q)
return render_to_response('search_results.html',
{books': books, 'query': q})
return render_to_response('search_form.html',
{error: error})

20 ,
. search_form.html
: ,
, (
):
<html>
<head>
<t it le>noncK</title>

</head>
<body>
{% if error %}
<p style="color: red;">
20 .
</>
{% endif %}
<form action-/search/" method="get">
<input type="text" name="q">
<input type="submit" 1="">
</form>
</body>
</html>

- .
.
20 ?
.
, error - ,
.
:

158

7.
def search(request):
errors = []
if q ' in request.GET:
q = request.GET[q ']
if not q:
errors.append(BBeAHTe .')
elif len(q) > 20:
errors.append(BBeAHTe 20 .)
else:
books = Book.objects.filter(title__icontains=q)
return render_to_response(search_results.html,
{books': books, 'query': q})
return render_to_response(search_form.html',
{errors: errors})

search_form.html,
, errors,
error:
<html>
<head>
<title>nonCK</title>
</head>
<body>
{% if errors %}
<ul>
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
<form action=/search/" method=get">
<input type="text name=q">
<input type=submit" ^^''^
</form>
</body>
</html>



, :
q . -
Django
.
, ,

. ,
.

contact_form.html.

159

<html>
<head>
<title>Cecb < >
</head>
<body>
<1> </>
{% if errors %}
<ul>
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
<form action=,7contact/M method="post">
<>: <input type="text" name="subject"></p>
<> e-mail (): <input type="text" name="e-mail"x/p>
<>:
<textarea name=message" rows=,,10M cols="50"x/textarea>
</p>
<input type="submit 1="0">
</form>
</body>
</html>

: , e-mail .
, .
, method-post, method-get,
-
.
, search_form.html.
, searchQ
, :
from django.core.mail import send_mail
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
def contact(request):
errors = []
if request.method == 'POST':
if not request.POST.get(1subject', *'):
errors.append(BBeAHTe .)
if not request.POST.get(message', ''):
errors.append( .1)
if request.POST.get(1e-mail') and
not in request.P0ST['e-mail']:
errors.append( e-mail.')
if not errors:
send_mail(
request.P0ST[subject' ],
request.P0ST[message'],

7.

160

request.POST.get('e-mail, 'noreply@example.com),
['siteowner@example.com],

)
return HttpResponseRedirect('/contact/thanks/)
return render_to_response(contact_form.html,
{errors: errors})

------------------------------------------------------------------------------------------------ books/views.?
, ,
- ? ; Django ,
URL.
contact ,
books. views. __init__..

, .

request.method POST.
,
. ,
request.method GET,
GET, POST.
: .

request.POST,
request.GET, HTML- <form> contact_f orm.
html method-post.
POST, request.GET .

, .
, request.POST,
get() ;

.

e-mail ,
, . , -
, @.
(
Django,
).


django.core.mail.sendjnail.
: , ,
send_mail - E-mailMessage,
: ,

.

161

, send_mail()
,
a Django .
http://docs.djangoproject.
//dev/topics/email/.

HttpResponseRedirect

.
( : /
URL/), ,
, , render_
to_response() .
, ,
, POST,
. ,
, ;
.
POST
, .

POST-. .

, , ,
.
? if?
: .
, ,
, , ,
( ).
,
, ,
:
# views.
def contacts request):
errors = []
if request.method == 'POST':
if not request.POST.get(subject'. '):
errors.append(' .')
if not request.POST.get('message. ''):
errors.append(' .)
if request.POST.get('e-mail') and
not in request.P0ST[e-mail']:
errors.append(Bee e-mail.')
if not errors:
send_mail(

162

7.
request.P0ST['subject],
request.P0ST['message'],
request.POST.get('e-mail, 'noreply@example.com),
['siteowner@example.com'],

)
return HttpResponseRedirect('/contact/thanks/')
return render_to_response('contact_form.html, {
'errors: errors,
'subject': request.POST.get('subject', ''),
'message': request.POST.get('message, ''),
'e-mail': request.POST.get('e-mail, ''),

})
# contact_form.html
<html>
<head>
<title>Cec < >
</head>
<body>
<1> </|1>
{% if errors %}
<ul>
{% for error in errors %}
<1i>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
<form action="/contact/" method="post">
<>: <input type="text" name="subject" value={{ subject }}"></p>
<> e-mail ():
<input type="text" name="e-mair' value="{{ e-mail }}">
</p>
<>:
<textarea name="message" rows="10 cols="50">
**{{ message }}**
</textarea>
</ p >
<input type="submit" 1=0>
</form>
</body>
</html>

, ,
. , ,
-
.

163


Django django.forms,
, :
HTML- .
.

newforms Django
Django django.
newforms. django.
forms, .
Django
- django.forms.
,
django.newforms, . Djan
go 1.0 django.forms , a django.newforms
django.forms.
,
Form HTML- ( <form>) .
<form>,
Form. ,
views.,
Form forms..
, views., :
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField()
e-mail = forms.EmailField(required=False)
message = forms.CharField()

Django.
Field,
CharField EmailField,
Form.
, , e-mail ,
required=False.
Python ,
. ,
HTML:
> from contact.forms import ContactForm
> f = ContactForm()

164

7.
> print f
<tr><th><label for="id_subject>Te M a : < / l a b e l x / t h x td >
<input type=text name=subject" id=id_subject" /></tdx/tr>

<tr><thxiabel for=id_e-mail>E-mail :</labelx/thxtd>


<input type=text name=e-mail id=id_e-mail /></td></tr>
<trxth><label for=id_message>Coo6meHHe:</labelx/thxtd>

<input type=text name=message id=id_message /></tdx/tr>

Django , <label>
. ,
.
HTML-
( <table>), , :
>>> print f.as_ul()
<li><label for="id_subject>TeMa:</label>

<input type=text" name=subject id=id_subject /></li>


<lixiabel for=id_e-mail>E-mail :</label>
<input type=text name=e-mail id=id_e-mail /x /l i>
<li><label for="id_message>Coo6meHne:</label>

<input type=text name=message id=id_message /x/li>


> print f.as_p()
< p x i a b e l for=id_subject>TeMa:</label>

<input type=text name=subject id=id_subject /></p>


<pxiabel for=id_e-mail>E-mail:</label>
<input type=text name=e-mail id=id_e-mail /></p>
< p x i a b e l for=id_message>Coo6meHne:</label>

<input type=text name=message id=id_message /></p>

, <table>, <ul>
<form> ,
.

. HTML :
> print f[ subject' ]
<input type=text name=subject id-id_subject />
> print f['message' ]
<input type=text name=message id=id_message />

Form .
, Form
, :
> f = ContactForm({subject: , e-mail: 'adrian@example.com,
... message: ' !})

Form,
:

165

> f.is_bound
True

, ,
is_valid().
, :
> f.is_valid()
True

e-mail ,
, required=False:
> f = ContactForm({' subject' : ''. 'message': ' !'})
> f.is_valid()
True

subject message,
:
> f = ContactForm({'subject' : })
> f.is_valid()
False
> f = ContactForm({'subject' : '', 'message': ''})
> f.is_valid()
False

:
> f = ContactForm( {' subject' : *, message: ''})
> f['message' ].errors
[u 'This field is required.']
> f['subject].errors

[]
> f['e-mail'].errors

[]
errors,
, :
> f = ContactForm({subject: , message: })
> f.errors
{'message': [uThis field is required.]}

, Form,
, cleaned_data.
. Django ,
, Python:
> f = ContactForm({'subject: , 'e-mail: 'adrian@example.com',
... message: ' !})
> f.is_valid()
True
> f.cleaned_data

166

7.
{'message': ' !'. 'e-mail': u'adrian@example.com', 'subject':
u''}

,
Unicode,
IntegerField DateField,
cleaned_data datetime.date.

Form
Form,
, contact().
contactQ,
forms:
# views.
from django.shortcuts import render_to_response
from mysite.contact.forms import ContactForm
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail(
cd[* subject],
cd[message'].
cd.getCe-mail', 'noreply@example.com'),
['siteowner@example.com' ].

)
return HttpResponseRedirect('/contact/thanks/)
else:
form = ContactForm()
return render_to_response('contact_form.html, {'form': form})
# contact_form.html
<html>
<head>
<1> < >
</head>
<body>
<1> </1>
{% if form.errors %}
<p style="color: red;">
{{ form.errors|pluralize }}1.

pluralize .
(rupluralize), ,
: {{ form, errors |rupluralize: "
, "}}. - . . .

167

</>
{% endif %}
<form action='' method="post">
<table>
{{ form.as_table }}
</table>
<input type="submit" 1="0">
</form>
</body>
</html>

, !
Django HTML-,

.
. ,
, ,
, , . (,

send_mail(),
.)


, , ,
message <input type=text>,
<textarea>. ,
widget:
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField()
e-mail = forms.EmailField(required=False)
message = forms.CharField(widget=forms.Textarea)


. ,
.
, Field ,
- .


- .
, ContactForm,
subject 100 .
CharField max_length:

168

7.
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
e-mail = forms.EmailField(required=False)
message = forms.CharField(widget=forms.Textarea)

min_length.



subject: ! (
). initial
Form:
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail(
cd[subject'],
cd[message'].
cd.get('e-mail', 'noreply@example.com'),
['siteowner@example.com].

)
return HttpResponseRedirect(/contact/thanks/')
else:
form = ContactForm(
initial={'subject': ' !'}

)
return render_to_response('contact_form.html', {'form': form})

subject.

, .
, , ,
.


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

169

,
Form.
message,
Form clean_message():
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
e-mail = forms.EmailField(required=False)
message = forms.CharField(widget=forms.Textarea)
def clean_message(self):
message = self.cleaned_data['message]
num_words = len(message.split())
if num_words < 4:
raise forms.ValidationErrorCtaiuKOM ! )
return message

Django ,
clean_ .
, .
clean_message()
( ,
CharField).
, self.cleaned_data.
, , ;
.
1()
split(). ,
ValidationError.
.
,
. (
Python) .
return, None,
.


HTML-,
Django,
;
, e-mail "E-mail. (, ?
Django
verbose_name , . 5.)
, .
label, :

170

7.
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
e-mail = forms.EmailField(required^False, label^Batu e-mail)
message = forms.CharField(widget=forms.Textarea)


contact_form.html {{ form.as_
table }} ,
.
-
CSS-. ,
CSS-: <1
class-errorlist>. ,
:
<style type=text/css>
ul.errorlist {
margin: 0;
padding: 0;

}
.errorlist li {
background-color: red;
color: white;
display: block;
font-size: 10px;
margin: 0 0 3px;
padding: 4px 5px;

>
</style>

, , HTML-
,
. {{ form.asjtable }}
- ,
,
,
.
(cinput type-text>, <select>, <textarea> . .)
,
{{ form.fieldname }},
{{ form.fieldname.errors }}.
:
<html>
<head>
<> < >
</head>
<body>

171

<> </>
{% if form.errors %}
< style=color: red;>
{{ form.errors|pluralize }}.
</p>
{% endif %}
<form action="" method="post">
<div class=field>
{{ form.subject.errors }}
<label for=id_subject>TeMa:</label>
{{ form.subject }}
</div>
<div class=field">
{{ form.e-mail.errors }}
<label for=id_e-mair>Ba[ij e-mail:</label>
{{ form.e-mail }}
</div>
<div class="field>
{{ form.message.errors }}
clabel for^'idjnessage^CooGiueHne: </label>
{{ form.message }}
</div>
<input type=submit 1=,,0">
</form>
</body>
</html>

, {{ form.message.errors }}
<ul c la s s - e rr o r lis t>, ,
( ).
form, message.errors
. :
<div class=field{% if form.message.errors %} errors{% endif %}>
{% if form.message.errors %}
<ul>
{% for error in form.message.errors %}
<li><strong>{{ error }}</strong></li>
{% endfor %}
</ul>
{% endif %>
<label for=id_message>Coo6iueHne:</label>
{{ form.message }}
</div>

,
<div> errors,
.

172

7.

?
-
. 8 12
Django, ,
Django ( 12).

Django.
. 8

URL ( 3).

II

8

URL
3
URL Django.
.

URL:
URL - Django,
Python.
.


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

)
3, URL
, -
.
.
Django
URL,
. ( ,

176

8. URL

, import
.) ,
views. URL
:
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = pa tternsC,
(r"hello/V , views.hello),
(r" t i m e / T , views.current_datetime),
(r"time/plus/(d{1,2})/$', views.hours_ahead),

)
Django
URL: ,
-.
:
from django.conf.urls.defaults import *
urlpatterns = pa tternsC,
(r"hello/V , mysite.views.hello),
(r~time/$, 'mysite.views.current_datetime),
(r'"time/plus/(d{1,2})/$, 'mysite.views.hours_ahead),

)
( , .
mysite.views.current_datetime ,
mysite. views, cu rent_datetime.)


; ,
, Django
.

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

)
(.)
. Django
.

URL:

177

,
.

:

,
.

URL
, Python.

- :

. .
.

Python, ,
.

,
URL. .



, ,
URL .
.
patterns().
:
from django.conf.urls.defaults import *
urlpatterns = patternsC,
(r"hello/V , 'mysite.views.hello),
(r"time/V , 'mysite.views.current_datetime),
(r~time/plus/(\cl{1,2})/$, 'mysite. views.hours_ahead),
(r~tag/(\w+)/$, weblog.views.tag),

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

)
urlpatterns += patterns('weblog.views,
(r"tag/(\w+)/$f , 'tag),

8. URL

178

, urlpatterns . ,
. , ,
patternsO, , ,
, .

URL
urlpatterns, , ,
URL Django .
DEBUG :
from django.conf import settings
from django.conf.uris.defaults import *
from mysite import views
urlpatterns = patternsC',
(r* **$' , views, homepage),
(r,''(\d{4})/([a-z]{3>)/$, views.archivejnonth),

)
if settings.DEBUG:
urlpatterns += patternsC,
(rdebuginfo/$, views.debug),

)
URL /debuginfo/ , DEBUG
True.



URL , ,
URL , Django

.
,
URL .


Python ,
,
.
,
.
- ,
.

URL:

179

:
def sel1(item, price, quantity):
print " %s %s %s % (quantity, item, price)


,
:
sel1(, '$2.50, 6)


, .
:
sell(item=, prices$2.50, quantity=6)
sell(item=, quantity=6, prices$2.50)
sel1(prices$2.50, item=, quantity=6)
sell(prices$2.50, quantity=6, item=)
sell(quantity=6, item=, prices$2.50)
sell(quantity=6, prices$2.50, item=)

, ,
,
, :
sell(, $2.50, quantity=6)
sell(, price=$2.50, quant it=6)
sell(, quantity=6, price=$2.50)


(?P<name>pattern), name - , a pattern . URL
:
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns(,
(r~articles/(\d{4})/$, views.year_archive),
(r~articles/(\d{4})/(\d{2})/$*, views.month_archive),

)
:
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns(1,
(r' ~articles/(?P<year>\d{4})/$, views. year_archive),
(r~articles/(?P<year>\d{4} )/(?P<month>\d{2} )/$ , views. month_archive),

8. URL

180

,
:
, .
, ,
U R L /articles/2006/03/ :
month_archive(request, 2006. 03)

:
month_archive(request, year=2006, months03)

U R L
, .

. ,
U R L ,
,
month_archive.
,
U R L .
,
;
.
, ,
Django.
U R L ,
, .


U R L ,
U R L
. , Django
, U R L
, .
U R L
:

,
, .


.
.

URL:

181



,
, . ,
:
# urls.
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patternsC,
(r^foo/S, views.foo_view),
(r~bar/$, views.bar_view),

)
tt views.py

from django.shortcuts import render_to_response


from mysite.models import MyModel
def foo_view(request):
m_list = MyModel.objects.filter(is_new=True)
return render_to_response(template"!.html, {m_list: m_list})
def bar_view(request):
m_list = MyModel.objects.filter(is_new=True)
return render_to_response('template2.html, {m_list: m_list})

, .
:
URL , URL ,
, URL
:
# urls.
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patternsC,
(r~(foo)/$, views.foobar_view),
(r~(bar)/$', views.foobar_view),

)
# views.py
from django.shortcuts import render_to_response
from mysite.models import MyModel
def foobar_view(request, url):
m_list = MyModel.objects.filter(is_new=True)
if url == 'foo:
template_name = template"!.html

8. URL

182

elif url == 'bar:


template_name = template2.html
return render_to_response(template_name,

{m_list: m_list})


URL .
/to o / /f /,
.
, URL
. URL
() : ,
.

:
# urls.
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patternsC',
(r1^foo/$, views.foobar_view,
(r'~bar/$. views.foobar_view,

{'template_name: 'templatel.html}),
{'template_name: 'template2.html'}),

)
tt views, py

from django.shortcuts import render_to_response


from mysite.models import MyModel
def foobar_view(request, template_name):
m_list = MyModel.objects.fiIter(is_new=True)
return render_to_response(template_name, {m_list: m_list})

, URL
template_name.
.
-
.
, Django, ,
, ,
11.
,
.

URL
, ,
, URL,
, .

URL:

183

URL
URL,
URL
, .
, , -
, URL :
/mydata/jan/01/
/mydata/jan/02/
/mydata/j /03/

# ...
/mydata/dec//
/mydata/dec/31/

-
URL ( ):
urlpatterns = patternsC',
(mydata/C?P<month>\w{3})/(?P<day>\d\d)/$, views.my_view),

)
:
def my_view(request, month, day):

# . ..

. ,
URL,
my_view, URL month
day ( ).
, URL /mydata/birthday/,
/mydata/j/06/.
:
urlpatterns = patternsC',
('mydata/birthday/$', views.my_view, {'month': 'jan', 'day': '06'}),
(r' ~mydata/(?P<month>\w{3})/(?P<day>\d\d)/$, views. my_view),

)
,
. month day,
- URL
- .


.
, :
def say_hello(person_name):
print , % s % person_name

184

8. URL
def say_goodbye(person_name):
print , %s' % person_name

:
def greet(person_name, greeting):
print %s, %s % (greeting, person_name)

, Django,
URL.

. :
Event, - BlogEntry. ,
- ,
, - .
, , :
# urls.
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patternsC,
(r'~events/$, views.event_list),
( r ' ~blog/entries/$, views.entry_list),

)
# views.py
from django.shortcuts import render_to_response
from mysite.models import Event, BlogEntry
def event_list(request):
obj _1i st = Event.objects.all()
return render_to_response(mysite/event_list.html,
{event_list: obj_1ist>)
def entry_list(request):
obj _1i st = BlogEntry.objects.all()
return render_to_response(mysite/blogentry_list.html,
{'entry_list1: obj_1ist>)

:
. :
# urls.
from django.conf.urls.defaults import *
from mysite import models, views
urlpatterns = pa tt er ns C,
(r~events/$, views.object_list, {model: models.Event}),
(r~blog/entries/$, views.object_list, {model: models.BlogEntry}),

URL:

185

# views.
from django.shortcuts import render_to_response
def object_list(request, model):
obj _1ist = model.objects.all()
template_name = 'mysite/%s_list.html % model.__name__.lower()
return render_to_response(template_name, {'object_list: obj_1ist})


, !
, ,
object_list .
, .

model.
Python
, .

model.objects.allQ-
(duck typing - , ):
, , , ,
, . ,
model, , objects,
11().


model.__name__.lowerQ. Python
_name_, .
, ,
. , Blog Entry
_name__ BlogEntry.

:
' object_list.
blogentry_list event_list,
.

, ,
, Django
,
.
11.


Django, ,
, . ,
,
.
URL.

186

8. URL


:
def my_view(request, template_name):
var = do_something()
return render_to_response(template_name,

{var: var})



,
URL, URL
. ,
URL
,
.
, , URL:
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patternsC',
(r'~mydata/(?P<id>\d+)/$', views.my_view, {id: 3}),

)
,
id. id, ,
. , URL (
, /mydata/2/ /mydata/432432/) , id
3 ,
URL.
, id
-
, ,
. ;
, .

,

-
. ,
,
. :
# urls.
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patternsC ,

URL:

187

('~blog/$, views.page),
(r' ''blog/page(?P<num>\d+)/$', views, page),

)
# views.py
def page(request, num^'V):
# num.
# ...

URL - views.
page, - URL .
,
num - 1
, num.
----------------------------------------------------------------------------------------------------
, 1,
.

,
.

,
template_name:
def my_view(request, template_name='mysite/my_view.html'):
var = do_something()
return render_to_response(template_name, {var: var})


URL ,
URL, .
,
, .
,
Django URL:
urlpatterns = patte rns(.
U

...

('"([ V]+)/([ V]+)/add/$' , views.add_stage),

# ...
)
, , URL /myblog/entries/add/ /th/groups/add/.

(/auth/user/add/) - ,

188

8. URL

. ,
:
def add_stage(request, app_label, model_name):
if app_label == auth and model_name == user:
tt
else:
tt

,
: URL
. , URL
:
urlpatterns = patte rns(,
tt ...

('~auth/user/add/$, views.user_add_stage),

''(['7]+)/(['7]+)/add/$', views.add_stage),
tt ...

/auth/user/add/
user_add_stage. URL
, ,
(
).



Unicode- .
, year
views.year_archive() ,
, \d {4}
, :
(1~articles/(?P<year>\d{4>)/$, views.year_archive),

.
Python
( ). -
datetime.date, :
> import datetime
>>> datetime.date(1993, 7 . 9 )
Traceback (most recent call last):
TypeError: an integer is required
> datetime.date(1993, 7, 9)
datetime.date(1993, 7, 9)

URL
:

URL:

189

# urls.
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = p a t t e r n s C ' ,

(r'~articles/(\d{4})/(\d{2})/(\d{2})/$', views.day_archive),

)
# views.py
import datetime
def day_archive(request, year, month, day):
tt TypeError!
date = datetime.date(year, month, day)

day_archive() :
def day_archive(request, year, month, day):
date = datetime.date(int(year),

int(month),

int(day))

, int() ValueError,
, -, ,
,
URL ,
, .

URL
Django
URL URL ,
Python.
GET POST, .
, URL.
, URL http://www.example.com/myapp/ Django
/,
URL http:// www.example.com/t/?page=3.
(, POST GET)
. ,
,
.


, ,
.
URL:
# urls.
from django.conf.urls.defaults import *

190

8. URL
from mysite import views
urlpatterns = p a t t e r n s C ' ,

# ...
( r ' ~somepage/$', views.some_page),

)
tt views, py

from django.http import Http404, HttpResponseRedirect


from django.shortcuts import render_to_response
def some_page(request):
if request.method == POST:
do_somethmg_for_post()
return HttpResponseRedirect(/someurl/')
elif request.method == GET:
do_something_for_get()
return render_to_response('page.html')
else:
raise Http404()

some_page() - ,
PO S T GET. URL: /somepage/.
P O S T G E T
.
GET- POST- ,
.
, ,

.
some_page():
tt views.

from django.http import Http404, HttpResponseRedirect


from django.shortcuts import render_to_response
def method_splitter(request, GET=None. P0ST=None):
if request.method == 'GET' and GET is not None:
return GET(request)
elif request.method == 'POST' and POST is not None:
return P0ST(request)
raise Http404
def some_page_get(request):
assert request.method == 'GET'
do_something_for_get()
return render_to_response('page.html')
def some_page_post(request):
assert request.method == 'POST'

URL:

191

do_something_for_post()
return HttpResponseRedirect(/someurl/')
tt urls. py

from django.conf.urls.defaults import *


from mysite import views
urlpatterns = patternsC,
tt ...
(r' ~somepage/$' , views.method_splitter,
{'GET': views.some_page_get, POST : views.some_page_post}),
tt ...

)
, .

method_splitter(),

request.method.
, GET POST,
. request.method GET,
GET. request.method POST,
POST. request.method -
(, HEAD) ( GET
POST) , Http404.

URL /somepage/
method_splitter()
: ,
GET POST .

, some_page() : some_page_get()
some_page_post(). ,
.

---------------------------------------------------------------------------------------------------- ,
request.method, method_splitter(). (
, some_page_post() request.method
POST.) - assert,
, .
.

,
request.method.
method_splitter()
, .
method_splitter() .
, , GET- POST, , request.

192

8. URL

method_splitter() ,
, , - URL
? ?

Python: ,
. , :
def method_splitter(request. *args, **kwargs):
get_view = kwargs.pop(1GET', None)
post_view = kwargs.pop(POST. None)
if request.method == GET and get_view is not None:
return get_view(request, *args, **kwargs)
elif request.method == POST' and post_view is not None:
return post_view(request, *args, **kwargs)
raise Http404

method_splitter(),
GET POST *args **kwargs ( ).

, .

, .
,
.
, , :
def foo(*args, **kwargs):
print " :"
print args
print " :"
print kwargs

:
>>> foo(1, 2, 3)
:
( 1. 2, 3 )
:

{}
> f( 1, 2, name=Adrian, framework^Django)
:
1. 2)
:
{framework: Django, name: Adrian}
(

method_splitter(). ,
*args **kwargs
.
kwargs. (),
GET POST, . (

URL:

193

() None, KeyError
, .)


, ,
Python. ,
, :
def my_view1(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(/accounts/login/)

...

return render_to_response(templatel.html)
def my_view2(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(/accounts/login/)
tt . . .
return render_to_response('template2.html')
def my_view3(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(1/accounts/login/)
tt . . .

return render_to_response(1template3.html)

,
request.user ,
. ,
/acco u n ts/lo gin /.
---------------------------------------------------------------------------------------------------- request.user - 14, -
, request.user ,
.

- ,
.
. :
def requires_login(view):
def new_view(request, *args, **kwargs):
if not request.user.is_authenticated():
return HttpResponseRedirect('/accounts/login/)
return view(request, *args, **kwargs)
return new_view

requires_login (view)
(new_view).
new_view requires_login, request.user.

8. URL

194

is _ a u th e n tic a te d () view.
i f not re q u e st.u se r.is_ a u th e n tica te d ()H 3
re q u ire s_ lo g in
URL:
from django.conf.urls.defaults import *
from mysite.views import requires_login, my_view1, my_view2, my_view3
urlpatterns = patternsC',
(r~view1/$. requires_login(my_view1)),
(r* ~view2/$, requires_login(my_view2))1
(r~view3/$, requires_login(my_view3)),

)
, .
re q u ir e s _ lo g in (),
,
.

URL
,
Django,
URL ,
.
URL
. URL,
:
from d ja n g o .c o n f. u r ls . d e f a u lt s import *
u r lp a tte rn s = p a t t e r n s C ,
( r '" w e b lo g / ', in c lu d e ( m y s it e .b lo g .u r ls ) ) ,
( r ''photos/' , in c lu d e ( m ysite. photos, u r l s ) ) ,
( r ~about/$ , m y s ite .v ie w s .a b o u t'),

)
6,
Django.
URL,
in c lu d e O .
: ,
in c lu d e O , $ (
), .
in c lu d e O , Django URL,
,
.
, m y site .b lo g .u rls:
from django.conf.urls.defaults import *

URL

195

urlpatterns = patte rns(,


(*~(\d\d\d\d)/$, mysite.blog.views.year_detai ),
(* ~(\d\d\d\d)/(\d\d)/$*, 'mysite.blog.views.month_detai ),

)
,
.

/weblog/2007/: URL ''weblog/'


URL. in c lu d e Q , Django
, w eblog/.
2007/,
m y site .b lo g .u rls.

/weblog//2007/ ( ): URL
''weblog/ URL.
in c lu d e (), Django ,
w eblog/. /2007/ ( ),
mysite. b lo g .u rls .

/about/: URL m ysite.view s.about

URL; ,
,
in clu d e Q .

indude()
URL
, :
tt root urls.

from django.conf.urls.defaults import *


urlpatterns = patternsC,
(r~(?P<username>\w+)/blog/, includeC foo. urls. blog)),

)
tt foo/urls/blog.py

from django.conf.urls.defaults import *


urlpatterns = patternsC,
(r1''S, foo. views. blog_index),
(r''archive/S* , foo. views. blog_archive),

)
username
URL , ,
, .
,
,
. -

8. URL

196

, ,
, ,
.

URL
indude()
URL
- .

.
, URL
.
:
tt urls.

from django.conf.urls.defaults import *


urlpatterns = patternsC',
(r~blog/, include(inner). {4blog id: 3}),

)
tt inner, py

from django.conf.urls.defaults import *


urlpatterns = patternsC,
(r~archive/$, mysite.views.archive),
(r"about/S, mysite.views.about),
(r'~rss/$, mysite.views.rss),

)
:
tt urls. py

from django.conf.urls.defaults import *


urlpatterns = patternsC,
(r^blog/, include(inner)),

)
tt inner, py

from django.conf.urls.defaults import *


urlpatterns = patternsC,
(r'"archive/$, mysite.views.archive, {* blog id: 3}),
(r"about/S, mysite.views.about, {blog id: 3}),
(r~rss/$, mysite.views.rss, {blog id: 3}),

197

(. ),

,
.
, , ,
,
, .

?

URL. 9
Django.

9


Django ,

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


, 4.

- , Python,
Django.
.

- ,
.
. ,
,
(, if for), -

RequestContext

199


.
{% %}:
{% if is_logged_in %}
!
{% else %}
, .
{% endif %}

- ,
.
{{ }}:
{{ first_name }}. {{ last_name }}.

- (
Python), .

,

.

. 4.

.
, 4 .

RequestContext

.
django.template.Context, Django
django.template.RequestContext,
. RequestContext
, ,
HttpRequest
.
RequestContext ,
.
, , :
from django.template import loader, Context
def view_1(request):
tt ...
t = loader.get_template('template1.html')
= Context({
'app: 'My app,

200

9.
user: request.user,
ip_address: request.META['REMOTE_ADDR],
message: - 1.'

})
return t .render(c)
def view_2(request):
tt . . .

t = loader.get_template(template2.html)
= Context({
app : My app,
user: request.user,
ip_address: request.META[REMOTE_ADDR],
message: - .

})
return t .render(c)

( ,
render_to_response(),
,
. , , .)
: , user
ip_address. .
RequestContext
.
, ,

render_to_response().
RequestContext Context.

,
RequestContext.
:
from django.template import loader, RequestContext
def custom_proc(request):
" , 'app', user 'ip_address'."
return {
'app': My app',
'user': request.user,
ip_address: request.META[REMOTE_ADDR]

}
def view_1(request):
tt . . .

t = loader.get_template(templatel.html)
= RequestContext(request, {message: ' - 1.'},
processors=[custom_proc])

RequestContext

201

return t .render(c)
def view_2(request):

. . .
t = loader.get_template(1template2.html* )
= RequestContext(request, {message: - .'},
processors=[custom_proc])
return t .render(c)

custom_proc.
- HttpRequest
, .
.

,
Context RequestContext.
. -, Request
Context , HttpRequest -
, .
-, RequestContext
processors - -
. custom_proc,
.

, ,
, user, ip_address,
custom_proc.


,
. message
.

4 render_to_
responseO, loader.get_
templateO, Context
renderQ.
,
render_to_response().
render_to_response().
context_instance:
from django.shortcuts import render_to_response
from django.template import RequestContext
def custom_proc(request):
" , 'app', 'user' and 'ip_address'."
return {
'app': My app',

9.

202

'user': request.user,
ip_address: request.META['REMOTE_ADDR]

}
def view_1(request):
tt ...
return render_to_response('templatel.html.
{'message': ' - 1.'},
context_instance=RequestContext(request, processors=[custom_proc]))
def view_2(request):
tt ...
return render_to_response('template2.html',
{'message': ' - .'},
context_instance=RequestContext(request, processors=[custom_proc]))


.
, , , ,
.
( ),
( processors).
processors, ,
.
Django .
TEMPLATE_CONTEXT_PROCESSORS ( settings.)
, RequestCon text. processors
RequestContext.
TEMPLATE_CONTEXT_PROCESSORS
:
TEMPLATE_CONTEXT_PROCESSORS = (
1django.core.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n,
'django.core.context_processors.media',

)

, custom_proc:

, . ,
TEMPLATE_CONTEXT_PROCESSORS ,
Python (
).
.
,

RequestContext

203

,
.
Django ,
.

django.core.context_processors.auth
TEMPLATE_CONTEXT_PROCESSORS ,
RequestContext :

user: django.contrib.auth.models.User,
(
Anonymousllser, ).

messages: ( )
.
request.user.
get_and_delete_messages(),
.

perms: django.core.context_processors.PermWrapper,

.

,
. 14.

django.core.context_processors.debug
.
TEMPLATE_CONTEXT_PROCESSORS ,
RequestContext :

debug: DEBUG (True False).


, ,
.

sql_queries: {sql: ..., time: ...},


SQL-,
, .
.

,

:

DEBUG True
IP -,
INTERNAL_IPS

204

9.

, debug
False, DEBUG
False, .

django.core.context_processors.i18n
, RequestContext
:

LANGUAGES: LANGUAGES.

LANGUAGE_CODE: request. LANGUAGE_CODE,


, - LANGUAGE_CODE.

. D.

django.core.context_processors.request
, RequestContext
request,
HttpRequest. , ,
.
,
HttpRequest, , IP -
:
{{ request.REM0TE_ADDR }}

.
,
,
.

, ,
TEMPLATE_CONTEXT_PROCESSORS, ,
,
,
, .
,
, , ,
.

,
, Python,
TEMPLATE_CONTEXT_PROCESSORS.

context_processors.py .

HTML

205

HTML
HTML- ,
.
, , :
, {{ name }}.

,
, , ,
:
<script>alert( hello)</script>

HTML:
, <script>alert(hello)</script>

, !
*<, :
<b>username

:
, <b>username


!
,
-,
.

(XSS)1.

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

. 20.

escape,
.
Django ,

. - ,
.


h ttp ://r u .w ik ip e d ia .o r g /w ik i/M e M c a u m o e u u _ C K p u n m u H e . - . . .

206

9.

.
, .

Django
. ,
:
< &lt;
> &gt;
( ) &#39;
( ) &quot;
& &;
, .
Django,
.



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



, safe:
: {{ data }}
: {{ data|safe }}

safe safe from fu rth er escaping (


) can be safely interpreted
as H T M L ( HTML).
, data <>,
:
: &lt;b&gt;
: <>


autoescape
.
, :

HTML

207

{% autoescape off %}
{{ name }}
{% endautoescape %}

Ter autoescape on off.


,
. :
. {{ name }}
{% autoescape off %}
: {{ data }}.
: {{ other_data }}
{% autoescape on %}
: {{ name }}
{% endautoescape %}
{% endautoescape %}

autoescape, ,
, ,
include, :
base.html

{% autoescape off %}
<h1>{% block title %}{% endblock %}</h1>
{% block content %}
{% endblock %}
{% endautoescape %}
tt child, html

{% extends "base.html" %}
{% block title %}To ce{% endblock %}
{% block content %}{{ greeting }}{% endblock %}


, ,
greeting <b>Hello!</b>,
HTML-:
<h1> ce</h1>
<>!</>

----------------------------------------------------------------------------------------------------
. , Python (
), , ,
, .
, ,
, ,
escape , .
, -

208

9.
, escape ,
.



, :
{{ data|default:" . }}


, safe.
,
, ,
.
, :
{{ data|default:"3 &lt; 2" }}

:
{{ data|default:3 < 2" }} <-- ! .

, ,
. -
,
.

-
, ,
,
.
Django :

django.template.loader.get_template(template_name): get_template
( Template)
. ,
TemplateDoesNotExist;

django. template, loader. select_template(template_name_list):


select_
template get_template,

.
.
, TemplateDoesNotExist.
4 ,
TEMPLATE_DIRS.
.

209

,
, TEMPLATE_LOADERS.
,
. Django
:

django.template.loaders.filesystem.load_template_source:
, TEMPLATE_DIRS.
;

django.template.loaders.app_directories.load_template_source:
Django .
, INSTALLED_
APPS, templates. ,
Django .
, ,
Django
. , INSTALLED_APPS (myproject.
polls, myproject.music), get_template(foo.htmr)
:

/path/to/myproject/polls/templates/foo.html

/path/to/myproject/music/templates/foo.html

,
- ,
INSTALLED_APPS, templates.
.

django.template.loaders.eggs.load_template_source:
app_directories, ,
eggs- Python, .
; ,
eggs-. (
Python Eggs - P ython
.)

Django ,
TEMPLATE_LOADERS. ,
.


, -
, ,
.

() . Django
, , ,

210

9.

. ,
.



- ,
Django.
:
1. -, , Django
.
manage. startapp,
,
. ,

.

INSTALLED_APPS. .
2. -, templatetags
Django. ,
models., views, . . :
books/
__ini t__.

models.
templatetags/
views.

templatetags :_init__. (
, , Python) ,
.
,
. ,
poll_extras.py, :
{% load poll_extras %}

{% load %} INSTALLED_APPS
,
Django. ;
,
.

,
Django, templatetags
. templatetags .
, {%load %}
, .

211

Python ,
, : .
,
register,
template. Library. ,
.
:
from django import template
register = template.Library()

---------------------------------------------------------------------------------------------------- Django.
django/template/defaultfilters.py
django/template/defaulttags.. django.contrib
.

register
.


- Python,
:

( ).

,
.

, {{ var|foo:bar }} foo
var bar.
- .
.
,
- ,
.
:
def cut(value, arg):
" arg
return value.replace(arg, ')


:
{{ somevanable|cut: }}

.
:

212

9.
def lower(value): # .
"
return value.lower()

,
Library, Django:
register.filter('cut, cut)
register.filter('lower, lower)

Library.filterQ :

()

P ython 2.4 register.filter()


:
@register.filter(name=cut)
def cut(value, arg):
return value. replace(arg,

')

@register.filter
def lower(value):
return value.lower()

name, ,
Django .
,
cut:
from django import template
register = template.Library()
@register.filter(name=cut)
def cut(value, arg):
return value.replace(arg,


,
.
4 ,
: .
, Django,
.
Django
. django.
template.Node renderQ. ,
- Node. ,
, :

213

, {{ person.name }}.
{% ifequal name.birthday today %}
!
{% else %}
He ,
.
{% endifequa1 %}

: person.name

IfEqual: name.birthday today

.\\

render()oopoaoo
renderQ Node
.
. ,
, ,
Node ( )
renderQ.


,
Python, .
Node,
.
, , {%current_time %}
,
, ,
strftime (. http://www.djangoproject.eom/r/python/strftim e/ ).
. ,
:
<> {% current_time %Y-%m-%d %1:% %" %}.</>

---------------------------------------------------------------------------------------------------- - Django {% now %}


.
.


Node:

9.

214
from django import template
register = template.Library()

def do_current_time(parser, token):


try:
tt split_contents() ,
tt .
tag_name, format_string = token.split_contents()
except ValueError:
msg = ' %r ' % token.split_contents()[0]
raise template.TempiateSyntaxError(msg)
return CurrentTimeNode(format_string[1:-1])

, :


: parser token. parser - ,
.
. token -
.

token.contents .
current_time %Y-%m-%d %1:%%.

token.split_contents() ,
, .
token.contents.split() (
Python ).
, ,
.


django.template.TemplateSyntaxError
.

,
.
token. split_contents()[0],
.

CurrentTimeNode (
), , ,
"%Y-%m-%d %1:% %.

format_string[1:-1].


Node; .


Node,
renderQ. CurrentTimeNode.

215

import datetime
class CurrentTimeNode(template.Node):
d e f _init__(self, format_string):
self.format_string = str(format_string)
def render(self, context):
now = datetime.datetime.now()
return now.strftime(self.format_string)

_init__() renderQ
( ). ,

,
renderQ.
,
, .
.


, Library
.
(. ). template.
Library tagQ:
register.tag('current_time, do_current_time)

ta g Q :

()

, Python 2.4
register.tag :
@register.tag(name=current_time")
def do_current_time(parser, token):

. . .

@register.tag
aef shout(parser, token):
tt ...

name , , Django
.



.
- . -

9.

216

,
.
- , ,
,
render().
CurrentTimeNode,
,
current_time:
class CurrentTimeNode2(template.Node):
d e f _init__(self, format_string):
self.format_string = str(format_string)
def render(self, context):
now = datetime.datetime.now()
context['current_time] = now.strftime(self.format_string)
return '

---------------------------------------------------------------------------------------------------- do_current_time2 current_time2


.

, renderQ .
,
, renderQ
.
:
{% current_time2 "%Y-%M-%d %1:% % %}
<> {{ current_time }}.</>

CurrentTimeNode2 :
current_time . ,
,
{{ current_time }}, {% current_time2 %}
.
-
:
{% get_current_time %Y-%M-%d %1:% %" as my_current_time %}
<p>The current time is {{ my_current_time }}.</p>

,
:
import re
class CurrentTimeNode3(template.Node):
d e f _init__(self, format_string, var_name):
self.format_string = str(format_string)

217

self.var_name = var_name
def render(self, context):
now = datetime.datetime.now()
context[self.var_name] = now.strftime(self.format_string)
return '
def do_current_time(parser, token):
tt
tt
try:
tt None == .
tag_name, arg = token.contents.split(None, 1)
except ValueError:
msg = 'Ter %r ' % token.contents[0]
raise template.TemplateSyntaxError(msg)
m = re.search(r'(.*?) as (\w+)', arg)
if m:
fmt, var_name = m.groups()
else:
msg = %r % tag_name
raise template.TemplateSyntaxError(msg)
if not (fmt[0] == fmt[-1] and fmt[0 ] in ( "" , .. )):
msg = %r " % tag_name
raise template.TemplateSyntaxError(msg)
return CurrentTimeNode3(fmt[1:-1], var_name)

do_current_time() CurrentTimeNode3 .


,
(, {% if %}, {% for %}).
parser.parse().
{%comment %}:
def do_comment(parser, token):
nodelist = parser.parse(('endcomment',))
parser.delete_first_token()
return CommentNode()
class CommentNode(template.Node):
def render(self, context):
return ''

parser. parse() ,
. django.template.
NodeList, Node,
, .

9.

218

, nodelist -
{%comment %} {%endcomment %}, .
parser.parse() {%
endcomment %}, parser.delete_first_
token(), .
CommentNode. render() .
{%comment %} {%endcomment %} .



do_comment() ,
{%comment %} {%endcomment %}.
- ,
.
{%upper %},
,
{%endupper %}:
{% upper %}
, {{ user_name }}.
{% endupper %}

, parser.parseQ.
nodelist Node:
def do_upper(parser, token):
nodelist = parser.parse(('endupper,))
parser.delete_fi rst_token()
return UpperNode(nodelist)
class UpperNode(template.Node):
d e f _init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
output = self.nodelist.render(context)
return output.upper()

UpperNode. render()
self.nodelist, render(context), renderQ
.

{%if %}, {%for %}, {%ifequal %} {%ifchanged
%}, django/template/defaulttags.py.


-
-

219

, -
. , current_
time. , ,
.
, Django
simple_tag, django.
template. Library. ,
render, ,
,
.
current_time
:
def current_time(format_string):
try:
return datetime, datetime. now(). strftime(str( format_stnng))
except UnicodeEncodeError:
return '
register. simple_tag(current_time)

Python 2.4
:
@register.simple_tag
def current_time(token):

. . .
, simple_tag:


, .

( ) ,
Unicode.


, -
. ,
Django ,
/ .
,
.
,
.
.
. , -

220

9.

Author.
:
{% books_for_author author %}

:
<ul>
<> </>
<>-</>
< > 0 </>
</ul>

,
. ,
, - .
:
def books_for_author(author):
books = Book.objects.filter(authors__id=author.id)
return {books: books}

,
. :
<ul>
{% for book in books %}
<li>{{ book.title }}</li>
{% endfor %}
</ul>

, ,
inclusion_tag() Library.
, book_snippet.html,
:
register.inclusion_tag(book_snippet.html)(books_for_author)

Python 2.4 ,
:
@register.inclusion_tag(book_snippet.html)
def books_for_author(author):
tt ...


.
, Django takes_context
. ,
,
- ,
.

221

, , ,
,
home_link home_title, .
Python :
@register.inclusion_tag(link.html', takes_context=True)
def jump_link(context):
return {
link: context[home_link],
title: context[home_title'],

}
---------------------------------------------------------------------------------------------------- context.

link, html :
< href={{ link }}>{{ title }}</>.


:
{% jump_link %}


Django (
- )
, ,
- . ,
,
Subversion, Subversion
Python, ( ) ZIP-.
( TEMPLATE,
LOADERS) - :
load_template_source(template_name, template_dirs=None)

template_name - ( ,
loader.get_template() loader.select_
templateQ), a template_dirs - ,
TEMPLATE_DIRS.
,
(template_source, template_path). template_source -
, ,
a template_path - , .
.

222

9.

,
django. template.TemplateDoesNotExist.
is_usable.
, ,
Python. ,
eggs- is_usable False,
pkg_resources,
eggs-.
.
ZIP-. TEMPLATE_DIRS
TEMPLATE_ZIP_FILES,
, ,
ZIP- .
from django.conf import settings
from django.template import TemplateDoesNotExist
import zipfile
def load_template_source(template_name, template_dirs^None):
ZIP-.
template_zipfiles = getattr(settings, TEMPLATE_ZIP_FILES, [])
tt ZIP- TEMPLATE_ZIP_FILES.

for fname in template_zipfiles:


try:
z = zipfile.ZipFile(fname)
source = z.read(template_name)
except (IOError, KeyError):
continue
z.close()
tt , .
template_path = %s:%s" % (fname, template_name)
return (source, template_path)
tt ,

raise TemplateDoesNotExist(template_name)
tt (. . zipfile
tt Python)

load_template_source.is_usable = True

,
TEMPLATE_LOADERS. ,
mysite.zip_loader, TEMPLATE_LOADERS
mysite. zip_loade.load_template_source.

223



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

Django
,
, DJANG0_
SETTINGS_MODULE. (
Python 4.)
Django,
, , ,
,
-
.

, D.
,
, , - ,
, django.conf.settings.configureQ,
.

TEMPLATE_DIRS (
), DEFAULT_CHARSET (
utf-8 ) TEMPLATE_DEBUG.

D; ,
TEMPLATE,.

?

Django.

10

5 Django , API ,
, .
Django.


,
, 5.
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)
e-mail = models.E-mailField()
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)

225

publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
def _Unicode __(self):
return self.title

5,
. ,
50, :
> from mysite. books, models import Book
> b = Book.objects.get(id=50)
> b.title
uThe Django Book

, , ,
ForeignKey ManyToManyField,
.


ForeignKey
. :
> b = Book.objects.get(id=50)
> b. publisher
<Publisher: Apress Publishing>
> b. publisher, website
uhttp://www.apress.com/

ForeignKey API
,
. ,
, publisher. book_set.all():
> = Publisher.objects.get(name=Apress Publishing)
> p.book_set.all()
[<Book: The Django Book>, <Book: Dive Into Python>, ...]

book_set - QuerySet (. 5),



, :
> = Publisher.objects.get(name=Apress Publishing)
> p.book_set.filter(name__icontains=django)
[<Book: The Django Book>, <Book: Pro Django>]

book_set _set
, .

--
-- ,
,

226

10.

, QuerySet. , ,
:
> b = Book.objects.get(id=50)
>>> b.authors.al1()
[<Author: Adrian Holovaty>, <Author: Jacob Kaplan-Moss>]
> b. authors, filter(first_name=Adrian)
[<Author: Adrian Holovaty>]
> b. authors. filter(first_name=Adam)

[]
.
, ,
author.book_set:
>>> = Author.objects.get(first_name=Adrian, last_name=Holovaty)
> a. book_set. al 1 ()
[<Book: The Django Book>, <Book: Adrians Other Book>]

ForeignKey, book_set
_set ,
.


5, syncdb, ,
, ,
.
,

. ,
.

Django.

Django , ,
.
API
( , ).

Django , ,
.

Django , ,
.

-
Python - . ,
.

227



, Django
, .
, ,
.
- ,
SQL,
manage. sqlall,
, . (,
SQL,
Django, .)
,
, . (
, ?)
.
:
1. .
2. manage. sqlall [ ]
CREATE TABLE .

, .
3. (, psql mysql,
manage. dbshell).
ALTER TABLE.

4. Python manage,
shell , .
(
, MyModel.objects.all()[:5]). ,
.
:
1. .
2. ALTER TABLE,

.
3. .
1
,

( Subversion svn update).
4. -, .

10.

228

num_pages
Book 5. :
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
num_pages = models.IntegerField(blank=True, null^True)
def _unicode__(self):
return self.title

---------------------------------------------------------------------------------------------------- , blank=True null=True,


6
NOT NULL.

NOT NULL
.
num_pages blank=True
null=True,
NULL .

, NULL.
NULL,
- , ,
, NOT NULL.
:
ALTER TABLE books_book ADD COLUMN num_pages integer;
UPDATE books_book SET num_pages=0;
ALTER TABLE books_book ALTER COLUMN num_pages SET NOT NULL;
COMMIT;

,
blank=True null=True .

manage. sqlall
CREATE TABLE. (
):
CREATE TABLE books_book (
"id serial NOT NULL PRIMARY KEY,
"title varchar(IOO) NOT NULL,
"publisher_id integer NOT NULL REFERENCES books_publisher (id),

229

"publication_date date NOT NULL,


num_pages integer NULL

);
:
num_pages integer NULL

,
psql ( PostgreSQL) :
ALTER TABLE books_book ADD COLUMN num_pages integer;

ALTER TABLE, , .
Python :
> from mysite.books.models import Book
> Book.objects.al 1 ()[:5]

,
ALTER TABLE.
-.


, .
:
1. -.
2. , ,
ALTER TABLE books_book DROP COLUMN num_pages;

.
, Django .

--
, --,
, .
1. ManyToManyField
-.
2. ,
DROP TABLE books_book_authors;

, .


, .
:

230

10.

1. models, -.
2. ,
DROP TABLE books_book;

,
, , books_book
.
, .

Book.objects.all() objects - ,
. 5
, .
,
.
, - ,
Django . Django
,
.

:
/
QuerySet, .


-
.
,
. (
, ,
, ,
.)
, Book title_
countQ,
, . (
, .)
# models.
from django.db import models
tt . .. Author Publisher .. .

class BookManager(models.Manager):
def title_count(self, keyword):

231
return self.filter(title_icontains^keyword).count()

class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
num_pages = models IntegerField(blank-True, null^True)
objects = BookManager()
def __unicode__(self):
return self.title

,
:
> Book.objects. title_count( django)
4
> Book.objects. title_count( python)
18

BookManager, django.db.
models.Manager. title_count(),
. self, filter(),
self - .

BookManagerQ objects .
,
objects ,
. objects, - ,
.

, title_count()?

.

QuerySet
QuerySet, ,
, . , Book.objects.all()
.
QuerySet ,
Manager.get_query_set(). QuerySet,
.
, -
, .
from django.db import models
# Manager,
class DahlManager(models.Manager):

232

10.
def get_query_set(self):
return super(DahlManager, self).get_query_set().fi1ter(
author^'Roald Dahl')
tt Book.

class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
tt ...
objects = models.Manager()
tt .
dahl_objects = DahlManager() tt .

Book.objects.all() ,
Book.dahl_objects.all() - ,
. , objects
Manager,
dahl_objects.
, get_query_set() QuerySet,
filter(), excludeO
QuerySet.
:
Book.dahl_objects.all()
Book.dahl_objects.filter(title='Matilda')
Book.dahl_objects.count()

:
.
ManagerQ.
,
.
.
class MaleManager(models.Manager):
def get_query_set(self):
return super(MaleManager, self).get_query_set().filter(sex=M )
class FemaleManager(models.Manager):
def get_query_set(self):
return super(FemaleManager, self).get_query_set().filter(sex='F)
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
sex = models.CharField(max_length=1, c h oi ce st(M '. Male'),
(F. Female)))
people = models.Manager()
men = MaleManager()
women = FemaleManager()

Person.men.all(), Person.women.allQ
Person.people.all() .

233

, ,
, . Django ,
(
) .
, ,
, get_query_
set( ) , .




.
,
.
-
, .
. ,
:
from django.contrib.localflavor.us.models import USStateField
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
birth_date = models.DateField()
address = models.CharField(max_length=100)
city = models.CharField(max_length=50)
state = USStateField() # , ...
def baby_boomer_status(self):
.. , ,
...
import datetime
if datetime.date(1945, 8, 1) <= self.birth_date \
and self.birth_date <= datetime.date(1964, 12, 31):
return "Baby boomer"
if self.birth_date < datetime.date(1945, 8, 1):
return "Pre-boomer"
return "Post-boomer"
def is_midwestern(self):
" True, ."
return self.state in (1IL', 'WI', 'MI', 'IN', 'OH', 'IA\ 'MO')
def _get_full_name(self):
" ."
return u'%s %s' % (self.first_name, self.last_name)
full_name = property(_get_full_name)

234

10.

. (
http://www.python.org/download/
releases/2.2/descrintro/#property)1. :
>>> = Person.objects.get(first_name=Barack', last_name='Obama')
>>> p.birth_date
datetime.date(1961, 8, 4)
> p. baby_boomer_status()
Baby boomer'
> p. is_midwestern()
True
> p.full_name tt ,
#
u'Barack Obama'

SQL-
Django
,
SQL-.
django.db.connection,
. , connection.
cursor() -, cursor.execute(sql,
[params]) - SQL- , ,
cursor.fetchoneO cursor.fetchall() . :
> from django.db import connection
> cursor = connection. cursor()
> cursor.execute(..
SELECT DISTINCT first_name
FROM people_person
WHERE last_riame = %s.. , ['Lennon'])
> row = cursor.fetchoneO
> print row
['John' ]

connection cursor Python


API ,
http://www.python.org/peps/pep-0249.html2. ,
API , , SQL- cursor.
e x e c u t e O , %s",
SQL-.

http://www.ibm.com/developerworks/ru/library/l-python-elegance-2/. - .
. .
2
http:// www.intuit./department/1/python/10/. - . . .

235

, A PI ,
.

django.db.connection,
. ,
:
from django.db import connection, models
class PersonManager(models.Manager):
def first_names(self, last_name):
cursor = connection.cursor()
cursor.execute(..
SELECT DISTINCT first_name
FROM people_person
WHERE last_name = %s.. , [last_name])
return [row[0] for row in cursor.fetchone()]
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
objects = PersonManager()

:
> Person.objects.first_names('Lennon' )
['John, Cynthia']

?

,
.

11

,
: -
. ,
Django
, -
.
,
.
,
.
, ,
.
8
. , , ,
,' ,
. ,
, URL .
Django :

:
;


. event_list entry_list 8 .
- .


, .
.
Django (http://www.djangoproject.

237

com/weblog/) , .
.

,
.



URL
, URL. (

8.)
URL,
:
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
urlpatterns = patternsC',
(r"about/S', direct_to_template,
template: about.html'

})
)

- , ! -
8. direct_to_
template
.
( )
,
.
, URL /about/<whatever>/
about/<whatever>.html.
URL, URL,
:
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from mysite.books.views import about_pages
urlpatterns = patternsC,
(r"about/S, direct_to_template,
template: about.html

}),
(r~about/(\w+)/$', about_pages),

)
about_pages:

11.

238

from django.http import Http404


from django.template import TemplateDoesNotExist
from django.views.generic.simple import direct_to_template
def about_pages(request, page):
try:
return direct_to_template(request, template=about/%s.html % page)
except TemplateDoesNotExist:
raise Http404()

direct_to_template
.
HttpResponse,
. , ,
. ,
,
TemplateDoesNotExist 404.

?
, ,
:
, (template-about/%s.html % page).
,
( 20).
?
. ,
,
, URL. ,
URL,
URL, \w+, a \w
1. (
) ,
.


direct_to_template, , , ,
.
, Django
,
.
1

, , ,
, . - . ..

239

:
. Publisher 5.
class Publisher(nodels.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]


URL:
from django.conf.urls.defaults import *
from django.views.generic import list_detail
from mysite.books.models import Publisher
publisher_info = {
queryset: Publisher.objects.al1(),

}
urlpatterns = patternsC',
(r~publishers/$, list_detail.object_list, publisher_info)

)
Python .
. object_list
, template_name ,
:
from django.conf.urls.defaults import *
from django.views.generic import list_detail
from mysite.books.models import Publisher
publisher_info = {
'queryset': Publisher.objects.al1(),
'template_name: publisher_list_page.html',

}
urlpatterns = patternsC',
(r'^publishers/S, list_detail.object_list, publisher_info)

)
template_name object_list
.
books/publisher_list.html, books

240

11.

, , publisher , .
,
object_list, publisher.
:
{% extends "base.html %}
{% block content %}
<2></12>
<u 1>
{% for publisher in object_list %}
<1i>{{ publisher.name }}</li>
{% endfor %}
</ul>
{% endblock %}

( , base.html,
4.)
.
, info.
.

.


,
.
, .
,
.
,
.
.


, , ,
object_list.
,
: ,
.
publisher_list, .
template.
object_name:
from django.conf.urls.defaults import *

241

from django.views.generic import list_detail


from mysite.books.models import Publisher
publisher_info = {
'queryset: Publisher.objects.al1(),
*template_name: 'publisher_list_page.html',
'template_object_name: 'publisher,

}
urlpatterns = patternsC,
(r'''publishers/!, list_detail.object_.list, publisher_info)

)
, ,
_list template_object_name.
template_object_name ; ,
, .


,
. , ,

. object_detail
,
, , .
:
extra_context. ,
. ,
,
:
publisher_info = {
queryset: Publisher.objects.all(),
template_object_name: publisher,
extra_context: {publisher_list: Publisher.objects.al1()}

}

{{ publisher_list }}.
.
. ,
?
, extra_context
. Publisher.objects.
all() URL,
( ).

242

11.

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

- ext ra_context
. extra,
context ( ),
( -
). :
def get_publishers():
return Publisher.objects.all()
publisher_info = {
'queryset1: Publisher.objects.all(),
'template_object_name: 'publisher',
'extra_context': {publisher_list: get_publishers}

}
, -
, Publisher.objects.all
:
publisher_info = {
'queryset': Publisher.objects.all(),
'template_object_name: 'publisher',
'extra_context: {'publisher_list: Publisher.objects.all}

}
Publisher.objects, all.
, , (
).


queryset,
. ,
( QuerySet .
5, - ).
,
:

243

book_info = {
queryset: Book.objects. rder_by('-publication_date),

}
urlpatterns = patternsC',
(r' ''publishers/I' , list_detail.object_list, publisher_info),
(r'~books/$, list_detail.object_list, book_info),

)
, .
, ,
. ,
:
apress_books = {
'queryset': Book.objects.filter(publisher__name='Apress Publishing' ),
'template_name: 'books/apress_list.html'

}
urlpatterns = patternsC',
(r'''publishers/!', list_detail.object_list, publisher_info),
(r* ''books/apress/S', list_detail.object_list, apress_books),

)
, , queryset,
.
, ,
, , .
,
.
,
URL,
.
.




, URL.
URL,
, ,
? ,
object_list
. ,
URL:
urlpatterns = patternsC ,
(*"publishers/!, 1ist_detai1.object_list, publisher_info),
(r"books/(\w+)/$', books_by_publisher),

244

11.

books_by_publisher:
from django.shortcuts import get_object_or_404
from django.views.generic import list_detail
from mysite.books.models import Book, Publisher
def books_by_publisher(request, name):
tt ( , 404).

publisher = get_object_or_404(Publisher, name__iexact=name)


tt object_list.

return 1ist_detai1.obj ect_list(


request,
queryset = Book.objects.filter(publisher=publisher),
template_name = 'books/books_by_publisher.html,
template_object_name = 'book',
extra_context = {publisher: publisher}

)
,
- Python.
,
HttpResponse.
, ,

( , . ) .
---------------------------------------------------------------------------------------------------- ,
extra_context.
, ,
.


,
.
, Author last_accessed,
, -
. ,
object_detail ,
.
URL,
author_detail:
from mysite.books.views import author_detail
urlpatterns = patternsC',
tt . ..

245

(1"authors/(?P<author_id>\d+)/$', author_detail),
tt ...

)
:
import datetime
from django.shortcuts import get_object_or_404
from django.views.generic import list_detail
from mysite.books.models import Author
def author_detail(request, author_id):
tt
tt HttpResponse.
response = 1ist_detai1.object_detail(
request,
queryset = Author.objects.al1(),
object_id = author_id,

)
tt . **.
tt object_detail(),

tt Author. ( ,
tt object_detail() Http404
tt . )
now = datetime.datetime.now()
Author.objects.filter(id=author_id).update(last_accessed=now)
return response

------------------------------------------------------------------------------------------------ , last_accessed
Author books/author_detail.html.

,
.

, :
def author_list_plaintext(request):
response = list_detail.object_list(
request,
queryset = Author.objects.all(),
mimetype = 'text/plain',
template_name = 'books/author_list.txt

)
response["Content-Disposition] = "attachment; filename=authors.txt
return response

,
HttpResponse, ,
HTTP-. , Content-Disposition -

11.

246

,
.

?
,
Django,
.
,
, .
,
.
Django.

12
Django

Django: .
, , ,
(runserver),
( -).
,
.
Django -,
, Apache. , ,
,
.



,
-, Django

. .


django-admin.py startproject,
2, settings.,
DEBUG True. Django
.
, DEBUG True:


django.db.connection.queries. ,
!

248

12. Django

404
(. 3),
404. ,
.

(
Python, , )
, , ,
.
.

, DEBUG True, Django ,


, .
, , ,
,
DEBUG False.


TEMPLATE_DEBUG
False, Django

.

404
DEBUG True, Django
404. DEBUG
False, :
404.html, .
, ,
Page not found (
).
404.html,
.
, base.html
title content:
{% extends base.html %}
{% block title %} {% endblock %}
{% block content %}
<11> </111>
<>, .</>
{% endblock %}

, 404.html,
DEBUG False -

249

URL. ( ,
.)

500
, DEBUG False, Django

.
500. html. 404. html,
.
500.html
. ,
,
,
. (
, .)
,
.
.
500. html:
<!D0CTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtdM>
<html lang="ru">
<head>
<title>CTpaHHua < >

</head>
<body>
<1> </11>
<>, -
.</>
<> , , , .</>
</body>
</html>


, , ,
. Django

,
- .
-, ADMINS ,
, .
(name, email),
:

250

12. Django
ADMINS = (
( , jlennon@example.com),
( , pmacca@example.com),

)
-, ,
. postfix, sendmail
, Django
EMAIL_HOST
. localhost ,
.
, ,
EMAIL_HOST_USER, EMAIL_HOST_PASSWORD, EMAIL_PORT
EMAIL_USE_TLS. , EMAIL_SUB JECT_PREFIX , Django
. [Django].


CommonMiddleware (, MIDDLEWARE_
CLASSES django.middleware.common.CommonMiddleware,
),

Referer,
.
, SEND_BROKEN_LINK_EMAILS True (
False), MANAGERS
, .
MANAGERS , ADMINS, :
MANAGERS - (
( , gharrison@example.com),
( , ringo@example.com),

)
, ,
.



settings,
, django-admin.py startproject.
, , ,
,
. (,
DEBUG False True ,

251

.) Django
, .

:

(, )
(, ),
.

,
Python,
.

.
, ,
.
, settings, .
settings_production.py ( ).
DEBUG .
, .
,
, . :
tt settings,

DEBUG = True
TEMPLATE_DEBUG - DEBUG
DATABASE_ENGINE = 'postgresql_psycopg2
DATABASE_NAME = 'devdb
DATABASEJJSER =
DATABASE_PASSWORD = 1
DATABASE_PORT =
U

...

tt settings_production.py

from settings import *


DEBUG - TEMPLATE_DEBUG - False
DATABASE_NAME = production
DATABASEJJSER - app
DATABASE_PASSWORD = letmein

settings_production.py settings.,
,
.
DEBUG False,
. ( ,
, DEBUG.)

252

12. Django

,
,
. ,
:
# settings.
import socket
if socket.gethostname() == 'my-laptop':
DEBUG = TEMPLATE_DEBUG - True
else:
DEBUG = TEMPLATE_DEBUG = False
U

...

socket Python
, .
- , -
P ython. ,
. . ,
.
Django.

settings.
settings. : settings_
dev.py, settings/dev. foobar.py. Django ,
, .
, settings.,
django-admin.py startproject, , manage.
,
. ,
settings. ,
manage.,
, django-admin.py
manage.. DJANGO_SETTINGS_MODULE Python
(, mysite.settings).

DJANGO_SETTINGS_MODULE
, ,
, ,
Apache. ,
: - DJANG0_
SETTINGS_MODULE - Django.

Django Apache mod_python

253

, , ,
URL R00T_URLC0NF,
.
DJANGO_SETTINGS_MODULE - Python
. , , mysite
Python, DJANGO_SETTINGS_MODULE
mysite. settings.

Django Apache
mod_python
- Apache m od_python
Django.
mod_python (http://www.djangoproject.eom/r/mod_python/ ) -
Apache , Python
- Python
. , Apache
,
.
Django Apache 2.x m od_python 3.x.
---------------------------------------------------------------------------------------------------- Apache ,
. , ,
Apache , .
, .

Apache
http://www.djangoproject.com//apache/docs/.

http://www.djangoproject.com/rlbooks/pro-apache/
(Peter
W ainwright) Pro Apache (Apress, 2004).

http://oreilly.com/catalog/9780596002039/
(Ben Laurie)
(Peter Laurie) Apache: The Definitive Guide,
(OReilly, 2002).


Django m od_python, ,
Apache.
, Apache
LoadModule, :
LoadModule pythonjnodule /usr/lib/apache2/rnodules/mod_python. so

254

12. Django

Apache
<Location>, Django
URL-:
<Location " / " >
SetHandle python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonDebug Off
</Location>

mysite.settings DJANGO_SETTINGS_MODULE
, .
Apache: mod_
python URL, / ,
Django. m od_python
DJANGO_SETTINGS_MODULE, ,
.
, <Location>,
<Directo>.
, <Location> URL -.
<Directory> .
, Apache ,
sys. path , .
m od_python, Django.
PythonPath [///', ///django] + sys.path


, PythonAutoReload Off. .
m od_python.

PythonDebug Off. ,
mod python ( )
Python.
Apache (
, <VirtualHost>)
Django.

Django
Apache
Django
Apache. ,
-, ,
.

Django Apache mod_python

255


VirtualHost:
NameVirtualHost *
<VirtualHost *>
ServerName www.example.com
ft . . .

SetEnv DJANGO_SETTINGS_MODULE mysite.settings


</VirtualHost>
<VirtualHost *>
ServerName www2.example.com

. . .
SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings
</VirtualHost>

Django
VirtualHost, ,

- m od_python.
Pythonlnterpreter <Location>
.
<VirtualHost *>
ServerName www.example.com
tt . . .

<Location Vsomething>
SetEnv DJANG0_SETTINGS_M0DULE mysite.settings
Pythonlnterpreter mysite
</Location>
<Location '7otherthing">
SetEnv DJANG0_SETTINGS_M0DULE mysite.other_settings
Pythonlnterpreter mysite_other
</Location>
</VirtualHost>

Pythonlnterpreter , ,
Location.

mod_python
m od_python Python,
Django-
Apache. ,
: Apache
MaxRequestsPerChild 1,
.
, , Django.
,
, print ( ,

256

12. Django

), , m od_python
; , ,
Apache. -
,
Python. . http://docs.python.
org/lib/module-logging.html.

Django
Apache
Django
, -.
- ( ,
Django). .
.
,
, Django,
m od_python , :
<Location ,,/media/,,>
SetHandle None
</Location>

/media/ Location URL


.
<LocationMatch>
. , ,
Django, media
URL, .jpg, .gif .png:
<Location 7 " >
SetHand1 python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
</Location>
<Location Vm ed ia />
SetHandler None
</Location>
<LocationMatch \-(jpgIQifIpng)$>
SetHandler None
</LocationMatch>

DocumentRoot,
Apache , .

Django Apache mod_python

257


A pache/m od_python
Django, Apache
_1.
Django.
,
Internal Server Error ( ), _
log ,
Python. . (,
,
m od_python.)


Django Apache
. ,
Django:

pyexpat (
XML), ,
Apache. . Expat Causing
Apache Crash http://www.djangoproject.eom/r/articles/
expat-apache-crash/.

, , Apache
m od_python mod_php,
MySQL. m od_python
- MySQL
Python. . FAQ
mod_python http://www.djangoproject.eom/r/articles/php-mod~
python-faq/.

m od_python ,
m od_python
Django. ,
m od_python. G etting m od_python
Working http://www.djangoproject.eom/r/articles/getting-mod~
python-working/.
- ,
Django: , ,
URL, RSS . .

. , ,
Django. ,
; ,

258

12. Django

. , .

,
ldconfig Linux, otool Mac ListDLLs ( Syslnternals)
Windows.

: mod_wsgi
m od_python
mod_wsgi (ihttp://code.google.eom/p/modwsgi/ ),
m od_python Django.
, Django.

Django FastCGI
Django Apache + m od_python
, ,
FastCGI.
, FastCGI
, m od_python.
FastCGI
, Apache.

FastCGI
FastCGI - ,
-. -
( ) FastCGI,
,
.
m od_python, FastCGI ,

. m od_python FastCGI-
-, , .
Django FastCGI,
flup - Python FastCGI.
, flup

,
SVN. f lup http://
www.diangoproiect.com/rljlupl.

Django FastCGI

259

?
Apache mod_*
( ,
, Python/m od_python Perl/m od_perl)
-.
(
),
.
Apache
, Django .
FastCGI
Python Django.
FastCGI
- , -.
,
.

FastCGI-cepeepa
FastCGI -,
FastCGI . -
(Apache, lighttpd - ) DjangoFastCGI ,
. ,
.
---------------------------------------------------------------------------------------------------- , ,
FastCGI-, -.
Django Apache
.

- FastCGI- :
UNIX- ( W in32 )
TCP-. ,
TCP- -
.
, (,
manage, ) manage. runfcgi:
/manage. runfcgi []

260

12. Django

runfcgi help,
.
socket,
- host port. -
/
FastCGI.
.

-:
./manage. runfcgi method=threaded host=127.0.0.1 port=3033

UNIX-:
./manage. runfcgi method=prefork
socket=/home/user/mysite.sock pidfile=django.pid

(
):
./manage. runfcgi daemonize=false socket=/tmp/mysite.sock

FastCGI
, ,
Ctrl+C.
UNIX k ill.
manage, runfcgi pidfile,
FastCGI :
kill 'cat $PIDFILE1

SPIDFILE

- pidf ile .

FastCGI UNIX,
:
#!/bin/bash
# .
PROJDIR=/home/user/myproject
PIDFILE=$PROJDIR/mysite.pid
S0CKET=$PR0JDIR/mysite.sock
cd $PR0JDIR
if [ -f SPIDFILE ]; then
kill cat-SPIDFILE'
rm -f SPIDFILE
fi

: ! - . .

Django FastCGI

261

exec /usr/bin/env - \
PYTHONPATH=../python:.. \
./manage.py runfcgi socket=$SOCKET pidfile=$PIDFILE

Django Apache FastCGI


Django Apache + FastCGI,
Apache m o d fa s tc g i. ,
http://www.djangoproject.
com/r/m od_fastcgi/.
, Apache,
Django FastCGI, httpd.
conf. :


FastCGI-cepeepa.

FastCGIExternalServer

mod_rewrite

URL FastCGI.

FastCGI-cepeepa
FastCGIExternalServer Apache,
FastCGI-. (http://www.djangopr0ject.c0m /r/m 0d_fastcgi/FastCG IExternalServer/),
: socket host. :
# FastCGI UNIX-/ :
FastCGIExternalServer /home/user/publ1c_html/myslte.fegi ^
-socket /home/user/mysite.sock
# FastCGI TCP-,
# /:
FastCGIExternalServer /home/user/publlc_html/mysite.fcgl -host
127.0.0.1:3033

/home/user/public_html/,
/home/user/public_html/mysite.fcgi .
URL, - , , , URL FastCGI (. ).

mod_rewrite
URL FastCGI
Apache, URL
FastCGI-. mod_rewrite
URL,
, mysite.fcgi ( URL,
FastCGIExternalServer, ).

262

12. Django

, Apache FastCGI URL, ,


/media/. , ,
, Django:
<Vi rtualHost 12.34.56.78>
ServerName example.com
DocumentRoot /home/user/public_html
Alias /media /home/user/python/django/contrib/admin/media
RewriteEngine On
RewriteRule "/(media.*)$ /$1 [QSA.L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule "/(.*)$ /mysite.fcgi/$1 [QSA.L]
</Vi rtualHost>

FastCGI lighttpd
lig httpd (http://www.djangoproject.eom/r/lighttpd/) -
-,
. FastCGI,
,
, ,
Apache.
, mod_f astcgi mod_
rewrite mod_access, mod_accesslog.
, ,
mod_alias.
lighttp d :
server.document-root = /home/user/public_html
fastcgi.server = (
/mysite.fcgi" => (
"main => (
tt TCP fastcgi host / port socket
tt host => 127.0.0.1,
tt port => 3033,
socket" => /home/user/mysite.sock,
check-local => disable,

)
).
)
alias.url = (
"/media/ => /home/user/django/contrib/admin/media/,

)
url.rewrite-once = (
"(/media.*)$ => $1,
"Vfavicon\. ico$ => /media/favicon, ico,
''(/.*)$ => "/mysite. fcgi$1,

Django FastCGI

263

Django-
lighttpd
lighttpd ,
.
FastCGI-,
, :
tt www.example1.com. ..

$[host] == www.example1.com {
server.document-root = "/foo/site1
fastcgi.server = (

)
}
tt www.example2.com...

$HTTP[host] == www.example2.com {
server.document-root = "/foo/site2"
fastcgi.server = (

)
}

Django,
fastcgi.server. Django FastCGI.

Django Apache


-, httpd.conf.
Django ,
-.
---------------------------------------------------------------------------------------------------- , -,
FastCGI- . Apache
, .


:
AddHandler fastcgi-script .fcgl
RewriteEngine On

.htaccess

264

12. Django
RewriteCond %{REQUEST_FILENAME> !-f
RewriteRule "(.*)$ mysite.fcgi/$1 [QSA.L]

,
Apache, FastCGI-.
mysite.fcgi,
:
#!/usr/bin/python
import sys, os
tt Python.

sys.path.insert(0, "/home/user/python)
tt .

(.)

tt os. chd i (/home/use r/myp ject")


tt DJANG0_SETTINGS_M0DULE.

os.environ[DJANG0_SETTINGS_M0DULE] = myproject.settings
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method=threaded, daemonize=false)


Python-
FastCGI-. Apache .
mysite.fcgi (
), . ,
, Apache Django.
UNIX,
touch:
touch mysite.fcgi

Django , ,
Django .
,
.
,
,
.
, , , , .
,
Apache + mod python.

FastCGI, Apache.

265


,
, . 12.1.

. 1 2 .1 . D ja n g o


- Django 3000 .

.
-
,
, . .,
.

, .


Django
: IP -
DATABASE_HOST.
IP -,

DNS, .
,
. 12.2.

266

12. Django

.1 2 . 2 .

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


:
,
.
,
.

, ,
Django (. 12.3).
-,

. lighttpd tux (http://
www.djangoproject.com/r/tux/), Apache
.

267

Django

>

. 1 2 .3 .

(,
. .) ;
.
.
, Django

.
, ,
.



, .
,
10 .
,
.
. . 12.3 -
, .

, .
, ,
-.
Django- -
Apache.

268

12. Django


- .


.
mod_proxy Apache - ,
Perlbal (http://www.djang0pr0ject.c0m/r/perlbal/ ).
-,
Memcached (. 15).
--------------------------------------------------------------------------------------------------- FastCGI ,
- , FastCGI- -
.
, FastCGI- ,
Apache/mod_python/Django.

-
, . 12.4.

. 1 2 .4 .

, -
, , -

269

. ,
- ,
.

,
. MySQL
, PostgreSQL
Slony (http://www.djangoproject.eom/r/slony/)
pgpool (http://www.djangoproject.eom/r/pgpool/),
.

,

DNS-.

,

.

,
-.

- ,
.


. 12.5.

Perlbal

Perlbal

Perlbal

> t : >

* ^



Django

Django

Django

Memcached

Memcached

. 12.5. Django
- ,
.

12. Django

270


,
, .

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

, - , ,
, , .

Django,
.

Django , .


.
, ,
.
;
90% -
/. ,
.
, ,
.

. ,
, .
; - ,
,
2 .
-.
- . ,
.

Keep-Alive
Keep-Alive - HTTP
TCP-,
.

271

, ,
Django-.

, , ,
Django .
HTTP- ,
,
.

Memcached
Django ,
Memcached.
,
- Memcached.

Memcached
, Memcached , .
15; ,
Django, , .
- ,
.


Django, Linux, Apache, PostgreSQL MySQL, . -
,
.
.
Django.
-
Django.
.

?
Django,
.
.

Ill
Django

13
,
HTML
, , HTML. HTMLeM .
: RSS,
PDF, . .
HTML -
,
, Django
.
Django
:

RSS/Atom.

( XML,
Google
).

, .

: MIME
(. 3), -
Python, - -.
HTML- , , 404,
XML-, , .
, Django :

HttpRequest .

HttpResponse.

276

13. , HTML

, HTML,
HttpResponse, , mimetype.
MIME .
, , ,
PNG. , ,
.
from django.http import HttpResponse
def my_image(request):
image_data = open("/path/to/my/image.png, "rb").read()
return HttpResponse(image_data, mimetype=image/png)

! (),
,
.
, HttpResponse
API,
. , ,
Python ( ) .
, ,
CSV- Django.

CSV
CSV - ,
. , ,
(CSV comma-separated
values, , ). , ,
CSV:
,
1995.146
1996,184
1997,235
1998,200
1999,226
2000,251
2001,299
2002,273
2003,281
2004,304
2005,203
2006,134
2007.147

---------------------------------------------------------------------------------------------------- .
.

CSV

277

CSV ,
.
CSV, -
. , P ython
csv ,
.
csv , API
, HttpResponse:
import csv
from django.http import HttpResponse
tt 1995 2007.
tt , ,
tt .

UNRULY_PASSENGERS = [146,184,235,200,226,251,299,273,
281,304,203, 134, 147]
def unruly_passengers_csv(request):
tt HttpResponse ,
tt CSV.
response = HttpResponse(mimetype=text/csv)
response['Content-Disposition] = 'attachment; filename^unruly.csv
tt CSV, HttpResponse ,
writer = csv.writer(response)
writer.writerow([Year, Unruly Airline Passengers])
for (year, num) in zip(range(1995, 2007), UNRULY_PASSENGERS):
writer.writerow([year, num])
return response

,
.

MIME text/csv (
text/html). ,
CSV.

Content-Disposition,
CSV-. (, )
, ,
. ,
.

HttpResponse ,

.

API CSV response


writer,
, a HttpResponse
.

278

13. , HTML

CSV- write .write row,


, , .

CSV ,
,
. writerowQ,
.

,
, HTML:
HttpResponse ( MIME), -
, , .
.

PDF
Portable Document Form at (PDF -
) Adobe ,
.
, .
PDF
; , ,
, .
Python Django PDF-
ReportLab (http://www.reportlab.org/rl_
toolkit.html). PDF ,
,
, .
, Django ReportLab KUsports.
com ,
,
.

ReportLab
PDF,
ReportLab. ,
http://www.reportlab.org/downloads.html
.
---------------------------------------------------------------------------------------------------- Linux, ,
. ReportLab
. , Ubuntu
apt-get install python-reportlab.

PDF

279

(, PDF)
http://www.reportlab.org/rsrc/userguide.pdf
.
,
Python:
>>> import reportlab

, ,
.


CSV, PDF Django
,
ReportLab A PI :
Hello World:
from reportlab.pdfgen import canvas
from django.http import HttpResponse
def hello_pdf(request):
# HttpResponse PDF.
response = HttpResponseCmimetype^application/pdf')
responsef'Content-Disposition] = attachment; filename=hello.pdf1
ft PDF, ",

= canvas.Canvas(response)
# PDF.
# PDF-.
# . ReportLab.
p.drawStnng( 100, 100, Hello w o r l d )
# PDF, ,
p.showPage()
p.save()
return response

MIME application/pdf
, PDF, HTML.
,
HTML .

ReportLab API ,
response canvas.Canvas,
.


PDF ( ), response.

280

13. , HTML

, PDF showPageQ saveQ, PDF-.

PDF-
PDF- (
) cStringlO
.
,
.
Hello World,
cStringlO:
from cStringlO import StringlO
from reportlab.pdfgen import canvas
from django.http import HttpResponse
def hello_pdf(request):
tt HttpResponse PDF.
response = HttpResponse(mimetype=application/pdf)
response[Content-Disposition'] = 'attachment; filename=hello.pdf'
temp = StringlOO
tt PDF, StringlO
tt "".

= canvas.Canvas(temp)
tt PDF.
tt PDF-.
tt . ReportLab.

p.drawString(100, 100, "Hello world.")


tt PDF.

p.showPage()
p.save()
tt StringlO ,

response.write(temp.getvalue())
return response


Python
.
, .

Z IP -. Python zipfile,

ZIP. ,
, .

281

ta rf ile
TAR.
. Python Im aging Library
(PIL; http://www.pythonware.com/products/pil/)

PNG, JPEG , GIF .
,

.

.
Python,
.
. ,
:

matplotlib (http://matplotlib.sourceforge.net/ )
, ,
MatLab M athem atica.

pygraphviz (,http://networkx.lanl.gov/pygraphviz/ ) -
Graphviz (http://graphviz.org/ ).
,
.

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


Django
, RSS
Atom.

RSS Atom?
RSS Atom - XML ,
.
RSS http://www.whatisrss.com/,
Atom - http:// www.atomenabled.org/.

282

13. , HTML


Python. .
,
URL /feeds/. URL (,
/feeds/) Django
.
, Feed-
URL.

Django, URL :
(~feeds/(?P<url>.*)/$, 'django.contrib.syndication.views.feed,
{'feed_dict': feeds}

),
Django RSS
URL, feeds/. (
feeds/ .)
: {*feed_.dict':
feeds}. ,
URL.
, feed_dict - , (
URL) Feed-.
URL, :
from django.conf.urls.defaults import *
from mysite.feeds import LatestEntries, LatestEntriesByCategory
feeds = {
latest: LatestEntries,
categories: LatestEntriesByCategory,

}
urlpatterns = pa tternsC,
tt ...
(r'~feeds/(?P<url>. *)/$, django. contrib. syndication, views, feed,
{feed_dict : feeds}),
tt ...

)
:

fee d s/la te st/, LatestEntries.

feeds/categories/, Latest
EntriesByCategory.

Feed-.

283

Feed - Python,
. (,
, )
(, , ,
, ).
django. contrib. syndication,
feeds. Feed. .


,
:
from django.contrib.syndication.feeds import Feed
from mysite.blog.models import Entry
class LatestEntries(Feed):
title = "
link = "/archive/"
description = " .
def items(self):
return Entry.objects.order_by('-pub_date)[:5]

django.contrib.syndication.feeds.Feed.

title, link description


RSS <title>, <link> <description>
.

itemsQ ,
<item>.
Entry, API ,
.

. <item> RSS-
<title>, <link> <description>.
, .
<title> <description>,
feeds/latest_title.html feeds/latest_description.html,
latest - URL.
.html .

, :

obj: ( , items()).

site: django.models.core.sites.Site,
. ,
{{ site.domain }} {{ site.name }}.

284

13. , HTML

,
{{ obj }},
. (
_U n i c o d e __ ().)
tit 1_
template description_template Feed-.

<link> .
, itemsQ, Django
get_absolute_url(). ,
Django item_link() Feed-,
item .
get_absolute_url() item_link() URL
Python.

LatestEntries
. latest_title.htm l

{{ obj.title }}

latest_description.htm l -
{{ obj.description }}

...



.
, RSS-
. Feed-
; DRY
(Dont Repeat Yourself - ), ,
.

,
, URL .
URL :

http://example.com/feeds/tags/python/:
python.

http://example.com/feeds/tags/cats/:
cats.

tags.
URL, - python cats - -

285

,
, .
.
:
from django.core.exceptions import ObjectDoesNotExist
from mysite.blog.models import Entry, Tag
class TagFeed(Feed):
def get_object(self, bits):
tt URL "/feeds/tags/cats/dogs/mice/"
tt , bits ,
if len(bits) != 1:
raise ObjectDoesNotExist
return Tag.objects.get(tag=bits[0])
def title(self, obj):
return " : %s % obj.tag
def 1ink(self, obj):
return obj.get_absolute_url()
def description(self, obj):
return " %s % obj.tag
def items(self, obj):
entries = Entry.objects.filter(tags_id__exact=obj.id)
return entries.order_by('-pub_date)[:30]

RSS
URL /feeds/tags/python/:
1. URL /feeds/tags/python/ ,
. /,
get_object() Feed-,
.
[python].
URL /feeds/tags/python/django/ [python,
django].
2. get_object() Tag
bits.
API
. ,
get_object() django.core.exceptions.
ObjectDoesNotExist. Tag.objects.get()
try/except, .
Tag.DoesNotExist,
Tag.DoesNotExist ObjectDoesNotExist.
ObjectDoesNotExist, get_object(),
Django 404.

286

13. , HTML

3. <title>, <link> <description> Django


title Q , linkQ descriptionQ.
, ,
.
:
a. , obj, obj -
, get_object().
b. .
c. .
4. , , items()
obj. , :
items(obj), itemsQ
items (
).
Feed-
Django (http://docs.djangoproject.
com /en/dev/ref/contrib/syndication/).



RSS 2.0. ,
Feed- feed_type:
from django.utils.feedgenerator import AtomlFeed
class MyFeed(Feed):
feed_type = AtomlFeed

, feed_type ,
.
. 13.1.
13.1.
Feed-

django.utils.feedgenerator.Rss201rev2Feed

RSS 2.01 ( )

django. u tils , feedgenerator. Rssllserland091Feed

RSS 0.91

django.utils.feedgenerator.AtomlFeed

A tom 1.0

( ,
, , MP3)
item_enclosure_url, item_enclosure_length
item_enclosure_mime_type:

287

from myproject.models import Song


class MyFeedWithEnclosures(Feed):
title = " "
link = "/feeds/example-with-enclosures/"
def items(self):
return Song.objects.all()[:30]
def item_enclosure_url(self, item):
return item.song_url
def item_enclosure_length(self, item):
return item.song_length
item_enclosure_mime_type = "audio/mpeg

Song song_url
song_length ( ).

, ,
<language> (RSS 2.0) xml:lang (Atom).
LANGUAGE_C0DE.

URL-
( ) link URL (
, /blog/) URL,
(, http://www.exafnple.cofn/blog/). link,

SITE_ID. ( .
16.)
Atom
<link r e l - self > .
.


Atom RSS

- Atom RSS. Django :
Feed- feed_type
. URL
. :
from django.contrib.syndication.feeds import Feed
from django.utils.feedgenerator import AtomlFeed
from mysite.blog.models import Entry
class RssLatestEntries(Feed):
title = " "

288

13. , HTML
link = "/archive/
description = " .
def items(self):
return Entry.objects.order_by(-pub_date)[:5]
class AtonLatestEntries(RssLatestEntries):
feed_type = AtonlFeed

URL:
from django.conf.urls.defaults import *
from myproject.feeds import RssLatestEntries, AtomLatestEntries
feeds = {
'rss: RssLatestEntries,
atom: AtomLatestEntries,

}
urlpatterns = patternsC*,
tt . . .

(r'"feeds/(?P<url>.*)/$', 'django.contrib.syndication.
{'feed_dict': feeds}),

. views.feed,

tt . . .


(sitemap) - XML, ,
.
.

Django (http://www.djangoproject.com/sitemap.xml):
<?xml version^'!. encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.djangoproject.com/documentation/</loc>
<changefreq>weekly</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>http://www.djangoproject.com/documentation/0_90/</loc>
<changefreq>never</changefreq>
<priority>0.1</priority>
</url>
</urlset>

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

289

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

sitem ap,
:
1. django.contrib.sitemaps INSTALLED_APPS.
2. , TEMPLATE_LOADERS
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/.



. .

FlatPageSitemap
django.contrib.sitemaps.FlatPageSitemap
.
location; lastmod, changefreq,
priority .
. 16.

GenericSitemap
GenericSitemap
(. 11).
, ,
info_dict, .
- queryset.
date_f ield, ,
queryset. lastmod
. GenericSitemap
priority changefreq,
URL.
URL,
FlatPageSitemap GenericSiteMap (
Entry, ).

292

13. , HTML
from django.conf.urls.defaults import *
from django.contrib.sitemaps import FlatPageSitemap, GenericSitemap
from mysite.blog.models import Entry
info_dict = {
queryset1: Entry.objects.al1(),
'date_field' : 'pub_date',

}
sitemaps = {
flatpages': FlatPageSitemap,
'blog': GenericSitemap(info_dict, priority=0.6),

}
urlpatterns = patternsC',
# ,
tt info_dict

U ...
tt

(' "sitemapV xml$' ,


'django.contrib.sitemaps.views.sitemap',
{sitemaps': sitemaps})


,
, ,
sitemaps. :

URL :
django. contrib. sitemaps, views, index django. contrib. sitemaps.views,
sitemap.

django.contrib.sitemaps.views.sitemap
section.

URL
:
(' ''sitemap. xml$',
django. contrib.sitemaps.views.index',
{sitemaps': sitemaps}),
(r'''sitemap-(?P<section>. +). xml$' ,
'django.contrib.sitemaps.views.sitemap',
{'sitemaps': sitemaps})

sitemap.xml,
sitemap-flatpages.xml sitemap-blog.xml. Sitemap-
sitemaps .

293

Google
, ,
Google .
django.contrib.sitemaps.ping_google().
sitemap_url,
URL (,
/sitemap.xml). , ping_google()
URL.
ping_google() URL ,
django.contrib.sitemaps.SitemapNotFound.
from django.contrib.sitemaps import ping_google
class Entry(models.Model):
U

...

def save(self, *args, **kwargs):


super(Entry, self).save(*args, **kwargs)
try:
ping_google()
except Exception:
# ,
# , HTTP
pass

ping_google() -
.
Google,
save() - .
, INSTALLED_APPS django.
contrib.sitemaps, manage.
ping_google. Google
, :
python manage. ping_google /sitemap.xml

?

Django ,
: , .

14
,
:
-.
,
.
, , . ,
, (,
). , - ,
, .
, ,
.
, . HTTP ,
,
.
, (1-,
. .),
.
,
. (cookie),
,
.

Cookies
,
HTTP
-. cookies. Cookie -
, -
.

Cookies

295

, ,
.
, .
google.com, Google
HTTP-, :
GET / /1.1
Host: google.com

Google :
/1.1 200
Content-Type: text/html
Set-Cookie: PREF=ID=5b14f22bdaf181:= 1167000671:LM=1167000671;
expires^Sun, 17-Jan-2038 19:14:07 GMT;
path=/; domain=.google.com
Server: GWS/2.1

Set-Cookie.
cookie (PREF=ID=5b14f22bdaf 181 :=1167000671 :LM=1167000671)
Google .
Google ,
, :
GET / /1.1
Host: google.com
Cookie: PREF=ID=5b14f22bdaf181:TM=1167000671:LM=1167000671

Cookie, Google ,
, . cookie ,
, ,
. Google (, , )
.

cookies
Django
, .
, cookies
. ,
, , -
cookie .
cookies .
HttpRequest COOKIES, .
cookie,
:

296

14. ,
def show_color(request):
if "favorite_color" in request.COOKIES:
return HttpResponse(Baui %s" % \
request.COOKIES["favorite_color])
else:
return HttpResponse(Y .)

cookie .
set_cookie() HttpResponse.
cookie favorite_color,
GET :
def set_color(request):
if "favorite_color in request.GET:
tt HttpResponse ...

response = HttpResponse(Tenepb %s" % \


request.GET["favorite_color])
cookie
response. set_cookie(favorite_color,
request. GET[,,favorite_color])
return response
else:
return HttpResponse(" .)
tt . . .

response.set_cookie()
, cookie
(. 14.1).
14.1. cookie

max_age

None

cookie .
None, cookie
.

expires

None


cookie. Wdy, DD-Mth-YY : :SS
GMT . ,
max_age.

7"

,
cookie. cookie
, URL
. ,

cookie .
,
.

path

297

Cookies

domain

None

, cookie.

cookie. , cookie
domain=".example, com",
www. example, com, www2. example, com
an.other.sub.domain.example.com.
None, cookie
, .

secure

False

rue,
cookie
HTTPS-.

cookies
, - ,
cookie. :

cookies - ;
cookies.
cookies.
, cookies ,

cookie.
, cookies
. , -
, .

Cookies ( HTTPS)
. HTTP
, cookies .
, ,
cookie .
cookie.
: ,
cookie
.
20.

Cookies .
cookies,

(http://wwwsearch.sourceforge.net/mechanize/)
HTTP- .

298

14. ,

cookies ,
. - cookies -
IsLoggedIn=1 . ,
;
, .

Django

, cookies
-. Django
, ,
.

. ,
cookies. cookies
, ,
, cookies.
,
.


(.
17) Django. ,
:
1. , MIDDLEWARE_CLASSES django.
cont rib. sessions, middleware. SessionMiddlewa re.
2. , INSTALLED_APPS
django.contrib.sessions ( ,
manage, syncdb).

, startproject,
, , ,
.
,
SessionMiddleware MIDDLEWARE_CLASSES django.
contrib.sessions INSTALLED_APPS.
-, .


SessionMiddleware ,
HttpRequest ( Django)
session, .
. :

Django

299

tt :

request.session[fav_color] = blue
tt -
tt , , .

fav_color = request.session[fav_color"]
tt :

del request.session[fav_color]
tt :

if fav_color in request.session:

request.session ,
keys() itemsQ. Django
.

request.session
P ython ( , . .);

, ,
Django .
, ,
(
Django), ,
Django.
, _fav_color:
request. session['_fav_color' ] = 'blue' tt He !

He request.session ,
.
Python. :
request, session = some_other_object tt He !
request.session, foo = 'bar'
tt He !

.
has_commented True ,
. (
)
:
def post_comment(request):
if request.method != 'POST':
raise Http404(' POST-')
if comment1 not in request.POST:
raise Http404( ')
if request.session.get('has_commented', False):
return HttpResponse( .)
= comments.Comment(comment=request.P0ST[comment])

14. ,

300

.save()
request.session[has_commented] = True
return HttpResponse( !')

, ,
:
def login(request):
if request.method != POST:
raise Http404( POST-)
try:
m = Member.objects.get(username=request.P0ST[username])
if m.password == request.P0ST[password]:
request.session['member_id] = m.id
return HttpResponseRedirect(/you-are-logged-in/')
except Member.DoesNotExist:
return ' .")

:
def logout(request):
try:
del request.session[member_id]
except KeyError:
pass
return HttpResponse(Bbi .")

---------------------------------------------------------------------------------------------------- .

. ,
.

cookies
, ,
cookies. Django
, . -
request.session.set_test_cookie(),
( !) - request.session.test_cookie_worked().
, ,
set_test_cookie() test_cookie_worked()
cookies. cookie, ,
, .
delete_test_cookie(),
. ,
.
:

Django

301

def login(request):
# ...
if request.method == POST:
# , cookie
# ( ):
if request.session.test_cookie_worked():
# cookie , .
request.session.delete_test_cookie()
#
# , ...
return HttpResponse(Bbi .)
# cookie ,
# . -
# ,
else:
return HttpResponse(
" cookie .")
# ,
# cookie,
request.session.set_test_cookie()
return render_to_response(foo/login_form.html)

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


-
D ja n g o , django.contrib.
sessions.models. -
32 , co o k ie . -
, A P I
.
> from django.contrib.sessions.models import Session
> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead)
> s.expire_date
datetime.datetime(2005, 8, 20, 13, 35, 12)

, ,
get_decoded(). ,
:
> s.session_data
1KGRwMQpTJ19hdXRoX3VzZXJ faWQnCnAyCkkxCnMuMTExY2Zj 0DI2Yj...

14. ,

302
> s.get_decoded()
{'user_id': 42}


Django
, -
.
# .
request.session[foo] = bar
tt .

del request.session[foo']
tt ,

request.session[foo'] = {}
tt Cron! HE ,
tt request. session[ foo], request, session,

request.session['foo'][1bar'] = 'baz'

,
SESSION_SAVE_EVERY_REQUEST True. Django
,
.
, cookie
. SESSION_SAVE_EVERY_REQUEST
True, cookie .
expires.

cookies
, , cookie Google,
, expires=Sun, 17-Jan-2038 19:14:07 GMT;.
cookie
, , cookie.
, cookie
.
SESSI0N_EXPIRE_AT_BR0WSER_CL0SE.
SESSI0N_EXPIRE_AT_BR0WSER_CL0SE
False, cookie
SESSI0N_C00KIE_AGE ( , 1 209 600 ).
, ,
.
SESSI0N_EXPIRE_AT_BR0WSER_CL0SE
True, Django cookies, ,
.

303

Django


, , -
.

,
pickle.
.
Python.

django_session.

.
request, session, Django
.

Django cookie, .
, cookie
( SESSION_SAVE_EVERY_REQUEST True).

Django
cookie. cookie ,
URL
,
(, JSP).
.
URL ,

Referer.

,
django.contrib.sessions; .


,
cookies Django (. 14.2).
14.2. , cookie

SESSI0N_C00KIE_D0MAIN

,
cookie. cookie
,
". example.com", -

None

None.

304

14. ,

14.2. ()

SESSI0N_C00KIE_NAME

cookie.
.

SESSION_COOKIE_SECURE

cookie
.
rue, cookie
HTTPS-.

"sessionid"
False



.
. ,
, ,
- .
, Django (
). Django
, ,
cookie .
auth/auth ( ). ,
.
:
1. , ,
().
.
2. ,
().
.

Django .

: , .

: (/) , ,
.

:
.

:
.

305

(. 6),
:
,
,
.


,
Django django.contrib,
. , , -
, :
1. , ,
. , ,
cookie, .
2. django.contrib.auth INSTALLED_APPS
manage, syncdb,
.
3. , MIDDLEWARE_CLASSES
django.contrib.auth.middleware.AuthenticationMiddleware -
SessionMiddleware.

,
.
request.user,
.
,
AnonymousUser ( . ).
, , is_authenticatedQ:
if request.user.is_authenticated():
tt ,
else:
tt .

User
User - request.user
(. ), -
. AnonymousUser
, user.is_
authenticatedQ, ,
User. . 14.3 14.4 User.

14. ,

306

14.3. User

username

. He 30 .
, .

first_name

. 30 .

last_name

. 30 .

email

. .

password

. (
Django ). .
.

is_staff

. ,
.

is_active

. ,
.
,
False.

is_superuser

. ,
.

last_login

.
.

date_joined

.

.

14.4. User

is_authenticated()

User
True. ,
,
.
. rue ,
,

.
is_anonymous()

rue Anonymousllser
( False User).
is_authenticated().

get_full_name()

first_name last_
name, .

set_password(passwd)

,
. User
.

307

check_password(passwd)

True,
.
,
.

get_group_permissions()

,

, .

get_all_permissions()

,
,
, .

has_perm(perm)

rue,
perm,
"package, codename".

has_perms(perm_list)

rue,

False.

.

False.
has_module_perms(app_label)

rue,
-
, app_label.

False.

get_and_delete_messages()

Message
.

email_user(subj, msg)


.
,
DEFAULT_FROM_EMAIL.
f rom_email,
.

, User ,
--: groups permissions. ,
User, ,
--:
# , :
myuser.groups = g roup_list

tt

:
myuser.groups.add(groupl, group2,...)

tt

:
myuser.groups.remove(group1, group2,...)

308

14. ,
# :
myuser.groups.clear()
tt

myuser.permissions = permission_list
myuser.permissions.add(permission1, permission2, ...)
myuser.permissions.remove(permission1, permission2, ...)
myuser.permissions.clear()


Django
( ),
, , .
Django ,
django.contrib.auth: authenticateQ loginQ.

authenticateQ.
, username password, User,
. authenticateQB03BpanjaeT None.
> from django. contrib import auth
> user = auth.authenticate(username=john', password^'secret)
> if user is not None:
print "!"
... else:
print " .

authenticateQ
. loginQ.
HttpRequest User
.
, authenticateQn loginQ
:
from django.contrib import auth
def login_view(request):
username = request.POST.get(1username, ')
password = request.POST.get(1password', ')
user = auth.authenticate(username=username, password=password)
if user is not None and user.is_active:
tt "
auth.login(request, user)
tt ,
return HttpResponseRedirect("/account/loggedin/)
else:
tt
return HttpResponseRedirect("/account/invalid/)

309

,
django.contrib.auth.logoutQ. Http
Request :
from django.contrib import auth
def logout_view(request):
auth.logout(request)
# ,
return HttpResponseRedirectCVaccount/loggedout/")

, auth.logoutQ ,
.
login logout
;
. ,

URL:
from django.contrib.auth.views import login,

logout

urlpatterns = p a t t e r n s C ' ,
# ...
( ' "accounts/login/S1 , login),
(r'"accounts/logout/T , logout),

)
Django URL
/accounts/login/ /accounts/logout/.

login registration/
login.html ( ,
template_name).
username password. :
{% extends "base.html %}
{% block content %}
{% if form.errors %}
<p class=,,error">HeBepHoe </>
{% endif %}
<form action^" method=post,,>
clabel for=,,username,,>HMfl :</label>
<input type="text" name^'username" value=,,M id=,,username">
clabel for=,,password,,>apo: </label>
cinput type=MpasswordM name=,,password" value= id=password">
cinput type="submit value=,,loginn />
<input type=,,hidden" name=,,next" value="{{ next|escape }}" />
</form>
{% endblock %}

310

14. ,


/accounts/profile/. URL, value next .
GET-
login,
next, .
logout .
registration/logged_out. html (
).
next_page, URL
, .



? ,
.

, , request.user.
is_authenticated(), :
from django.http import HttpResponseRedirect
def my_view(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/accounts/login/?next=%s' % request.path)
tt ...

:
def my_view(request):
if not request.user.is_authenticated():
return render_to_response('myapp/login_error.html')
tt ...

login_

required:
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
tt ...

login_required

,
URL /accounts/login/, URL
next , : /accounts/login/?next=/polls/3/;

311

,
.
, .



- ,
, .
,
request.user . ,
,
polls.can_vote (
. ):
def vote(request):
if request.user.is_authenticated() \
and request.user.has_perm('polls.can_vote)):
tt
else:
return HttpResponse(" .)

Django user_
passes_test.
, :
def user_can_vote(user):
return user.is_authenticated() and user.has_perm("polls.can_vote)
@user_passes_test(user_can_vote, login_url="/login/)
def vote(request):
tt ,
tt .

user_passes_test :
, User
True, . ,
user_passes_test ,
User ; .
( )
login_url, URL (
/accounts/login/). ,
user_passes_test ,
login_url.

,
, Django

14. ,

312

: permission_required().
:
from django.contrib.auth.decorators import permission_required
@permission_required('polls.can_vote, login_url='7 1 ogin/M)
def vote(request):
tt ...

, permission_required()
login_url, /accounts/login/.


Django -
?
,
URL , :
from django.contrib.auth.decorators import login_required
from django.views.generic.date_based import object_detail
@login_required
def limited_object_detail(*args, **kwargs):
return object_detail(*args, **kwargs)

, login_required
.

,


. 6 ,

. .
API,
, . .

create_

user:
> from django. contrib. auth. models import User
> user = User.objects.create_user(username=john,
email='jlennon@beatles.com,
password^glass onion)

user - User,
(create_user()

313

save()). -
:
> user. is_staff = True
> user.saveO

set_password():

> user = User, objects. get(username=' John)


> user.set_password('goo goo goo joob*)
> user.saveO

He password .
, .
,

password

User

hashtype$salt$hash

: (hashtype), (salt)
(hash), . hashtype
, shal ( )
md5; .
salt - ,
. :
Sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4


User.set_password() User.check_password().

1
(hash)
. ,
, .
, ,
,
. ,
,
.

salted hash
, . - ..

14. ,

314

, ,
,
, .
, , .
, (rain
bow tables), ,
, .

.
- ,
-
.
, ,

, -
, .

,
.



,
. -,
Django
. , .

.
Django :
from
from
from
from

django import forms


django.contrib.auth.forms import UserCreationForm
django.http import HttpResponseRedirect
django.shortcuts import render_to_response

def register(request):
if request.method == POST:
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/books/")
else:
form = UserCreationForm()
return render_to_response("registration/register.html", {

315


'form': form,

))


register.html. :

registration/

{% extends "base.html %}
{% block title %} {% endblock %>
{% block content %>
<> </>
<form action^" method=post">
{{ form.as_p >}
<input type="submit 1= >
</form>
{% endblock %}



,
RequestContext (. 9).
---------------------------------------------------------------------------------------------------- , ,
RequestContext TEMPLATE_CONTEXT_PROCESSORS
"django.core.context_processors.auth (
). . 9.

RequestContext
( User AnonymousUser)
{{ u s e r }}:
{% if user.is_authenticated %}
<> , {{ user.username }}. , .</>
{% else %>
<> , . , .</>
{% endif %}

{{ perms
}}. -
, .
perms .
{% if perms.polls %},
-
, {% if perms.polls.can_vote %},
.

14. ,

316

, ,
{%if %}:
{% if perms.polls %>
<> - .</>
{% if perms.polls.can_vote %}
<> !</>
{% endif %}
{% else %>
<> .</>
{% endif %}

,
,
.
.

- ,
.
Django,
.
Django
:


,
.

,
,
.

,
.

,
. ,
,
,
,
.
- , , -
Django.
auth_permission
manage. syncdb.

317

<app>.<action>_<object_name>".
, polls Choice,
polls.add_choice, polls.change_choice polls.delete,
choice.

, Django,
django.contrib.auth.models. ,
API
.

- ,
, ,
.
.
,
. ,
can_edit_home_page,
.


. ,
,
,
, ,
.
, ,
. -
, django.contrib.auth.models,
A PI .

-
.
User. ,
, .
Django
. ,

(The object was created successfully).
API
. :

14. ,

318

user.message_

set.create(message=message_text).

, user.get_
and_delete_messages(), Message
( ) .

:
def create_playlist(request, songs):
tt , .
tt . . .

request.user.message_set.create(
message=CnncoK .

)
return render_to_response("piaylists/create.html",
context_instance=RequestContext(request))

RequestContext,

{{ messages }}.
:
{% if messages %}
<ul>
{% for message in messages %>
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}

, RequestContext
get_and_delete_messages,
, .
, ,
, .
,
.

?
- .
, , , ,

, .

Django, .

15

-?
, .
- ,
, -
, .
, .
- .
- - w ashingtonpost.com
slashdot.org,
.
- .
- .
- ,
.
,
-:
, URL
:

:

( )

Django ,
,
. Django
:
, ,
, .

320

15.

Django ,
, Squid
(http://www.squid-cache.org/ ), .
,
( HTTP-) ,
.


.
, , , .
, ;
, , - .
CACHE_BACKEND.
CACHE_BACKEND.

Memcached
Memcached -
Django,
.
LiveJournal.com,
Danga Interactive .
, Facebook W ikipedia,
.
Memcached http://danga.
/ memcached/. -
,
. -
,
. , ,
.
Memcached
Python.
Django. ,
:

cmemcache,
http://gijsbert.org/cmemcache/.

-
cmemcache, python-memcached,
jtp:llitp.tuxnmy.com/pub/python-memcached/.
URL- , Memcached
http://www.danga.com/memcached/
Python Client APIs.

321

Memcached Django,
CACHE_BACKEND memcached://ip:port/, ip - IP -
Memcached, a port - ,
.
Memcached localhost
(127.0.0.1) 11211:
CACHE_BACKEND = memcached://127.0.0.1:11211/'

Memcached -
. ,
Memcached ,
,
.
, CACHE_BACKEND
.
Mem
cached, 172.19.26.240
172.19.26.242 ( 11211):
CACHE_BACKEND = memcached://172.19. 26. 240:11211;172.19.26.242:11211/

Memcached,
172.19.26.240 ( 11211),
172.19.26.242 ( 11212) 172.19.26.244 ( 11213):
CACHE_BACKEND = memcached :/*
172.19.26.240:11211;172.19.26.242:11212; 172.19.26.244:11213/'

,
: .
,
,
. ,
Django
;
, ,
.


,
:
python manage. createcachetable [cache_table_name]

[cache_table_name] - .
,
.

322

15.

CACHE_BACKEND db://tablename,
table - .
my_cache_table:
CACHE_BACKEND = 'd b ://my_cache_table

,
. - .


.


_
BACKEND file://. ,
/var/tmp/django_cache,
:
CACHE_BACKEND = file:///var/tmp/django_cache

.
- file://, -
/var/tmp/django_cache. Windows
file:// , :
file://:/f/ba

,
.
.
, ,
,
-. ,
apache, /var/tmp/django_cache
apache .

, Python- pickle.
- ,
.


,
Memcached,
.
.
CACHE_BACKEND locmem:///, :
CACHE_BACKEND = 'locmem:///'

323

, ,

. ,
,
, , .
.

( )
, Django
, ,
.
, ,
,
,
.
, CACHE_BACKEND
:
CACHE_BACKEND = dummy:///


Django ,

. ,
CACHE_BACKEND Python
URI (, ), :
E_BACKEND = 'path.to.backend://'


.
django/core/cache/backends/.
---------------------------------------------------------------------------------------------------- (,
)
, Django.
.

CACHE_BACKEND
,
.
CACHE_BACKEND.
:

324

15.

timeout: .
300 (5 ).

max_entries: locmem, filesystem database


,
.
300.

cull_percentage: ,
max_entries. 1/cull_percentage,
cull_percentage=2 .
0 , max_entries
.
, .

timeout 60:
CACHE_BACKEND = "memcached://127.0.0.1:11211/?timeout=60"

timeout 30 _
entries 400:
E_BACKEND = "locmem:///?timeout=30&max_entries=400"


.
MIDDLEWARE_CLASSES django.middleware.cache.
UpdateCacheMiddleware django.middleware.cache.FetchFromCacheMiddleware,
:
MIDDLEWARE_CLASSES = (
'django. middleware.cache.UpdateCacheMiddleware'.
'django.middleware.common.CommonMiddleware'.
'django. middleware.cache.FetchFromCacheMiddleware'.

---------------------------------------------------------------------------------------------------- : update , fetch


. ,
MIDDLEWARE_CLASSES .

CACHE_MIDDLEWARE_SEC0NDS:

325

CACHE_MIDDLEWARE_KEY_PREFIX:
Django
, -
, Django,
. ,
.

, GET
POST . _
MIDDLEWARE_ANONYMOUS_ONLY True,
.
(
). ,
CACHE_MIDDLEWARE_ANONYMOUS_ONLY
AuthenticationMiddleware.
,
HttpResponse :

Last-Modified,
( ) .

Expires,
CACHE_MIDDLEWARE_SECONDS.

Cache-Control,
, _
MIDDLEWARE_SECONDS.

---------------------------------------------------------------------------------------------------- . 17.


( max-age Cache-Control),
, CACHE_MIDDLEWARE_SECONDS
. django.views.decorators.cache
( cache_control)
( never_cache).
. :
.


-
. django.views.decorators.cache
cache_page,
, :
from django.views.decorators.cache import cache_page

326

15.
def my_view(request):
# ...

my_view = cache_page(my_view, 60 * 15)

, Python 2.4 :
@cache_page(60 * 15)
def my_view(request):

# ...
cache_page :
.
my_view() 15 . (,
60 * 15, , 15 60 ,
900 .)
, ,
URL. URL
, URL
. , URL:
urlpatterns = (',
(r'~foo/(\d{1,2})/$', my_view),

/ f /1/ /foo/23/ ,
. URL (, /foo/23/)
URL
.


URL

,
cache_page my_view.

, .
,
, ?
, ?

URL, .
,
cache_page , URL.
URL
urlpatterns = (',
(r~foo/(\d{1,2})/$', my_view).

327

:
from django.views.decorators.cache import cache_page
urlpatterns = ('',
(r1foo/(\d{1,2})/$, cache_page(my_view, 60 * 15)),

)
He cache_page URL.


,
cache
. ,
{%load cache %}.
{% cache %}
. :
. :
{% load cache %}
{% cache 500 sidebar %}
.. ..
{% endcache %}


. ,

.
{% cache %} ,
:
{% load cache %}
{% cache 500 sidebar request.user.username %}
.. ..
{% endcache %}


. {%cache %}
, .
; ,
. , ,
my_timeout 600,
:
{% cache 600 sidebar %} ... {% endcache %}
{% cache my_timeout sidebar %} ... {% endcache %}

.
, ,
.

15.

328

API

.
, ,
,
.
,
,
(
), .
Django API
.
.
Python, : , ,
. . (
Python ; .
Python.)
django.core.cache cache,
CACHE_BACKEND:
>

from django.core.cache import cache

: set(key, value, timeout_


seconds) get(key):
> cache. set('my_key' , 'hello, world! ', 30)
> cache.get('my_key')
'hello, world!'

timeout_seconds
timeout CACHE_BACKEND (. ).
, cache.get() None:
# 30 , my_key ...
> cache. get( my_key)
None

None,
:
None , None.
cache.get() default. ,
, :
> cache.get (my_key', has expired)
'has expired'

( ,
), add(). ,

API

329

s e t(), ,
:
> cache.set(add_key, )
> cache.add(add_key, )
> cache. get('add_key)
' '

, add() ,
. True,
, False .
get_many(),
,
, (
):
> cache. set('. 1)
> cache. set('b , 2)
> cache. set( ', 3)
> cache. get_many([a'. b , ' '])
{' a' : 1. b ' : 2, ': 3}

, delete()ooe ,
:
> cache. delete( )


. incr() decr() .

1, / ,
.
, ,
ValueError:
> cache.set('num' . 1)
> cache. incr('num)

2
> cache. incr('num', 10)
12
> cache. decr('num)
11

> cache. decr('num'. 5)

---------------------------------------------------------------------------------------------------- incr()/decr() .
, (
, Memcached), .
,
:
.

330

15.



. - :
,
. ,
.
:

-,
http://example.com/
, . ,
example.com, ; ,
, .

Django- -,
, Squid Web Proxy Cache (http://www.squid-cache.org/ ),
.
-
.

- .
,
,
, .


, :

, ,
URL,
.
, ,
-. ,
.
, ,
,
. .
, HTTP .
, ,

.
.

Vary
Vary ,
. -

331

Vary

,
, , .
Django ,
, (, /stories/2005/
jun/23/bank_robbed/). ,
URL

, cookie .
(cookie, ,
),
Vary.
Django vary_on_
headers:
from django.views.decorators.vary import vary_on_headers
tt Python 2.3.

def my_view(request):
tt ...
my_view = vary_on_headers(my_view,

'User-Agent)

tt Python 2.4+.
@vary_on_headers('User-Agent')
def my_view(request):
tt ...

( Django
)
.
vary_on_headers
Vary (, response^Vary] = useragent ) ,
Vary ( ),
.
vary_on_headers() :
@vary_on_headers('User-Agent, 'Cookie)
def my_view(request):
tt ...

,
cookie
. , ,
Mozilla toolbar cookie
, Mozilla
foo=ham cookie.
cookie ,
vary_on_cookie.
:

332

15.
@vary_on_cookie
def my_view(request):
tt ...
@vary_on_headers('Cookie')
def my_view(request):
tt ...

,
vary_on_headers, : User-Agent user-agent
.

django.utils.cache.patch_vary_headers.
Vary , :
from django.utils.cache import patch_vary_headers
def my_view(request):
tt ...
response = render_to_response(template_name, context)
patch_vary_headers(response, ['Cookie'])
return response

patch_vary_headers
HttpResponse, -
, .

:

, .
:
( ) ( ).

.
- ,
. -
, , - .
, .
Django cache_control,
:
from django.views.decorators.cache import cache_control
@cache_control(private=T rue)
def my_view(request):
tt . ..

-.

. , HTTP :

333

,
,
. ( ,
, - ,
.)

cache_control Django .
cache_control ,

3600 :
from django.views.decorators.cache import cache_control
@cache_control(must_revalidate=True, max_age=3600)
def my_view(request):
tt .. .

cache_control()
HTTP Cache-Control.
:

public=True

private=True

no_cache=True

no_transform=True

must_revalidate=True

proxy_revalidate=True

max_age=num_seconds

s_maxage=num_seconds

(,
max-age , _
MIDDLEWARE_SETTINGS. cache_control
max-age, .)
,
never_cache, HTTP-,
, ,
. :
from django.views.decorators.cache import never_cache
@never_cache
def myview(request):
tt . . .

334

15.


Django ,
:

django.middleware.http.ConditionalGetMiddleware
GET- LastModified, .

django.middleware.gzip.GZipMiddleware (
)
.

MIDDLEWARE CLASSES

MIDDLEWARE_CLASSES .
, ,
.
Vary.
UpdateCacheMiddleware
.
, , ,
, . UpdateCacheMiddleware
, Vary. :

SessionMiddleware Cookie

GZipMiddleware Accept-Encoding

LocaleMiddleware Accept-Language

, FetchFromCacheMiddleware
.
, ,
, . FetchFromCacheMiddleware
,
Vary, .

?
Django ,
(contrib),
. :
(. 6)
(. 14).
.

16
django.contrib
Python
: P ython
,
, - . Django

,
-. - .

Django
Django django.contrib.
-
. ,
.
, ,
django.contrib.
(
),
.
, django.contrib, :
django.contrib
Django .
Django , ,
: django.contrib - .
django.contrib :

admin: Django. . 6.

admindocs:
. , .
Django.

16. django.contrib

336

auth: Django. . 14.

comments: .
, . Django.

contenttypes: ,
Django
. contrib

. , ,
django/contrib/contenttypes.

csrf: HTTP- CSRF (cross-site

request forgery). . CSRF.

databrowse: Django,
. , .
Django.

flatpages: HTML-
.

formtools:
, .
, . Django.

gis: Django
().
.
, .
http://geodjango.org/.

humanize: ,
. . .

localflavor: ,

. ,
(ZIP-)
.

markup:
. . .

redirects: . .
.

sessions: . . 14.

sitemaps: XML. .

13.

sites: ,
Django.
. .

syndication:
RSS Atom. . 13.

337

webdesign: ,
- ( ).
{%lorem %}.
. Django.


, django.contrib,
.

-
Django.
, ,
,
.

1:

1 , Django
LJW orld.com Lawrence.com
: Lawrence Journal-World ,
. LJW orld.com , Lawrence,
com - .
.
,
,
.
.
? ,
,
--. Django
, .
,
.

2:

LJW orld.com Lawrence.com
,
. :
-
.

,

338

16. django.contrib

.
. Site
,
name (, LJWorld.com) domain (, www.ljworld.com)
.
name
domain Django,
.


, , .
:

Site django.contrib.sites domain


name.

SITE_ID Site,
.

, Django
, .
sites, :
1. INSTALLED_APPS django.contrib.sites.
2. manage. syncdb,
django_site. , Site
example.com.
3. example.com,
, Site,
, Python API.
Site ,
Django.
4. SITE_ID .
Site,
.


,
.


,
,
ManyToManyField, Site:
from django.db import models
from django.contrib.sites.models import Site

339

class Article(models.Model):
headline = models.CharField(max_length=200)
tt ...
sites = models.ManyToManyField(Site)

,
.
.
Article article_detail :
from django.conf import settings
from django.shortcuts import get_object_or_404
from mysite.articles.models import Article
def article_detail(request, article_id):
a = get_object_or_404(Article, id=article_id, sites__id=settings.SITE_
ID)
tt . ..

,
,
, SITE_ID.
, , LJW orld.com SITE_ID
1, Lawrence.com - 2.
, LJW orld.com ,
,
LJW orld.com.


Site
--,
ForeignKey.

, ,
:
from django.db import models
from django.contrib.sites.models import Site
class Article(models.Model):
headline = models.CharField(max_length=200)
tt ...
site = models.ForeignKey(Site)

, .




,
, . :

340

16. django.contrib
from django.conf import settings
def my_view(request):
if settings.SITE_ID == 3:
tt ,
else:
tt .

,
.
:
from django.conf import settings
from django.contrib.sites.models import Site
def my_view(request):
current_site = Site.objects.get(id=settings.SITE_ID)
if current_site.domain == foo.com:
tt ,
else:
tt .

Site SITE_ID
, Site (Site.objects)
get_current().
:
from django.contrib.sites.models import Site
def my_view(request):
current_site = Site.objects.get_current()
if current_site.domain == foo.com:
tt ,
else:
tt .

---------------------------------------------------------------------------------------------------- django.conf.settings .


DRY ( )
(. 2
), name domain
Site. :
from django.contrib.sites.models import Site
from django.core.mail import send_mail
def register_for_newsletter(request):
tt . . .

...

current_site = Site.objects.get_current()

341

send_mail( %s % \
current_site.name,
. ,\\ %s. % \
current_site.name,
editor@%s % current_site.domain,
[user_email])

it ...

, Lawrence.com
Lawrence.com,
LJW orld.com -
LJWorld.com. .
( )
, Django.
, Lawrence.com LJW orld.
com - ( TEMPLATE_DIRS),
:
from django.core.mail import send_mail
from django.template import loader, Context
def register_for_newsletter(request):
tt .. .
tt . . .

subject = loader.get_template('alerts/subject.txt).render(Context({}))
message = loader.get_template('alerts/message.txt).render(Context({}))
send_mail(subject, message, do-not-reply@example.com, [user_email])
tt . . .

subject.txt message.txt
LJW orld.com Lawrence.com. ,
, , , .
Site ,
, .

CurrentSiteManager
Site ,
CurrentSiteManager
(. 10). ,
, Site.
CurrentSiteManager , :
from django.db import models
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
class Photo(models.Model):
photo = models.FileField(upload_to=/home/photos)

342

16. django.contrib
photographer_name = models.CharField(max_length=100)
pub_date = models.DateField()
site = models.ForeignKey(Site)
objects = models.Manager()
on_site = CurrentSiteManager()

Photo.objects.allO Photo
, Photo.on_site.all() - Photo,
,
SITE_ID.
, :
Photo.objects.filter(site=settings.SITE_ID)
Photo.on_site.al1()

CurrentSiteManager , Photo
?
site. ForeignKey ManyToManyField
,
CurrentSiteManager.
publish_on:
from django.db import models
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
class Photo(models.Model):
photo = models.FileField(upload_to=/home/photos)
photographer_name = models.CharField(max_length=100)
pub_date = models.DateField()
publish_on = models.ForeignKey(Site)
objects = models.Manager()
on_site = CurrentSiteManager('publish_on)

CurrentSiteManager,
, ValueError.
---------------------------------------------------------------------------------------------------- , (
) , CurrentSiteManager.
, , , Django
objects = models.ManagerO .
, Django - ,
- ,
, ,
(
), objects = models.ManagerO
CurrentSiteManager.

343

Django
,
,
Django
. Django ,
Site,
SITE_ID
.
, Django :

(. )
.
Django
SITE_ID.


.
site SITE_ID,
, ,
.

(.
)
. site,

SITE_ID.

(. 13) title
description {{ site }},
Site, .
, URL
domain Site,
.

(. 14) django.
contrib.auth.views.login ,
{{ site_name }}, Site -
{{ site }}/.


,
, ,
.
-, Apache,
,
Apache
.

16. django.contrib

344

Django
.
Django
(flatpages), django.contrib.flatpages.


. Django,

, API
.
URL
.
URL ,
. ( . .)


flatpages :
1. INSTALLED_APPS django.contrib.flatpages.
django.contrib.sites, INSTALLED_
APPS .
2. MIDDLEWARE_CLASSES django.contrib.
flatpages.middleware.FlatpageFallbackMiddleware.

3. manage. syncdb,
.
flatpages : django_flatpage django_
flatpage_sites. URL
, -
--,
.
FlatPage,
django/cont rib/f latpages/models. :
from django.db import models
from django.contrib.sites.models import Site
class FlatPage(models.Model):
url = models.CharField(max_length=100, db_index=True)
title = models.CharField(max_length=200)
content = models.TextField(blank=True)
enable_comments = models.BooleanField()
template_name = models.CharField(max_length=70, blank=True)
registration_required = models.BooleanField()
sites = models.ManyToManyField(Site)

345

url: URL , ,
(, /about/contact/).

title: . ,

content: ( HTML-).
,
.

enable_comments:
. .

.

template_name: .
; ,
flatpages/default.html.

registration_required:
.
, 14.

sites: , .
,
.


Django, API .
. ,
.
,
FlatpageFallbackMiddleware.
Django 404,
URL. ,
, URL sites
SITE_ID.
,
flatpages/def ault.html ( ).
flat Flat .
RequestContext.
FlatpageFallbackMiddleware ,
.
----------------------------------------------------------------------------------------------------
404 ( ) - 500
( ) . ,

346

16. django.contrib
MIDDLEWARE_CLASSES . ,
FlatpageFallbackM iddlew are
, .

,
,
.


Django ,
FLatpages.
, .

Python API
,
Django, django/contrib/flatpages/
models.py. API
, :
> from django.contrib.flatpages.models import FlatPage
> from django. contrib. sites, models import Site
> fp = FlatPage.objects.create(
u r1=/about/,
title=About,
content=<p>About this site...</p>,
enable_comments=False,
template_name=,
registration_required=False,
...

> fp. sites, add (Site, objects, get (id=1))


> FlatPage. objects. get(url=/about/)
<FlatPage: /about/-About>


flatpages/def ault.html, template_name FlatPage
.
flatpages/default.html
. flatpages,
default.html.

flatpage, Flatpage.
flatpages/def ault. html:

347

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"


http://www.w3.org/TR/REC-html40/loose.dtd>
<html>
<head>
<title>{{ flatpage.title }}</title>
</head>
<body>
{{ flatpage.content|safe }}
</body>
</html>

, sa fe ,
HTML- fla tp a g e .c o n te n t
.

Django
,
. , Django:
/m usic/ /sectio n s/a rts/m u sic/ .
, : -
, .


:
1. INSTALLED_APPS d ja n go .co n trib . r e d ir e c t s .
2. MIDDLEWARE_CLASSES d ja n go .co n trib .
re d ire c ts , middleware. R e d irectFallb a ckM id d le w a re .
3. manage, py syncdb,

.
manage. syncdb d ja n g o _ re d ire c t,
s it e _ id , old_path new_path.

, API .
. ,
.

R ed irectFallbackM iddlew are.
Django 404,

URL old_path s it e _ id ,
SITE_ID . ( SITE_ID .
.) :

16. django.contrib

348

1. new_path,
URL new_path.
2. new_path,
410 (Gone) .
3. , .
---------------------------------------------------------------------------------------------------
404 ( ) - 500
( ) . ,
MIDDLEWARE_CLASSES . ,
RedirectFallbackM iddleware
, .

------------------------------------------------------------------------------------------------ ,
, .
, (
FlatpageFallbackMiddleware , RedirectFallback
Middleware), .

,

,
.


Django ,
Redirects.
, .

Python API
Django,
d ja n go /co n trib /re d ire cts/m o d e ls..
API ,
:
> from django.contrib.redirects.models import Redirect
> from django.contrib.sites.models import Site
>>> red = Redirect.objects.create(
site=Site.objects.get(id=1),
old_path=/music/,
new_path=/sections/arts/music/,

CSRF

349

>*
> Redirect.objects.get(old_path= /music/)
<Redirect: /music/ ---> /sections/arts/music/>

CSRF
django.contrib.csrf HTTP-
CSRF (cross-site request forgery),
. ,
URL ,
,
. ,
, .

CSRF-
,
example.com.
U R L example.com/logout. ,
example.com/logout.
example.com/
logout, URL <if rame>
. ,
example, , ,
<if rame> example.com/logout,

example.com.
, - -
,
,
, ,
.
.

CSRF-
example.com,
( )
GET-.
POST-.
, ,
CSRF-.
, example.com
, <form> POST URL example, com/logout. ,
:

16. django.contrib

350
<input type=hidden name=confirm value=true>

POST- URL example.com/logout


;

POST, confirm
true.
, , CSRF ,
. ,
, <if rame>,
JavaScript.

CSRF-
- ? ,
, GET- .
, -
<if rame>, .
POST-. -
<form>, POST,
, .

, .
CSRF- Django.

CSRF
django. contrib.csrf : middleware, .
CsrfMiddleware, CSRF-.
, django.contrib.csrf.middleware.
CsrfMiddleware' MIDDLEWARE_CLASSES.
SessionMiddleware,
CsrfMiddleware SessionMiddleware (

). , ,
- ,
CsrfMiddleware GZipMiddleware.
CsrfMiddleware MIDDLEWARE_CLASSES .
. MIDDLEWARE_
CLASSES 15.
, CsrfMiddleware.

, POST-
csrfmiddlewaretoken,
.
, ,

aTaKCSRF

351

, ,
.

POST-,
cookie,
csrfmiddlewaretoken. ,
403 Cross Site R equest Forgery detected. Request
aborted. ( HTTP-. .)

, POST
.
,
POST ( POST-). ,
GET- ,
.
POST-, cookie, ,
,
.
,
HTML, Content-Type.
t e xt/html a p p lication/
xml+xhtml.

CSRF
C s r f M i d d l e w a r e
Django (. 14).
,
.
HTML- -
(, HTML
document.write JavaScript),
, .
. (
, C srfM i d d l e ware c s r f m i d d lewaretoken
HTML- ,
, HTML,
.) ,
,
csrfmiddlewaretoken.
CSRF- .
http://en.wikipedia.org/wiki/CSRF


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

352

16. django.contrib


d jango.co n trib.humanize ,

. ,
d j a n g o . c o n t r i b . h u m an i z e INSTALLED_APPS.
{% load hum a n i z e %}.
1.

apnumber
1 9,
, :
1
2 two
10 (10)
, .

intcomma
,
, :
4500 4,500
45000 45,000
450000 450,000
4500000 4,500,000
, .

intword

. ,
. 1
(1,000,000,000,000,000). :
1000000 1.0 million
1200000 1.2 million
1200000000 1.2 billion
, .


,
, . -

. . .

353

ordinal
, :
1 1st
2 2nd
3 3rd
254 254th
, .


django.contrib.markup ,
:

textile: Textile (http://en.wikipedia.org/wiki/

Textile_%28markup_language%291).

markdown: M arkdown (http://en.wikipedia.


org/wiki/M arkdown2).

restructuredtext: re s tru c tu re d Text (http://


en.wikipedia.org/wiki/ReStructuredText).


HTML. ,
textile Textile HTML:
{% load markup %}
{{ object.content|textile }}

, django. contrib. markup


INSTALLED_APPS.
{%load markup %}.
( django/contrib/markup/templatetags/markup.py).

?
(CSRF,
. .) .
,
,
, .
Django ,
.
1

h ttp ://
ru.w ikipedia.org/w iki/T extile_% 28_% 29. - . . .

http://

ru.wikipedia.org/wiki/Markdown. - . . .

17


, Django.
,
, . .
,

.

. ,
.

,
14,
(,
request.session request.user).

,
15, - , ,
,
.

,
CSRF- ( 16)
.


,
.

355

?
.
Django
(. 12).
, ,
IP- (request.META[REMOTE_IP])
, , .
,
HTTP- X-Forwarded-For,
IP - .
,
, -,
, IP - , , META[REMOTE_ADDR]:
class SetRemoteAddrFromForwardedFor(object):
def process_request(self, request):
try:
real_ip - request.META[HTTP_X_FORWARDED_FOR']
except KeyError:
pass
else:
tt HTTP_X_FORWARDED_FOR IP-,
tt . .
real_ip = real_ip.split( V )[0]
request.META[REMOTE_ADDR *] = real_ip

---------------------------------------------------------------------------------------------------- - X-Forwarded-For, Django


request.[HTTP_X_FORWARDED_FOR ].
, content-length content-type,
request.
,
_.

(.
), X-Forwarded-For
request.META[REMOTE_ADDR].
Django ,
- ;
request.[REMOTE_ADDR] ,
- .
,
Django.
django.middleware, http, .

17.

356


,
;
, .
, .
,
MIDDLEWARE_CLASSES .
, Python
. , ,
MIDDLEWARE_CLASSES ,
django-admin.py startproject:
MIDDLEWARE_CLASSES = (
django.middleware.common.CommonMiddleware,
django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware' ,

)
Django
, MIDDLEWARE_CLASSES
.
CommonMiddleware, .
.
Django
,
MIDDLEWARE_CLASSES,
- . ,
- :

, - .



, ,
.

:_init__(self)
_init__()
.


. , _init__()
- , -
.

357

_init__() , ,
. _init__() django.
core.exceptions.MiddlewareNotUsed, Django
. , ,
,
, , ,
, .
_init__(),
, self.

: process_request(self, request)
- ,
Django URL ,
. HttpRequest,
.
process_request() None,
HttpResponse.

None Django
, - ,
.

HttpResponse Django
,
.

:
process_view(self, request, view, args, kwargs)
,
Django , ,
.
, . 17.1.
17.1. , process_view()

request

HttpRequest.

view

Python, Django
. , .

args

,
, request
( ).

kwargs

,
.

17.

358

process_request(), process_view()
None HttpResponse.

None Django
, ,
.

HttpResponse Django
,
.

:
process_response(self, request, response)
,
.
. - HTML-
gzip.
: request , response - , .
,
None, process_response()
HttpResponse. ,
(, ), .

:
process_exception(self, request, exception)
,
.
,
.
request
exception - ,
.
process_exception() None
HttpResponse.

None Django ,
.

HttpResponse Django
.

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

359

. - Django
http://code.djangoproject.com/wiki/ContributedMiddleware
, .


Django
. .


: django. con t rib. auth.middleware.AuthenticationMiddleware.
.
HttpRequest, ,
request.user,
.
. 14.


: django.middleware.common.CommonMiddleware.
.

,
DISALLOWED_USER_AGENTS. ,
,
user-agent
. :
import re
DISALLOWED_USER._AGENTS = (
re.compile(r'"OmniExplorer_Bot'),
re.compile(r"Googlebot1)

)
import re. ,
DISALLOWED_USER_AGENTS
(
re.compile()). -
Python,
, import.

URL
APPEND_SLASH PREPEND_WWW. APPEND_SLASH
True, URL,
, URL,
,

360

17.

. , foo.com/bar foo.com/bar/, foo.


com/bar/f ile.txt .
PREPEND_WWW True, URL,
www., URL,
W W W .
URL. ,
URL.
URL- example.com/bar, example.com/
bar/ www.example.com/bar/ .
,
, URL .

ETag
USE_ETAGS . ETag
HTTP. USE_ETAGS
True, Django
ETag -

Not Modified.

,
GET- (. ), , ,
ETag.


: django.middleware.gzip.GZipMiddleware.
,
gzip ( ).
-.

.
,
, , ,
.

GET-
: django.middleware.http.ConditionalGetMiddleware.
GET-.
Last-Modified ETag If-NoneMatch If-Modified-Since,
304 ( ). ETag
USE_ETAGS, , ETag
. ,
CommonMiddleware.

361

HEAD
Date Content-Length.

-
( X-Forwarded-For)
: django.m iddlew are.http.SetRemoteAddrFromForwardedFor.

? . request.
META[REMOTE_ADDR ], re q u e st.[ __
F0RWARDED_F0R ], . ,
-,
REMOTE_ADDR 127.0.0.1.
--------------------------------------------------------------------------------------------------------- HTTP_X_F0RWARDED_F0R.
-,
HTTP_X_F0RWARDED_F0R,
.
HTTP_X_F0RWARDED_F0R,
REM0TE_ADDR, , 1-.
,
HTTP_X_F0RWARDED_F0R.


: d jango .co ntrib.sessio ns.m id dlew are.Sessio nM id dlew are.
. . 14.


: django.middleware.cache.UpdateCacheM iddleware django.
middleware, cache. FetchFromCacheMiddlewa re.


Django . 15.


: django.m iddlew are.transaction.TransactionM iddlew are.
COMMIT ROLLBACK
.
, COMMIT,
, ROLLBACK.
.
, ,

362

17.

Django - . ,
, ,
.
.
.

?
-
.
,
, , 1980- .

18


Django ,
.
.
.


Django SQL-,
Python,
.
.
Django ,
.
in spectdb manage, in sp e ctd b .

inspectdb
inspectdb ,
,
Django P ython
.

. , Django
.
1. Django django-adm in.py star tp ro je c t m ysite
( mysite - ).
2. m y site / se ttin g s.p y
, . -

364

18.

, DATABASE_NAME, DATABASE_ENGINE,
DATABASE_USER, DATABASE_PASSWORD, DATABASE_HOST DATABASE_PORT. (
, . 5.)
3. Django, python
mysite/manage.py startapp myapp ( myapp - ).
4. python mysite/manage.py inspectdb.
DATABASE_NAME
. ,
, inspectdb.
5. models.
:
python mysite/manage.py inspectdb > mysite/myapp/models.

6. mysite/myapp/models.,
.
.


,
,
. ,
.

(

). , ,
--,
ManyToManyField.


, .
, , Django
id, .
:
id = models.IntegerField(primary_key=True)

,
.

(, CharField, DateField)
(, VARCHAR, DATE). inspectdb ,
, TextField
This field type is a guess (
) .
.

365

Django,
. Django
.


Python (, pass, class for), inspectdb
_field,
db_column .
, INT for,
:
for_field = models.IntegerField(db_column=for)

inspectdb Field renamed


because it was a Python reserved word ( ,
Python).

,
( ), , ,
. ,
Book Foreign Key,
Author, Author Book.
,
, ,
.

inspectdb
PostgreSQL, MySQL SQLite,
primary_key=True.

, Django ,
primary_key=True.

inspectdb
PostgreSQL MySQL.

IntegerField ,
INT.


Django
,

.
, LDAP-,
. ,

LDAP- Django.

366

18.

Django
.

,
.


Django
. django.contrib.auth.
authenticate() (. 14), Django
,
. , Django
, .
AUTHENTICATION_BACKENDS. , Python,
,
. ,
Python.
AUTHENTICATION_BACKENDS
:
('django.contrib.auth.backends.ModelBackend,)


.
AUTHENTICATION_BACKENDS
:
, Django
.


,
: get_user(id) authenticate(**credentials).
get_user id,
, ,
User.
authenticate
.
:
class MyBackend(object):
def authenticate(self, username=None, password=None):
# User.

,
:

367

class MyBackend(object):
def authenticate(self, token^None):
tt User.

authenticate
User,
.
None.
Django User,
Django ,
. , User
,
(LDAP-, . .).
, ,
authenticate , Django
.
,
,
settings.,
Django User.
from django.conf import settings
from django.contrib.auth.models import User, check_password
class SettingsBackend(object):
, ADMIN_LOGIN ADMIN_PASSWORD.
, :
ADMIN_LOGIN = admin
ADMIN_PASSWORD = 'Sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de

def authenticate(self, username=None, password=None):


login_valid = (settings.ADMIN_LOGIN == username)
pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
if login_valid and pwd_valid:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
tt .
tt , ;
tt settings, .
user = User(username=username,
password^get from settings.py)
user.is_staff = True
user. ,is_superuser = True
user.save()

368

18.
return user
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None

.
Django.


-
Django -
, .
- Apache,
httpd.conf, URL . ( 12
Django Apache + m od_python,
,
.)
, URL Django
, httpd.conf.
(. 12) , Django
:
<Location " / " >
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonDebug On
</Location>

<Location /"> , Django


URL, .
<Location>
. , ,
, , a Django
/admin/,
-.
<Location> /admin/:
<Location 7admin/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonDebug On
</Location>

369

Django URL,
/admin/, ,
.
, Django URL (
/admin/) . Django
URL (, /admin/people/person/add/),
(/people/person/add/). ,
URL /admin/.

?

Django:
50 !
Django ( ). ,
Django-.

19

Django
,

55 . ,
, Django
.
.
,
.
- ,
.

,
,
,
,
. (internationalization)
I18N ( 18 -
/ N).
-

( ).
(localization) L10N.
Django ;
,
, (, ),
. Django 50
. ,
Django .

371

.

,
Django:
, .
Django ,
.
Django :

,
.

,
Django
.

---------------------------------------------------------------------------------------------------- Django GNU gettext (http://www.


gnu.org/software/gettext/),
Python gettext.

Django
:
1. Python- .
2. .
3.
.
.


Django
, .
,
USE_I18N = False.
Django
.
django.core.
context_processors.i18n TEMPLATE_CONTEXT_PROCESSORS.

372

19.


,
. , .
;
, .

Python

ugettextQ.
_.
Welcome to my s ite
:
from django.utils.translation import ugettext as
def my_view(request):
output = _(Welcome to my site.)
return HttpResponse(output)

, :
from django.utils.translation import ugettext
def my_view(request):
output = ugettext(Welcome to my site.)
return HttpResponse(output)

,
:
def my_view(request):
words = [Welcome, to, my, 'site.']
output = _(' '.join(words))
return HttpResponse(output)

.
:
def my_view(request):
sentence = Welcome to my site.
output = _(sentence)
return HttpResponse(output)

------------------------------------------------------------------------------------------- ,
, Django
, django-admin.py makemessages, .
.

373

, _() ugettextQ,
,
. :
def my_view(request, m, d):
output = _(Today is %(month)s %(day)s .) % {month: m, day: d}
return HttpResponse(output)


. , Today is November 26 -
: 26 .
( ).

(, %(day)s),
(, %s %d), 1.

.


django.utils.translation.ugettext_noop()
, .
.
-,

, , , ,
,
.


django.utils.translation.ugettext_lazy()
,
.
,
:

help_text

from django.utils.translation import ugettext_lazy


class MyThing(models.Model):
name = models.CharField(help_text=ugettext_lazy(This is the help text'))

ugettext_lazy()
1, . ,
, ,
Django.

, ( ugettext) ,
, . - . . .

374

19.

ugettext_lazy() , Python
Unicode ( Unicode).
, ( str)
, ugettext_lazy() ,
. Unicode
,
Python. :
tt : - Unicode1 Unicode.
uHello %s" % ugettext_lazy(people)
tt He , Unicode
tt ( - Unicode)

Hello %s" % ugettext_lazy(,people)

- "hello <django.utils,
,
, ugettext_lazy().
.
functional...>,

ugettext_lazy,
_ ( ):
from django.utils.translation import ugettext_lazy as
class MyThing(models.Model):
name = models.CharField(help_text=_(This is the help text))

Django .
(
).
, Meta verbose_name
verbose_name_plural ,
, Django :
from django.utils.translation import ugettext_lazy as
class MyThing(models.Model):
name = models.CharField(_('name), help_text=_('This is the help text'))
class Meta:
verbose_name = _(my thing')
verbose_name_plural = _('mythings)


, -
, django.utils,
translation.ungettext(). :
from django.utils.translation import ungettext

, U ni
code. - . . .

375

def hello_world(request, count):


page = ungettext('there is %(count)d object,
there are %(count)d objects, count) % {
'count': count,

}
return HttpResponse(page)

ungettext :
,
( count)1.


Django
,
Python. ,
{%load i18n %}.
{% trans %} (
), :
<title>{% trans "This is the title." %}</title>
<title>{% trans myvar %}</title>

noop, ,
. ,
, :
<title>{% trans "myvar noop %}</title>

{% trans %}
. ,
, {% blocktrans %}:
{% blocktrans %}This string will have {{ value }} inside.{% endblocktrans %}

(,
),
{% blocktrans %}:
{% blocktrans with value|filter as myvar %}
This will have {{ myvar }} inside.
{% endblocktrans %}

and:

{% blocktrans with book|title as book_t and author|title as author_t %}


This is {{ book_t }} by {{ author_t }}

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

376

19.
{% endblocktrans %}

(
) {% plural %},
{% blocktrans %} {% endblocktrans %}. :
{% blocktrans count list|length as counter %}
There is only one {{ name }} object.
{% plural %}
There are {{ counter }} {{ name }} objects.
{% endblocktrans %}


ugettext/ungettext. RequestContext
, :

LANGUAGES - , , - (
).

LANGUAGE_CODE -
, : en-us (. Django
).

LANGUAGE_BIDI - . True
, (, ),
a False - (, , . .).

RequestContext ,
:
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_current_language_bidi as LANGUAGE_BIDI %}

, {%load

i18n

%}.


, .
_():
{% some_special_tag _(Page not found) value|yesno:_(yes,no") %}

, ,
.
---------------------------------------------------------------------------------------------------- "yes,,
"yes " .
, ,
. , "yes,
", .

377


ugettext_lazy() ungettext_lazy()
.
,
,
( ).
,
.

: string_concat()

Python (\join([...])) ,
. django.
utils.translation.string_concat(),
, ,
. :
from django.utils.translation import string_concat
tt . . .

name =' ugettext_lazy(uJohn Lennon)


instrument = ugettext_lazy(uguitar)
result = string_concat([name, ': , instrument])

,
result, , result
( ).

allowJazy()
Django (
django.utils), . ,
.
,
: , -
. ,
(
).
django.utils,
functional.allow_lazy(). ,

, ,
. :
from django.utils.functional import allow_lazy
def fancy_utility_function(s, ...):
tt - s

378

19.

fancy_utility_function = allow_lazy(fancy_utility_function, Unicode)

, allow_lazy()
(*args), ,
. Unicode
,
Unicode.
,
, ,
.


,
( ). ,
.


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


.
,
. .
Django , django-admin.py makemessages,
.
,
( de - , ):
django-admin.py makemessages -1 de

. , pt_BR -
, a de_AT -
.
:

379

Django.

Django.

Django ( , Subversion, ,
, SPYTHONPATH).
, Django.


, .
( ) locale/LANG/LC_MESSAGES.
locale/de/LC_MESSAGES/django.po.
django-admin.py makemessages
.html. ,
--extension -:
django-admin.py makemessages -1 de - txt

,
-extension ( -) :
django-admin.py makemessages -1 de - html,txt -e xml

JavaS cript (. )
djangojs, - js.

Gettext ?

makemessages

gettext ,
.

django-admin.py

gettext,
(locale/en/LC_MESSAGES/django.po),
, .
.

Windows?
Windows
GNU gettext,
django-admin makemessages, gettext
Windows .
- . -
, , ,
, -
. - ,
.

380

19.

, Django
Welcome to my site.:
_(Weicome to my site.")

to django-admin.py makemessages -,
:
path/to/python/module, :23
msgid Welcome to my site.
msgstr

tt:

msgid - , .
.

msgstr - , . ,
.
.


(, #),
,
.

- , ,
msgstr ( msgid), .
,
.
. ,
!

, :
django-admin.py makemessages -


( )
, ,
gettext. django-admin.py
compilemessages.
- mo- , gettext. django-admin.
compilemessages , djangoadmin.py makemessages:
django-admin.py compilemessages

. .

381

Django

Django
(
, Django)
.
Django
: ,
.
,
LANGUAGE_CODE. Django
,
.
, Django
, ,
LANGUAGE_CODE, .
,
,
LocaleMiddleware. ,
.
LocaleMiddleware,
django.middleware.locale.LocaleMiddleware MIDDLEWARE_CLASSES.
,
:

SessionMiddleware,
.

CacheMiddleware,
.

MIDDLEWARE_CLASSES

LocaleMiddleware

MIDDLEWARES LASSES = (
django.contrib.sessions.middleware.SessionMiddleware,
django.middleware.locale.LocaleMiddleware,
django.middleware.common.CommonMiddleware,

)
. 17.
LocaleMiddleware
, :
1.
.

django_language

2. , cookie.
3. cookie , HTTP- AcceptLanguage. , -

382

19.

. Django
,
, .
4. ,
LANGUAGE_CODE.
:

,
. ,
pt-br.

, ,
Django . ,
de-at ( ),
de, de.

, LANGUAGES.

( ),
LANGUAGES . :
LANGUAGES = (
( d e '. _ ( German)),

('en, _( English)),

)

( , , de-ch en-us).

LANGUAGES, ,
,
- ugettextO,
django.utils.translation.
django.utils.translation ,
,
.
, - ugettext(),
:
ugettext = lambda s: s
LANGUAGES = (
(de, ugettext(German)),
(en, ugettext(English')),

django-admin.py makemessages
,
. -

383

ugettext() ,
LANGUAGES.

LocaleMiddleware ,
Django.
,
Django.
, Django
,
, .
-
(, ,
).
-
. , ,
;
. , DATETIME_
FORMAT ( DATE_FORMAT, TIME_FORMAT) ,
. ,
now.

LocaleMiddleware ,
request.LANGUAGE_CODE HttpRequest.
. :
def hello_world(request):
if request.LANGUAGE_CODE == de-at':
return HttpResponse(You prefer to read Austrian German.)
else:
return HttpResponse(You prefer to read another language.)

, (
)
settings.LANGUAGE_CODE, - request.
LANGUAGE_CODE.



Django :
1. locale ,
.
, .
2. locale .
, .
3. ,
locale.

django/conf/

19.

384

, ,
,
.

. .
:

$APPPATH/locale/<language>/LC_MESSAGES/django.(po|rno)

$PROJECTPATH/locale/<language>/LC_MESSAGES/django.(po|rno)

<language>/LC_MESSAGES/django.(po|rno)
, LOCALE_PATHS,

$PYTHONPATH/django/conf/locale/<language>/LC_MESSAGES/django.(po|rno)

djangoadmin.py makemessages, Django.


- ,
conf/locale ( )
locale/ ( ).
-, get text,
django-admin.py compilemessages, .
django-admin.py compilemessages
-,
, LOCALE_PATHS.

--settings=path.to.settings,

,
LocaleMiddleware.
,
Django .
, .

,
.

makemessages:
,
,
.
,
( ,
), .
django-admin.py makemessages
, , ,
, .

setjanguage

385

setjanguage
Django
django.views.i18n.set_language,

.
URL
:
("i18n/, include(django. conf.urls. i18n)),

---------------------------------------------------------------------------------------------------- /i18n/setlang/.

, POST
language.
,
.
cookie django_language. (
, LANGUAGE_COOKIE_NAME.)
, Django
, :

Django

, Django
URL Referer.

(,
),
(/).

next

POST-.

HTML- :
<form action=/i18n/setlang/ method=post>
cinput name=next type="hidden value=/next/page/ />
<select name=language>
{% for lang in LANGUAGES %}
coption value={{ lang.O }}>{{ lang.1 }}</option>
{% endfor %}
</select>
<input type=submit value=Go />
</form>

JavaScript
JavaS cript-
:

386

19.

JavaS cript
gettext.

JavaS cript
mo-; .

JavaS cript
.

Django :
JavaS cript , JavaScript
gettext .

javascript_catalog
javascript_catalog;
JavaS cript-, ,
gettext, .
, Django
, info_dict URL.
:
js_info_dict = {
packages : ( your.app.package,),
}

urlpatterns - patternsC,
( r "jsi18n/$ , django.views.i18n.javascript_catalog, js_info_dict),
)

packages
Python ( ,
INSTALLED_APPS)
, locale. ,
. , JavaScript .
,
URL:
urlpatterns = patternsC,
( ~jsi18n/(?P<packages>\S+)/$ , django.views.i18n.javascript_catalog),
)

,
URL +. ,
,
, .
django.conf
, INSTALLED_APPS.

JavaScript

387

JavaScript
,
:
<script type=text/javascript src=/path/to/jsi18n/"x/script>


. , JavaS cript-
get text:
document.write(gettext(this is to be translated));

ngettext:

var object_cnl = 1 // 0, 2, 3, ...


s = ngettextC literal for the singular case,
literal for the plural case, object_cnt);

:
function interpolate(fmt, obj. named);

Python,
interpolate ,
:

: obj JavaS cript- Array,



. :
fmts = ngettext(There is %s object Remaining: %s,
There are %s objects. Remaining: %s, 11);
s = interpolate(fmts, [11, 20]);
// s - There are 11 objects. Remaining: 20

: ,
named true. obj
JavaS cript . :
d - {
count: 10
total: 50

};
fmts = ngettext(Total: %(total)s, there is %(count)s object,
there are %(count)s of a total of %(total)s objects, d.count);
s = interpolate(fmts, d, true);

; JavaScript,
. ,
Python,
, (,
ngettext ).

19.

388

JavaScript
,
Django: djangoadmin.py makemessages. ,
-d djangojs:
django-admin. makemessages -d djangojs -1 de


JavaS cript. ,
django-admin. compilemessages ,
Django.

,
gettext
gettext, , ,
Django:

django djangojs. ,
,
( /usr/share/locale/). django
Python ,
, ,
. djangojs
JavaS cript, ,
.

Django xgettext .
xgettext msgfmt, Python.

gettext Windows
,
(-).
-,
,
,
gettext.
1. ZIP- http://sourceforge.net/
projects/gettext:

gettext-runtime-X.bin.woe32.zip

gettext-tools-X.bin.woe32.zip

libiconv-X.bin.woe32.zip

2.
utils).

(C:\Program

Files\gettext-

389

3.

PATH:

a. -> - - .
b. Path
.

c.

;C:\Progran Files\

gettext-utils\bin.

gettext ,
xgettext --version . ,
0.14.4 .
Django
gettext, xgettext --version
Windows xgettext.
.

?
:
.

20

.

. : ,
;
, ;

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

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

, .
, Django.


,
-:

SQL

391

,
.
, -.
, , ,
, .
, ,
. (
), (HTTP-, cookie
. .). ,
, - .
:
, ,
.
: ?.

SQL
SQ L1- ,
- (
GET/POST URL),
SQL- .
, , ,
.
, SQL-
.
, , ,
.
,
:
def user_contacts(request):
user = request.GET[username']
sql = SELECT * FROM user_contacts WHERE username = %s'," % username
tt SQL-. ..

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

.
. ,
;

SQL. - . ..

20.

392

. , ,

OR =.
SQL-:
SELECT * FROM user_contacts WHERE username = ' OR a = a ;


, OR,
.
. , ,
; DELETE FROM user_
contacts WHERE a = . (
SQL-):
SELECT * FROM user_contacts WHERE username = ';
DELETE FROM user_contacts WHERE a = 'a';

! .

,
: , ,
SQL-.
API Django :
SQL-,
, (,
PostgreSQL MySQL).
, API
foo.get_list(bar__exact="' OR 1=1)

Django ,
:
SELECT * FROM foos WHERE bar = V

OR 1=1'

.
A PI
:
where extra().
SQL-; .

, API
(. 10).

.

. , ,
, :

(XSS)

393

from django.db import connection


def user_contacts(request):
user = request.GET['username]
sql = "SELECT * FROM user_contacts WHERE username = %s
cursor = connection.cursor()
cursor.execute(sql, [user])
tt . ..

execute SQL-
%s
, ,
. ,
SQL- .
, ;
SQL
( ). ,
, POST-,
.
Django django.db.connection.ops.quote_name,
, ,
.

(XSS)
(cross-site scripting - X S S )
, -
HTML-.

HTML-, <script>.
XSS- cookie
,
().
,
,
. :
from django.http import HttpResponse
def say_hello(request):
name = request.GET.get('name. world)
return HttpResponse(<h1>Hello. %s!</h1> % name)

GET- HTML. URL http://example.com/hello/?name=Jacob


:
<h1>Hello, Jacob!</h1>

394

20.

. , URL http://example.
com/hello/?name=<i>Jacob</i>? :
<h1>Hello, <i>Jacob</i>!</h1>

, <i>;
URL HTML-
, . ,
, ,
- ,
, .
, ,
. , MySpace
XSS- .
JavaS cript-,
, .
.
, , ,
,
( , MySpace) .

MySpace.
MySpace ,
, ,
-
- .

: ,
, HTML-.
Django
. , ,

:
tt views,

from django.shortcuts import render_to_response


def say_hello(request):
name = request.GET.get('name. world)
return render_to_response(hello.html1, {name: name})
tt hello, html

<h1>Hello, {{ name }}!</h1>

URL http://example.com/hello/name=<i>Jacob</i>
:

HTTP-

395

<h1>Hello, &lt;i&gt;Jacob&lt;/i&gt;!</h1>

4,
, .
, :
?.
XSS-.

-
H T T P - (cross-site request forgery - CSRF)
,
,
, .
Django . (
16.)


- , ,
, .
:
,
(
).

(session forging),
(,
), .
,
,
, cookie.
cookie,
.

cookie, cookie,
.
14 cookie ,
, cookie
.
, cookie -
IsLoggedIn=1 LoggedlnAsllser^jacob.
.
, cookie.
, .

396

20.

,

.
,
URL (ht tp://example. com/?PHPSESSID=f a90197ca25f 6ab40bb1374c510d
7a32).
,
.
,

, .
.

,

, .
- , cookie
(, ).
,
.
, XSS-.
,
.

URL .
Django ( 14)
URL.

cookie .
, ,
.
, Django (request.session) .
cookie ,
.

,
. XSS-
,
, .
.


.
,
Django

397

. - ,
,
.
,
.
,
,
.
,
HTTPS. ,
SSL-, SESSI0N_C00KIE_
SECURE True, Django cookie
.


SQL -
. -,
.

. ,

.
,
.
,
.
(
, - ).
Subject .
,
- hello\ncc:spamvictim@example.com ( \ -
). :
: hardcoded@example.com
Subject: hello
: spamvictim@example.com

, SQL, - ,
,
.

,
SQL:
.

20.

398

Django (
django.core.mail)
, (
, ).
django.core.mail.send_mail ,
, Django BadHeaderError.
Django
, :
,
.
SafeMIMEText, , Django.


- ,
,
, ,
, , .
, ,
:
def dump_file(request):
filename = request.GET[filename]
filename = os.path.join(BASE_PATH, filename)
content = open(filename).read()
tt ...

, ,
BASE_PATH ( os. path.join).
, .. (
),
BASE_PATH. ,
, ,

/et c/passwd.
, , . ,
,
.
- ,
, .
Ruby on Rails. 2006 R ails
URL http://example.eom/person/poke/1,
.
URL ,
!

399

,
,

.
---------------------------------------------------------------------------------------------------- ,
!

Django
,
( django.views, static). :
import os
import posixpath
tt . . .

path = posixpath.normpath(urllib unquote(path))


newpath = 11
for part in path.spli1(/'):
if not part:
tt
continue
drive, part = os.path.splitdrive(part)
head, part = os.path.split(part)
if part in (os.curdir, os.pardir):
tt ' .
continue
newpath = os.path.join(newpath, part).replace('\ Y , '/)

Django (
static.serve, , , ),
.
, URL , Django
, .
URL, Django
, URL.



. ,
Django
.

20.

400


,
.

. Django ,
, .

, -
Python ( ).
.
, ,
.
,
.

12 ,
Django DEBUG.
, False.
Apache 4- m od_python ( 12)
Apache
PythonDebug Off; ,
Django.


,
. , , ,
, .
,
; ,
-
- ? ,

-.
.

?
.
, Django.
Django-,
Google.

IV



5
.
.
.
, , API ,
Django
.
http://docs.djangoproject.
/.

- -
.
,
Field. Django
:

(INTEGER, VARCHAR . .).

,
Django,
(<input type=text>, <select> . .).

,
.


. , (ForeignKey .),
.

404


Django
:


Python,
. :
class Example(models.Model):
pass = models. IntegerField() tt pass - !


-
Django. :
class Example(models.Model):
foo_bar = models. IntegerField() tt foo__bar'
tt !

, ,
(.
db_column ).
SQL, join, where, select,
,
Django SQL-,
,
.

AutoField
IntegerField, .
;
Django .

BooleanField
, true/false.

MySQL...
MySQL TINYINT
0 1 (
BOOLEAN ). MySQL -
BooleanField 0
1, True False.

405

, Python ,
1 == True 0 == False .
, obj is True, obj .
MySQL, .
(
==).

CharField
.
( Text Field.)
CharField
: max_length. (
). Django,
.

CommaSeparatedlntegerField
, . CharField,
max_length .

DateField
, Python datetime.date.

DateTimeField
, Python datetime, datetime.

DecimalField
, Python
Decimal. :

max_digits - .

decimal_place - .

, 999 2
, :
models.Decimal Field( . . . . max_digits=5, decimal_places=2)

10
:
models.Decimal Field( . . . . max_d ig its = 19, decimal_places=10)

406

DecimalField decimal.
Decimal, , Python.

EmailField
CharField, ,
.

FileField
.
---------------------------------------------------------------------------------------------------- primary_key unique
;
.

:
upload_to

,
MEDIA_R00T django.core.files.
File.url.

,
strftime (. time
Python).
( ).
, ,
;
.
UNIX- (
), .
. .1.
. , uploadjto

instance

, F ileField.
, ,
.

,
AutoField,

.
fllename

.
.

407

:
storage

: ,
.
FileField
ImageField (. ImageField),
.
1. MEDIA_R00T , Django
(
). , MEDIA_URL -
URL, . , -
.
2. FileField ImageField
uploadjto, Django,
MEDIA_R00T .
3. (
MEDIA_R00T). Django url(). ,
ImageField mug_shot,
URL {{ object.mug_shot.url }}.
, , MEDIA_R00T /home/media,
upload_to photos/%Y/%m/%d. %Y/%m/%d
strftime:
%Y - , % - ,
%d - . , 15
2007, /home/media/photos/2007/01/15.
, URL,
, ,
name, url size.
, ,
,
.
, ,
. ,
-,
CGI- -,
URL, . .
FileField
varchar(IOO). ,
max_length.

408

FilePathField
CharField,
.
,
:
path

. ,
, . , /home/images.
match

. ,
FilePathField.
,
. , foo.*\.txt$
foo23.txt , bar.txt foo23.gif - .
recursive

. True False, False. ,


path.
, .
, match
, .
/home/images/bar/foo.
gif, /home/images/foo/bar.gif,
match foo.gif bar.gif, :
FilePathField(path=/home/images, match=f o o . r e c u r s i v e = T r u e )

FilePathField
varchar(IOO). ,
max_length.

FloatField
, Python float.

ImageField
FileField, ,
.
:
height_field

,
.
width_field

,
.

409
, FileField,
ImageField height width -
.
Python Im aging Library,
http://www.pythonware.com/products/
pH/.
ImageField
varchar(IOO). ,
max_length.

IntegerField
.

IPAddressField
IP- (, 192.0.2.30).

NullBooleanField
Boolean Field,
NULL. BooleanField null=True.

PositivelntegerField

PositiveSmalllntegerField
PositivelntegerField, ,
( ).

SlugField
(slug) - ,
, , ,
. URL.
CharField, max_length.
max_length , Django
50.
db_index
True.

SmalllntegerField
IntegerField,
( ).

410

TextField
.

CharField.

TimeField
, Python datetime.time.
, , DateField.

URLField
CharField URL;
:
veri fy_exists

True ( ),
URL ( ,
, 404). ,
URL,
, ,
, .
.
CharField, URLField
max_length. ,
200.

XMLField
TextField, ,
XML-, .
:
schema_path

, RelaxNG,
. RelaxNG . http://www.
relaxng.org/.


.
.

null
True,
NULL; -

411

, , .
False.
,
, NULL. null=True
- , , ,
. blank=True,
,
null (.
blank).
null , CharField
Text Field, .
null=True,
: NULL .
; Django
, NULL.
---------------------------------------------------------------------------------------------------- Oracle null=True
, ,
NULL.

.
6.

blank
True, .
False.
, null.
, - .
blank=True,
Django .
blank=False, .

choices
(, ),
.
choices :
YEAR_IN_SCHOOL_CHOICES = (
( FR', 1Freshman'),
(SO, Sophomore'),
( ' JR', Junior ),
( ' SR , Senior ),
( ' GR , ' Graduate ),

412

-
, - .
choices :
class Foo(models.Model):
GENDER_CHOICES - (
(M, '),
( , '),

)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

:
GENDER_CHOICES = (
( , '),
( , ),

)
class Foo(models.Model):
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)


:
MEDIA_CH0ICES - (
( ' Audio , (
( ' v i n y l , Vinyl ),
( cd , CD'),

)
).
( Video , (
( vhs , VHS Tape' ),
( ' dvd', DVD ),

)
),
( unknown , Unknown ),

)
- , -
, ,
.

( unknown ).
, ,
, .
.
choices
( ForeignKey). choices
,
.

413

db_column
, .
, Django .
, -
SQL ,
Python ( , ). Django
.

db_index
True, django-admin. sqlindexes
CREATE INDEX.

db_tablespace
,
, .
DEFAULT_INDEX_TABLESPACE, , db_tablespace
, .
, .

default
;
.
.

editable
False,
,
. True.

help_text
,
.
,
.
,
HTML-, ,
. HTML. :
help_text=AaTy <>--</>."


django. utils, html. escapeQ.

414

primary_key
True, .
primary_key=True,
Django AutoField,
, primary_key=True ,
.
primary_key=True
null=False unique=True.
.

unique
True,
.
,
ModelForm (
). ,
save IntegrityError.

ManyToManyField, FileField ImageField.

unique_for_date
DateField DateTimeField,
,
.
, title, unique_for_
date=pub_date, Django
title pub_date.
,
ModelForm ( ),
.

unique_for_month
unique_for_date, .

unique_for_year
unique_for_date unique_for_month.

verbose_name
. ,
Django name,
.

415

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

ForeignKey
--.
- ,
.
,
-- , models.
ForeignKeyC self).

, ,
, :
class (models.Model):
manufacturer = models.ForeignKey(Manufacturer)
...
class Manufacturer(models.Model):
tt . ..

, , ,
models.. ,
,
. , , Manufacturer
production, :
class Car(models,Model):
manufacturer = models.ForeignKey('production.Manufacturer')

, Django
_id .
manufacturer_id (
, db_column).
,
SQL- . ,
.
ForeignKey
( ),
.

limit_choices_to
, ,
.
datetime . ,

416

, ,
pub_date :
limit_choices_to = {pub_date_lte: datetime,now}

limit_choices_to FormSet,

related_name
, .

to_field
, .
Django ,
.

ManyToManyField
--.
- ,
. , ForeignKey,
.
-- Django
.
.
,
64 ,
.
, author_books_9cdf4, -
. db_table
.
ManyToManyField
( ),
.

related_name
, related_name ForeignKey.

limit_choices_to
, limit_choices_to ForeignKey.
limit_choices_to , ManyToManyField
,
through.

417

symmetrical
ManyToManyField
self. :
class Person(models.Model):
friends = models.ManyToManyField("self)

Django

ManyToManyField ,
Person person_set. ,
ManyToManyField ( - , - ).

, --
, symmetrical False.
Django ,
ManyToManyField.

through
Django
--.
, through ,
.
, - .

db_table
--.
, ,
.

OneToOneField
--. ForeignKey
unique=True,

.
,
; ,
--
.
, .
, ForeignKey,
.
, OneToOneField
, ForeignKey, :

418

parentjink
True ,
() , ,
-
OneToOneField,
-.


Meta,
:
class Book(models.Model):
title = models.CharField(maxlength=100)
class Meta:
tt

, ,
, .
,
. Meta , .

abstract
True,
. , , . Django.

db_table
, :
db_table = music_album


Django
,
.
(, manage,
startapp), .
, bookstore ( manage,
startapp bookstore) Book,
bookstore_book.
,
db_table Meta.
, -
SQL ,

419

Python ( , ). Django
.

dbjtablespace
,
.
, .

get_latest_by
DateField DateTimeField. ,
latest Manager.
:
get_latest_by = "order_dateM

managed
True, Django
django-admin.py syncdb
reset. , Django
.
False,
.
,
, .
, True False .
, :

,
. ,
,
.

, managed=False, ManyField, ,
-- .

.
,
( managed,
) through.

, managed=False,

.

420

Python,
managed=False
. -.

ordering

:
ordering = ['-order_date]

.
-,
. ,
.
?.
---------------------------------------------------------------------------------------------------- ordering,
.

, pub_date
:
ordering = ['pub_date]

:
ordering = [-pub_date* ]

pub_date ,
author , :
ordering = ['-pub_date', 'author']

proxy
True, ,
, -. . Django.

unique_together
,
:
unique_together = (("driver", "restaurant"),)

. ,
ModelForm ( Django),
( CREATE TABLE
UNIQUE).

421

unique_together
,
:
unique_together = ("driver", "restaurant)

verbose_name
:
verbose_name = "pizza"

, Django
: CamelCase camel case.

verbose_name_plural
:
verbose_name_plural = "stories

, Django verbose_name + "s".


API

API Django API
, .
, API.
,
.
API , API ,
, Django
.
http://docs.
djangoproject.com/.
,
:
from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
def __unicode__(self):
return self.name
class Author(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
def _unicode__(self):
return self.name
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)

423

body_text = models.TextField()
pub_date = models.DateTlmeField()
authors - models.ManyToManyField(Author)
def __unicode__(self):
return self.headline



,
, save(), :
>>> from mysite.blog.models import Blog
> b = Blog(name='Beatles Blog, tagline='All the latest Beaties news.')
> b. save()

SQL- INSERT. Django


, saveQ.
.
, , .
create.

?
Django :
1. pre_save: ,
.
, .
. .
2. :

.
-
.
, , FileField.
3. :
,
.
.
, , .

. , DateField
Python datetime.
datetime ,
ISO- .

424

. API

4. :
SQL- INSERT.
5. post_save: pre_save,
, .



id, -
primary_key=True (. AutoField
).
AutoField,

saveQ:
>>> 2 = Blog(name=Cheddar Talk', tagline=Thoughts on cheese.')
>>> b2.id tt None, id 2
None
> b2.save()
>>> 2.id tt .
14

, id
, , Django.
AutoField,
ID,
id saveQ,
:
>>>
>
3
>
>>>
3

= 1(id=3, name='Cheddar Talk', tagline='Thoughts on cheese.')


b3. id
b3.save()
b3.id

,
,
!
, , Django
, ,
.
, Cheddar
Talk, :
> 4 = Blog(id=3, name^'Not Cheddar', tagline='Anything but cheese.')
> b4.save() tt ID=3!

425



, , .


save() ,
.
5 Blog ,
name
:
> 5.name = 1New name'
>>> b5.save()

SQL- UPDATE. Django


,
saveQ.

Django , UPDATE,
INSERT
, ,

saveQ. Django SQL INSERT UPDATE. , save()
Django :

,
True (
, None ), Django
SELECT,
.

, Django
UPDATE.


, Django
INSERT.


, ,
.
Foreign Key ;
:

426

. API
> joe = Author.objects.create(name="Joe")
> entry.author = joe
> entry. save()

Django
.


, :
> blogs = Blog.objects.filter(author__name__contains="Joe")

.
, Que
ry Set. , SQL-
.
QuerySet Manager
, , .
QuerySet .
, - ,
.
SQL QuerySet SELECT, -
WHERE.

QuerySet -
Manager. ,
objects.
:
> Blog.objects
<django.db.models.manager.Manager object at 0x137d00d>

,
;
:
>>> b = Blog(name=Foo, tagline='Bar')
> b.objects
Traceback (most recent call last):
File <stdin>", line 1, in <module>
AttributeError: Manager isn't accessible via Blog instances.

- QuerySet .
QuerySet,
. , Blog.objects - QuerySet,
Blog, .

QuerySet

427

QuerySet
QuerySet , -
.
,
.
QuerySet .
QuerySet, , Django
,
(, ,
QuerySet).
, .
,
QuerySet . ,
QuerySet,
:
print [.headline for in Entry.objects.all()]
print [e.pub_date for e in Entry.objects.al1()]

,
, . ,
, ,

- Entry.
, QuerySet
:
queryset = Poll.objects.all()
print [p.headline for p in queryset] tt .
print [p.pub_date for p in queryset] tt .


.
11():
>>> Entry.objects.al1()

QuerySet,
.
.
QuerySet,
. , filterQ () cludeQ:
> 2006 = Entry, objects, fi 1te(pub_date_year=2006)
>>> not2006 = Entry.objects.exclude(pub_date__year=2006)

428

. API

,
.


QuerySet QuerySet;
:
> qs = Entry.objects.filter(headline_startswith=What)
>>> qs = qs.exclude(pub_date__gte=datetime.datetime.now())
> qs = qs.filter(pub_date__gte=datetime.datetime(2005, 1, 1))

QuerySet, ,
, , ,
. QuerySet ,
What,
1 2005 .
, QuerySet
, QuerySet
.
;
, Django
QuerySet.
QuerySet :

: QuerySet - ,
.
QuerySet for:
qs = Entry.objects.filter(pub_date_year=2006)
qs = qs.filter(headline_icontains="bill")
for e in qs:
print e.headline

headline ,
2006 bill,
.

: QuerySet
().
Python, .

: QuerySet , QuerySet
, Python.
QuerySet ( ),
step, Django
.

: QuerySet
list(), :

429

> entry_list = 1ist(Ent.objects.al 1())

, ,
Django . ,
QuerySet
.

QuerySet
QuerySet
, .
QuerySet :
q1 = Entry.objects.f ilter(headline__startswith-What")
q2 = q1.exclude(pub_date__gte^datetime.now())
q3 = ql.filter(pub_date_gte=datetime.now())

QuerySet . ,
headline What.
,
pub_date . -
: ,
pub_date .
QuerySet (q1).

QuerySet
QuerySet,
,
. LIMIT OFFSET
SQL- SELECT.
, (LIMIT 5):
> Entry, objects.al 1 ()[ :5]

- (OFFSET 5 LIMIT 5):


> Entry, objects, al 1 ()[5:10]

QuerySet
QuerySet, .
,
step. ,
,
:
> Entry.objects.al 1 ()[: 10:2]

430

. API

, (, SELECT
foo FROM bar LIMIT 1),
. ,
Entry headline
:
> Entry, objects. order_by('headline)[0]

:
>>> Entry.objects. rder_by('headline)[0:1].get()

, , ,
,
IndexError, - DoesNotExist.

, QuerySet
QuerySet ,
,
SQL-. ,
,
.

filter(**lookup)
QuerySet, ,
.

exclude(**lookup)
QuerySet, ,
.

order_by(*fields)
, QuerySet,
, ordering
(. ).
order_by():
Entry.objects.filter(pub_date__year=2005).order_by('-pub_date,
'headline)


pub_date, headline.
-pub_date . ,
.
?, :
> Entry, objects. order_by('?)

,
.

431

Meta QuerySet order_by(),


.

distinct()
QuerySet, SQL-
SELECT DISTINCT, .
QuerySet .
,
Blog.objects.all() .
,
. distinct().

values(*fields)
QuerySet,
, .
:
tt Blog.
> Blog.objects.fi1ter(name_startswith=Beatles)
[Beatles Blog]
tt .
> Blog.objects.filter(name__startswith='Beaties).values()
[{id: 1, 'name': Beatles Blog, tagline: All the latest Beatles news.}]

values()
fields, , SELECT.
,
.
:
> Blog.objects.values()
[{id: 1, name: Beatles Blog, tagline: All the latest Beatles news.'}],
> Blog, objects. values( id, name)
[{id: 1, name: Beatles Blog}]

,
,
. ,
.

dates(field, kind, order)


QuerySet,
datetime.datetime,
, .
field DateField
DateTimeField . kind

432

. API

year, month day. datetime.datetime,


,
:

year,
.

month,
/ .

day,
// .

order ASC DESC


ASC. -
. :
> Entry, objects. dates('pub_date , year)
[datetime.datetime(2005, 1, 1)]
>>> Entry.objects.dates('pub_date, month)
[datetime.datetime(2005, 2, 1), datetime.datetime(2005, 3, 1)]
>>> Entry.objects.dates(pub_date, day)
[datetime.datetime(2005, 2, 20), datetime.datetime(2005, 3, 20)]
> Entry, objects. dates( pub_date, day, ordersDESC)
[datetime.datetime(2005, 3, 20), datetime.datetime(2005, 2, 20)]
> Entry.objects.filter(headline__contains=Lennon).dates(pub_date, day)
[datetime.datetime(2005, 3, 20)]

select_related()
Query Set,

.
(
), ,
, .
.

select_related().
:
tt .
> = Entry.objects.get(id=5)
tt Blog.
> b = . blog

select_related:
tt .
> = Entry.objects.select_related().get(id=5)

433

tt , .. e.blog
tt .

> b = . blog

select_related() .
:
class City(models.Model):
tt . . .

class Person(models.Model):
...
hometown = models.ForeignKey(City)
class Book(models.Model):
tt . . .

author = models.ForeignKey(Person)

Book.objects.select_related().get(id=4)
Person, City:
> b = Book.objects. select_related().get(id=4)
> p = b.author
tt .
> = p. hometown
tt .
> b = Book.objects.get(id=4) tt select_related().
> = b.author
tt .
> = p.hometown
tt .

, select_related() ,
null^True.
select_related()

.
,
.

, QuerySet
QuerySet ,
QuerySet, - : ,
. .

get(**lookup)
, ,
,
. ,
AssertionError.
DoesNotExist,
, .
DoesNotExist . :

. API

434

> Entry, objects, get(id=foo) tt Entry.DoesNotExist

django.core.exceptions.Object try
:
DoesNotExist

DoesNotExist,

> from django.core.exceptions import ObjectDoesNotExist


> try:
e = Entry.objects.get(id=3)
b = Blog.objects.get(id=1)
... except ObjectDoesNotExist:
print " , ."

create(**kwargs)
,
. :
> = Person(first_name="Bruce",
> p. save()

last_name="Springsteen")

:
>>> = Person.objects.create(first_name="Bruce", last_name="Springsteen")

get_or_create(**kwargs)
, ,
. (object, created), object -
, a created - , True,
.

:
try:
obj = Person.objects.get(first_name=John, last_name=Lennon)
except Person.DoesNotExist:
obj = Person(first_name=John, last_name=Lennon,
birthday=date(1940, 10, 9))
obj.save()


. get_or_create()
:
obj, created =
first_name
last_name
defaults

Person.objects.get_or_create(
= 'John ,
= Lennon,
= {birthday: date(1940, 10, 9)}

)
get () ,
get_or_create(), de-

435

faults. , get_or_create() ,
False. ,
get_or_create() , ,
True.
:
defaults = kwargs.pop('defaults, {})
params = diet([ (k, v) for k, v in kwargs. items() if
params.update(defaults)
obj = self.model(**params)
obj.save()

not in k])

.
, defaults ,
, (
).
defaults, .

.
defaults
get_or_create(),
defaults__exact:
Foo.objects.get_or_create(
defaults_exact = 'bar',
defaults={defaults: bar}

-------------------------------------------------------------------------- , get_or_create() ,
,
. get_or_create() ,
POST- (
). , GET-
; POST.

count()
, ,
QuerySet. count()
. :
# Entry .
> Entry.objects.count()
4
tt Entry, headline
tt Lennon

436

. API
> Entry.objects.filter(headline_contains^Lennon).count()
1

count() SELECT C0UNT(*),


,
Python
1() .
(, PostgreSQL MySQL) countQ
, Python.
.

in_bulk(idlist)

,
, :
>
{1:
>
{1:
>

Blog, objects,
Beatles Blog}
Blog, objects.
Beatles Blog,
Blog, objects.

in_bu 1k([ 1 ])
in_bulk([ 1, 2])
2: Cheddar Talk}
in_bulk([ ])

{}

. in_bulk() ,
.

latest(field_name=None)
,
field_name.
Entry , ,
pub_date:
> Entry, objects, latest(pub_date)

Meta get_latest_by,
. Django
get_latest_by.
f ield_name

get (), latest()


.

DoesNotExist,


- WHERE SQL.
filter(), exclude() get () QuerySet.

437

, ,
field__lookuptype=value (
, ). :
> Entry.objects.fiIter(pub_date_1te='2006-01-011)

SQL-:
SELECT * FROM blog_entry WHERE pub_date <= 2006-01-01;


.
.

exact
.
> Entry.objects.get(headline_exact="Man bites dog")

,
Man bites dog.

headline

, ,
, ,
(exact). ,
:
> Blog.objects.get(id_exact=14)
> Blog.objects.get(id=14)

tt
tt _exact

,
.

iexact
.
> Blog.objects.get(name_iexact=beatles blog)


BLoG . .

Beatles Blog, beatles blog, BeAtLes

contains
.
Entry, objects, get(headline__contains=Lennon')

Today Lennon honored ,


today lennon honored - .
SQLite LIKE ,
contains icontains.

438

. API


LIKE
,
SQL LIKE (iexact, contains, icontains, startswith, istartswith, endswith iendswith), Django
:
. ( LIKE
, -
.)

, .
, , headline
, :
Entry.objects.filter(headline_contains^% )

Django. SQL- :
SELECT ... WHERE headline LIKE %\%%';

To .

icontains
.
> Entry.objects.get(headline_icontains^Lennon)

contains, ,
today lennon honored.

head

line

gt, gte, It, Ite


, , , .
>
>
>
>

Entry, objects,
Entry, objects,
Entry, objects,
Entry, objects,

filter(id__ gt=4)
fiIter (id__ 11=15)
filter(id__lte=3)
filter(id__gte=0)

,
id 4, 15, 3
0.
.
,
(, 4"
"10").

439

in
,
:
Entry.objects.filter(id_in=[1, 3, 4])

(
id), 1, 3 4.

startswith
:
>>> Entry.objects.filter(headline_startswith='Will')

Will he run? W illbur named


judge, Who is Will will found in
crypt.

istartswith
:
> Entry.objects.f i1te (head line_istartswith^'will)

Will he run?, W illbur named


judge will found in crypt, Who is Will.

endswith iendswith

. startswith istartswith:
>>> Entry.objects.filter(headline_endswith=cats)
> Entry.objects.filter(headline_iendswith=cats)

range
, :
> start_date = datetime.date(2005, 1, 1)
> end_date = datetime.date(2005, 3, 31 )
> Entry.objects.filter(pub_date__range=(start_date, end_date))

range , SQL
BETWEEN - , .

year, month, day


date datetime ,
:
tt , 2005
>>>Entry.objects.filter(pub_date_yea =2005)

. API

440

tt ,
>>> Entry.objects.filter(pub_date__month=12)
tt ,

>>> Entry.objects.filter(pub_date_day=3)
tt : ,
tt

>>> Entry.objects.filter(pub_date_month=12, pub_date_day=25)

isnull

NULL SQL.

True

False,

IS NULL

IS NOT

>>> Entry.objects.filter(pub_date_isnull^True)

search
,
. contains,
.
MySQL
.


Django - primary,
key. Blog id,
:
>>> Blog.objects.get(id_exact=14) tt
>>> Blog.objects.get(id=14)
tt _exact
>>> Blog.objects.get(pk=14)
tt pk id__exact

pk _exact;

:
tt 1, 4 7

> Blog, objects, fiIter(pk_in=[ 1, 4,7])


tt , id > 14
>>> Blog.objects.filter(pk_gt=14)

pk
. , :
>>> Entry, objects, fi Iter (blog_id__exact=3) tt
>>> Entry.objects. filter(blog__id=3) tt _exact
>>> Entry.objects.filter(blog__pk=3) tt __pk __id__exact

441

Q-

,
, ,
id.

Q-
( filterQ )
AND.
(, OR)
Q-.
Q- (django.db.models.Q) ,
, ,
.
, Q-
LIKE:
Q(question__startswith=What)

Q- & |. ,
Q-, Q-.
, Q-,
(OR) question__startswith:
Q(question__startswith=Who) | Q(question__startswith=*What')

WHERE

SQL:

WHERE question LIKE Who% OR question LIKE What%

Q- & |,
.
.
, (
, filterQ, exclude(), getQ),
Q- .
Q-,
AND, :
Poll.objects.get(
Q(question_startswith=Who),
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))

)
SQL-:
SELECT * from polls WHERE question LIKE Who%
AND (pub_date = 2005-05-02 OR pub_date = 2005-05-06')

Q-
. ( )

442

. API

WHERE,
AND. Q-
. , :
Poll.objects.get(
Q(pub_date=date(2005, 5, 2)) I Q(pub_date=date(2005, 5, 6)),
question_startswith=Who)

. - :
tt

Poll.objects.get(
question_startswith^'Who',
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)))

http://www.djangoproject.com/documentation/models/or_lookups/.


( Foreign Key,
OneToOneField ManyToManyField),
API .
, Entry
Blog, e.blog.
, Django
- ,
. , b Blog
Entry entry_set: b.entry_set.all().

.

Blog, Author

En

try,


Django
.
SQL- JOIN. ,
,
. ,
Entry, name
Blog Beatles Blog:
>>> Entry.objects.filter(blog__name__exact=Beatles Blog)

.
.
(. ),
.

443

Blog,
Entry, headline
Lennon:
> Blog.objects.fiIter(entry_headline__contains^Lennon)


Foreign Key,
()
:
= Entry.objects.get(id=2)
e.blog
tt Blog.

,
. ,
, save():
= Entry.objects.get(id=2)
e.blog = some_blog
e.save()

ForeignKey null=True (
NULL), NULL,
None :
= Entry.objects.get(id=2)
e.blog = None
e.save() tt "UPDATE blog_entry SET blog_id = NULL

- .

, :
= Entry.objects.get(id=2)
print e.blog tt Blog,
print e.blog tt ;

, select_related() QuerySet
--:
= Entry.objects.select_related().get(id=2)
print e.blog tt ; ,
print e.blog tt ; .

select_related()



- For
eignKey, .

444

. API

ForeignKey, ,
, ,
, .
F00_set, F00 - , .
Query Set, ( ,
), .
:
b = Blog.objects.get(id=1)
b.entry_set.all() tt Entry, Blog.
tt b.entry_set Manager, QuerySet.

b.entry_set.filter(headline_contains^Lennon)
b.entry_set.count()

F00_set related_name
ForeignKey. ,
Entry blog = ForeignKey(Blog, related_name=entries),
:
b = Blog.objects.get(id=1)
b.entries.a 11 () tt Entry, Blog.
tt b.entries Manager, QuerySet.

b.entries.filter(headline__contains=Lennon)
b.entries.count()

related_name ,
, .

, :
Blog.entry_set tt
tt AttributeError: "Manager must be accessed via instance.

QuerySet,
,
:

add (obj 1, obj 2, ...):


, :
b = Blog.objects.get(id=1)
e = Entry.objects.get(id=234)
b.entry_set.add(e) tt Entry e Blog b.

create(**kwargs): ,
. :
b = Blog.objects.get(id=1)
e = b.entry_set.create(headline=Hello, body_text='Hi',
pub_date=datetime.date(2005, 1, 1))
tt e.save() - .

445

( ) :
b = Blog, objects. get(icM)
e = Entry(blog=b, headline^Hello, body_text=Hi,
pub_date=datetime.date(2005, 1, 1))
e.save()

,
, .
createO blog. Django ,
blog Entry .

remove(obj1, obj2, ...):


:
b = Blog.objects.get(id=1)
e = Entry.objects.get(id=234)
b.entry_set. remove(e) tt Entry e Blog b.


ForeignKey null=True.
None (NULL),
.
b.entry_set() e.blog = None,
blog null=True, .

clear():

b = Blog.objects.get(id=1)
b.entry_set.clear()

, ,
.
removeO, clear() For
eignKey null=True.
,

, :
b = Blog.objects.get(id=1)
b.entry_set = [el, e2]

clear() ,
entry_set
, ( ).
clear() , ,
,
.

. ,
.

446

. API

--
--
. API
, -- (. ).
: ,
ManyToManyField,
,
,
_set * ( --).
:
= Entry.objects.get(id=3)
. authors, al 1 () tt Author Entry
.authors.count()
.authors.filter(name__contains=John)
a = Author.objects.get(id=5)
a. entry_set.all() tt Entry Author

ForeignKey, ManyToManyField
related_name. Ma
nyToManyField Entry related_name=entries,
Author entries_set, ent ry_set.

?
-
. Django
DRY ( ),
Django .
?
, ,
.
INSTALLED_APPS.
Django ,
, INSTALLED_APPS,
. ,
INSTALLED_APPS - Django
.



, .

447

,
.
, b Blog
:

id=5,

Entry.objects. filter(blog=b)
tt
Entry.objects, filter(blog=b.id) tt id
Entry, objects. filter(blog=5)
tt id


deleteO.
:
.delete()

. QuerySet
deleteO, .
, Entry,
pub_date 2005:
Entry.objects.fi1te (pub_date_yea r=2005).delete()

Django ON DE
LETE CASCADE SQL. ,
,
. :
b = Blog.objects.get(pk=1)
tt Blog Entry,

b. deleteO

, deleteO - QuerySet,
.
, Entry.objects.deleteO,
.
,
:
Entry.objects.11()delete()



API
. Django
, .
django.shortcuts.

448

. API

get_object_or_404()
- get()
Http404, .
get_object_or_404(),
Django,
, get() ,
. ,
Http404. :
tt

Entry 3
= get_object_or_404(Entry, pk=3)

, get()
, .

, get_object_or_404()
Manager:
tt

Fred
= get_object_or_404(e.authors, name=Fred)

tt
tt

'recent_entries
3
= get_object_or_404(Entry.recent_entries, pk=3)

get_list_or_404()
, get_object_or_404(), get()
filter(). ,
Http404.

SQL
SQL-,
- Django,
SQL.

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

11 ,
.

.
, 11. ,
Book, Publisher
Author, .

,
.
. . .1
;
, .
. ,

allow_empty

,
.
False ,
404.
True.

context_processors


( ),
.
. 9.

450

.1. ()

extra_context

, .
. -
,
,
.

minetype

M I M E .
DEFAULT_MIME_TYPE,
text/html (

).
queryset

QuerySet (
Author, objects, all( )),
. QuerySet .
.
.

template_loader

. django. template,
loader. . 9.

template_name

,
. ,
QuerySet.

template_object_name ,
. 'object.

(
object_list ,

),
_1 ist.


django.views.generic.simple
:
.


: django.views.generic.simple.direct_to_template.
,
{{ params }} , URL.

URL , ,
URL /foo/ foo_index.html,

451

URL /f/15/ -
{{ params.id }}, 15:
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
urlpatterns = patternsC',
(r'foo/$', direct_to_template, {'template': 'foo_index.html'}),
(r~foo/(?P<id>\d+)/$, direct_to_template,
{'template': foo_detail.html'}),

template: .

URL
: django.views.generic.simple. redirect_to.
URL. URL
,
URL.
URL None, Django 410 (
).

URL
/foo/<id>/ /bar/<id>/:
from django.conf.urls.defaults import *
from django.views.generic.simple import redirect_to
urlpatterns = patterns('django.views.generic.simple,
(~foo/(?p<id>\d+)/$, redirect_to, {'url': /bar/%(id)s/'}).

)
// 410:
from django.views.generic.simple import redirect_to
urlpatterns = patterns('django.views.generic.simple',
(~bar/$', redirect_to, {'url': None}),

url: URL, , .
None, - 410 (
).

452


/
/ ( django.
views.generic.list_detail) ,
,
- .


django.views.generic.list_detail.object_list.
.

object_list
( Author, 5),
URL :
from mysite.books.models import Author
from django.conf.urls.defaults import *
from django.views.generic import list_detail
author_list_info = {
queryset: Author.objects.all(),

}
urlpatterns = patternsC,

(rauthors/T , list_detail.object_list, author_list_info)

queryset: QuerySet,
(. . .1).

paginate_by: ,
. ,
paginate_by . ,
GET- ,
( ),
URL . (.
).

(
. .1).

allow_empty

context_processors

extra_context

mimetype

template_loader

template_name

template_object_name

453


template_name
<app_label>/<model_name>_list.html.
(app_label) (model_name)
queryset. - ,
, ,
.
, queryset
Author.objects.all(), books,
- author. ,
books/author_list.html.


extra_context,
:

object_list: .
template_object_name,
object. foo,
foo_list.

is_paginated: , ,

.
paginate_by, False.
,
:

results_per_page: (
paginate_by).

has_next: , ,
.

has_previous: , ,
.

: , .
1.

next: , .
,
. 1.

previous: , .
1.

454

pages: , .

hits: ,
.


paginate_by, Django
. URL :

URL, , :

(''objects/page(?P<page>[0-9]+)/$, object_list,
diet(in fo_dict))

,
, URL :
/obj ects/? page=3

1, ,
1.


. django.views.generic.list_detail.object_detail.

.

object_list,
,
URL :
from mysite.books.models import Author
from django.conf.urls.defaults import *
from django.views.generic import list_detail
author_list_info = {
queryset : Author.objects.al1(),

}
author_detail_info = {
"queryset" : Author.objects.al1(),
template_object_name" : "author",

}
urlpatterns = patternsC,
(rauthors/$, list_detail.object_list, author_list_info),
(r~authors/(?P<object_id>d+)/$', list_detail.object_detail,
author_detail_info),

455

queryset: QuerySet,
(. . .1).

, :

object_id:

slug: . ,
slug_field (.
).

slug_f ield: , . ,
slug,
object_id.

template_name_f ield: ,
.
.
, the_template,
f.html, template_name_field the_
template,
' foo.html.
, template_name_field,
, ,
template_name. ,
, .


(. . .1):

context_processors

extra_context

mimetype

template_loader

template_name

template_object_name


template_name template_name_field
, <app_label>/<model_
name>_detail.html.

456


extra_context,
:

object: .
template_object_name, object.
foo,
foo.




.
(//) .

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

.
,
Django 404 ( ),
, , . ,
,
.
(, ).
allow_f uture True -
(
).


: django.views.generic.date_based.archive_index.
,
( ) ,
.

,
. ,
Book, publication_date,
archive_index:

from mysite.books.models import Book


from django.conf.urls.defaults import *
from django.views.generic import date_based
book_info = {
"queryset

: Book.objects.al1(),

457

date_field : ,,publication_date

}
urlpatterns = patternsC,
(r"books/$. date_based.archive_index, book_info),

date_field: DateField DateTimeField ,


QuerySet, ,
, .

queryset: QuerySet, .

allow_future: , ,
(. ).

num_latest: ,
. 15.


(. . .1):

allow_empty

context_processors

extra_context

mimetype

template_loader

template_name


template_name
<app_label>/<model_name>_archive.html.


extra_context,
:

date_list: datetime.date, ,
queryset .
.
, 2003 2006 ,
datetime.date,
.

latest: num_latest ,
date_field. , num_latest -

458

10, latest 10 queryset


.


: django.views.generic.date_based.archive_year.
.
,
, ,
.

,
:
from mysite.books.models import Book
from django.conf.urls.defaults import *
from django.views.generic import date_based
book_info = {
"queryset"
: Book.objects.al1(),
date_fieldM : publication_date

}
urlpatterns = patternsC',
(r"books/S1, date_based.archive_index, book_info),
(r*~books/(?P<year>d{4})/?$, date_based.archive_year, book_info),

date_field: , archive_index (.
).

queryset: QuerySet, .

year: ,

( URL, ).

make_object_list: , ,

. True,
object_list ( object_
list ; .
). False.

allow_future: , ,
(. ).


(. . .1):

allow_empty

context_processors

extra_context

mimetype

template_loader

template_name

template_object_name

459


template_name
<app_label>/<model_name>_archive_year.html.


extra_context,
:

date_list: datetime, date, ,


queryset .
.

year: .

object_list: make_object_list True,



, .
template_object_name, object.
template_object_name f,
foo_list. make_object_list
False, object_list
.


: django.views.generic.date_based.archive_month.
.

,
:
urlpatterns = patternsC',
(~books/$, date_based.archive_index, book_info),
(r~books/(?P<year>d{4})/?$', date_based.archive_year, book_info),

(
r'~(?P<year>d{4})/(?P<month>[a-z]{3})/$',
date_based.archivejnonth,
book_info

460

),
)

year: ,
().

month: , , ,
month_format.

queryset: QuerySet, .

date_field: DateField DateTimeField ,


QuerySet, ,
, .

month_format: ,
month. , Python
time.strftime. ( http://

docs.python.org/library/tim e.htm ltttim e.strf time.)


% - (,
, . .). ,
%.

allow_future: , ,
(. ).


(. . .1):

allow_empty

context_processors

extra_context

mimetype

template_loader

template_name

template_object_name


template_name
<app_label>/<model_name>_archive_month.html.


extra_context,
:

month: datetime.date, .

461

next_month: datetime.date,
. ,
None.

previous_month: datetime.date,
. next_month,
None.

object_list: .
template_object_name,
object. template_object_name
foo, foo_list.


: django.views.generic.date_based.archive_week.
.
---------------------------------------------------------------------------------------------------- ,
Python, Django , .

urlpatterns = patternsC',

tt ...
(
' ~(?P<year>d{4})/(?P<week>d{2})/$',
date_based.archive_week,
book_info

),
)

year: ,

().

week: , ().

queryset: QuerySet, .

date_field: DateField DateTimeField ,


QuerySet, ,
, .

allow_future: , ,
(. ).


(. . .1):

462

allow_empty

context_processors

extra_context

mimetype

tenplate_loader

template_narne

ternplate_object_narne


ternplate_name
< a p p_label>/<model_name>_archive_week.html.


e x t r a_context,
:

week:

datetime.date,

obje c t _ l i s t : .
t e mplate_ob ject_name,
o b j e c t . t e n p l a t e _ o b j e c t _ n a m e
f o o , foo_list.


: django.views.generic.date_based.archive_day.
.

urlpatterns = p a t t e r n s C ,

#
(

. ..

~(?P<year>d{4})/(? P<month>[a-z]{3 >)/(?P<day>d{2 >)/$,


date_based.archive_day,
book_info

),
)


,
().

year:

month: , , ,
month_format.

463

day: , , ,
day_format.

queryset: QuerySet, .

date_field: DateField DateTimeField ,


QuerySet, ,
, .

month_format: ,
month. . .

day_format: month_format, .
%d" (
01 31).

allow_future: , ,
(. ).


(. . .1):

allow_empty

context_processors

extra_context

mimetype

template_loader

template_name

template_object_name


template_name
<app_label>/<model_name>_archive_day.html.


extra_context,
:

day: datetime, date, .

next_day: datetime.date, .
,
None.

previous_day: datetime.date, .
next_day,
None.

464

object_list: .
tenplate_object_name,
object. template_object_name
foo, foo_list.


django.views.generic.date_based.archive_today
. archive_day
, year/month/day ,
.

urlpatterns = patternsC,
tt . . .

(~books/today/$, date_based. archive_today, book_info),


: django.views.generic.date_based.object_detail.
.
URL object_detail.
object_detail URL /entries/<slug>/,
- URL /entries/2006/aug/27/<slug>/.
----------------------------------------------------------------------------------------------------
URL, , , unique_for_date
, .
unique_for_date . .


,
, , Django .
, , ,
URL .
,
.
urlpatterns = patternsC ',
...

(
~(?P<year>d{4})/(?P<month>[a-z]{3})/(?P<day>d{2 >)/(?P<object_
id>[w-]+)/$,

date_based.object_detail,

465

book_info

).
)

year: ().

month: , month_format.

day: , day_f ormat.

queryset: QuerySet, .

date_field: DateField DateTimeField ,


QuerySet,
, year, month day.

, :

object_id:

slug: . ,
slug_f ield (. ).

allow_future: , ,
(. ).

month_format: ,
month. . .

day_format: month_format, .
%d (
01 31).

slug_f ield: , .
, slug,
object_id.

template_name_f ield: ,
.
. , thejtemplate,
foo.html, template_name_field
the_template,
foo. html.


(. . .1):

context_processors

extra_context

mimetype

template_loader

466

template_name

template_object_name


template_narne
<app_label>/<model_name>_detail.html.


extra_context,
:

object: .
template_object_narne, object.
foo,
foo.

D


Django. ,
.


- Python
. :
DEBUG - False
DEFAULT_FROM_EMAIL = webmaster@example.com
TEMPLATE_DIRS = ('/home/templates/mike, /home/templates/john)

- , :

Python,
.

, :
MY_SETTING = [str(i) for i in ()]


,
. .
django/conf/global_settings.py.
Django :
1. global_settings.py.
2. ,
.

D.

468

, global_
settings, ; .

,
,
. manage, diffsettings
, Django .
manage, F.

Python-
Django ,
django.conf.settings:
from django.conf import settings
if settings.DEBUG:
tt

, django.conf.settings - , .
:
from django. conf.settings import DEBUG tt He .

, ,
: global_settings
, django.conf.settings
, .
, ,
, ,
.



. , :
from django.conf import settings
settings. DEBUG = True tt He !

,
, ,
. , -.
.

: DJANGO_SETTINGS_MODULE

469



Django. :

, ,
.
.

,
.

:
DJANGO_SETTINGS_MODULE
Django ,
. DJANG0_
SETTINGS_MODULE.

Python (, mysite.
settings). ,
( PYTHONPATH).
0

------------------------------------------------------ PYTHONPATH http://


diveintopython.org/getting_to_know_python/everything_is_an_objecthtmi.

django-admin.py
django-admin.py (. F)
,
.
UNIX Bash :
export DJANGO_SETTINGS_MODULE=mysite.settings
django-admin.py runserver

Windows :
set DJANGO_SETTINGS_MODULE=mysite.settings
django-admin.py runserver


--settings:
django-admin.py runserver --settings=mysite.settings

D.

470

manage, , start project


,
DJANGO_SETTINGS_MODULE; manage, . F.

(mod_python)
Apache + m od_python ,
. SetEnv:
<Location /mysite/>
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
</Location>

. mod_python
http://docs.djangoproject.com/en/dev/howto/deployment/modpython/.


DJANGO_SETTINGS_MODULE
DJANG0_
SETTINGS_MODULE. ,
, -
, .
Django
. django.conf.settings.
configure(), :
from django.conf import settings
settings.configure(
DEBUG = True,
TEMPLATE_DEBUG = True,
TEMPLATE_DIRS = [
'/home/web-apps/myapp,
/home/web-apps/base,

]
)
configureQ ,
.

, . -
configureQ, Django
.

DJANGO_SETTINGS_MODULE

471

Django -
, -
,
settings.conf igureQ Django
. (. TIME_Z0NE, ,
.) ,
.


,
django.conf.global_settings, - ,
default_settings (
) configureQ.
_
defaults, DEBUG True
, myapp_defaults:
from django.conf import settings
from myapp import myapp_defaults
settings.configure(default_settings=myapp_defauIts, DEBUG=True)

, myapp_def aults
:
settings.configure(myapp_defau1ts, DEBUG = True)


. Django ,
. ,
Django,
,
.
django.conf.settings.global_settings.

configure()
DJANGO_SETTINGS_MODULE
DJANGO_SETTINGS_MODULE,
configureQ, ,
.
, , Django
EnvironmentError .
DJANGO_SETTINGS_MODULE
- ,
configureQ, Django EnvironmentError,
, .

D.

472

, conf igure( )
.
, - :
DJANGO_SETTINGS_MODULE, .

configureQ

ABSOLUTE_URL_OVERRIDES
: {} ( )
, app_label.model_name
, URL.
get_absolute_url()
. :
ABSOLUTE JJRLJ)VERRIDES - {
'blogs.weblog: lambda : /blogs/%s/ % .slug,
news.story: lambda o: /stories/%s/%s/ % (o.pub_year, o.slug),

}
,
,
.

ADMIN_MEDIA_PREFIX
:

/media/

URL ,
: CSS, JavaS cript .
.

ADMINS
: () ( )
,
. DEBUG=False
, Django
.
( ,
), :
((John, john@example.com), (, mary@example.com))

, Django
.

473

ALLOWED_INCLUDE_ROOTS
: () ( )
, ,
{% ssi %}. ,
,
.
, , ALLOWED_INCLUDE_ROOTS
(/home/html, /var/www), {%ssi /home/html/foo.txt %}
, {%ssi /etc/passwd %} .

APPEND_SLASH
: True
, URL- .
,
CommonMiddleware (. 17). . PREPEND_
WWW.

CACHE_BACKEND
: locmem://
(. 15).

CACHE_MIDDLEWARE_KEY_PREFIX
: ( )
,
(. 15).

DATABASE_ENGINE
: ( )
(,
postgresql_psycopg2 mysql).

DATABASE_HOST
: ( )
. localhost.
SQLite .
MySQL
(/), MySQL
UNIX-:
DATABASE_HOST = /var/run/mysql'

474

D.

MySQL
, , 1-
.

DATABASEJSIAME
: ( )
. SQLite .

DATABASE_OPTIONS
: {} ( )
,
.
.

DATABASE_PASSWORD
: ( )
. SQLite .

DATABASE_PORT
: ' ( )
.
, . SQLite
.

DATABASEJJSER
: ( )
. SQLite
.

DATE_FORMAT
: Nj , (, Feb. 4, 2003)
,
, Django, ,
, .
, now (. , . .2).
. DATETIME_FORMAT, TIME_F0RMAT, YEAR_M0NTH_
FORMAT M0NTH_DAY_F0RMAT.

DATETIME_FORMAT
no : N j, Y, P' (, Feb. 4, 2003, 4 p.m.)

475

/ ,
, Django,
, , .
, now (. , . .2).
. DATE_FORMAT, TIME_FORMAT, YEAR_MONTH_FORMAT
MONTH_DAY_FORMAT.

DEBUG
no : False
.
, ,
django/views/debug.py HIDDEN_
SETTINGS, ,
SECRET, PASSWORD PROFANITIES.
,
( ) .
, ,
, . ,
. .
.
DEBUG.

DEFAULT_CHARSET
: utf-8
HttpResponse,
MIME. DEFAULT_
CONTENTJYPE Content-Type.
HttpResponse . G.

DEFAULT_CONTENT_TYPE
: text/html
HttpResponse,
MIME.
DEFAULT_CHARSET Content-Type.
HttpResponse . G.

DEFAULT_FROM_EMAIL
: webmaster@localhost
,

.

476

D.

DISALLOWED_USER_AGENTS
: () ( )
,
,
.
. ,
CommonMiddleware (. 17).

EMAIL_HOST
: localhost
, . .
EMAIL_PORT.

EMAIL_HOST_PASSWORD
: ( )
SMTP-, EMAIL_
HOST. EMAIL_HOST_USER
.
, Django .
. EMAIL_HOST_USER.

EMAIL_HOST_USER
: ( )
SMTP-,
EMAIL_HOST. , Django
. . EMAIL_HOST_PASSWORD.

EMAIL_PORT
: 25
SMTP-, EMAIL_
HOST.

EMAIL_SUBJECT_PREFIX
: [Django]
Subject ,
django.core.mail.mail_admins django.core.mail.mail_
managers. .

FIXTURE_DIRS
: () ( )

477


. ,
, Windows.
Django,
http://docs.djangoproject.com/en/dev/topics/testing/.

IGNORABLE_404_ENDS
: (mail.pl, mailform.pl, mail.cgi, mailform.cgi,
favicon.ico, .php)

, URL,
404 (
. 12).
404, URL,
, .
. IGN0RABLE_404_STARTS SEND_BROKEN_LINK_
EMAILS.

IGNORABLE_404_STARTS
: {{/ cgi-bin/, /_vti_bin\ /_vti_inf )
To , IGN0RABLE_404_ENDS,
URL.
. IGN0RABLE_404_ENDS SEND_BROKEN_LINK_
EMAILS.

INSTALLED_APPS
: () ( )
,
Django.
Python Django.
. 5.

LANGUAGE_CODE
: en-us
.
; ,
en-us.. 19.

LANGUAGES
: ,
. ,
, .

D.

478

, Django, django/
conf/global_settings.py.

,
( , ), , (ja\
Japanese). .
. 19.
.
,
.
LANGUAGES,
,
django.utils.translation ,
,
.

gettext(). :
gettext = lambda s: s
LANGUAGES = (
(de, gettext('German)),
(en, gettext('English)),

)
make-messages.py
,
;
gettext() ,
LANGUAGES.

MANAGERS
: () ( )
, ADMINS; ,
, SEND_BROKEN_LINK_
EMAILS=True.

MEDIA_ROOT
: ( )
,
(, /home/media/media.lawrence.com/).
. MEDIA_URL.

MEDIA URL
: ( )

479

URL MEDIA_R00T (, " h ttp ://


media.lawrence.). URL , .

: http://www.example.com/static/

: http://www.example.com/static


. 12.

MIDDLEWARE_CLASSES
:
(django. contrib. sessions, middleware. SessionMiddleware,
django. contrib. auth. middleware. AuthenticationMiddleware,
django. middleware, common. CommonMiddlewa re,
dj ango. middleware, doc. XViewMiddleware)

.
. 17.

MONTH_DAY_FORMAT
: F j
,
Django, , ,
, , .
, now (.
, . .2).
,
Django ,
.
. , January 1,
- 1 .
. DATE_FORMAT, DATETIME_F0RMAT, TIME_F0RMAT
YEAR_MONTH_FORMAT.

PREPEN D W WW
no : False
www. URL,
. ,
CommonMiddleware (. 17). .
APPEND_SLASH.

D.

480

ROOTJJRLCONF
:
, Python
URL (, mydjangoapps.urls). . 3.

SECRET_KEY
:
.
Django.
.
- , . django-admin.py
start project ,
.

SEND_BROKEN_LINK_EMAILS
: False
,
MANAGERS, , -
Django- ( 404)
Referer (
). ,
CommonMiddleware (. 17). .
IGN0RABLE_404_STARTS IGN0RABLE_404_ENDS.

SERIALIZATIONMODULES
:
.
. http://docs.djangoproject.com/en/dev/
topics/serialization/.

SERVER_EMAIL
: root@localhost
,
, , ,
ADMINS MANAGERS.

SESSION_COOKIE_AGE
: 1209600 ( , )
cookie. . 14.

481

SESSION_COOKIE_DOMAIN
: None
cookie. cookie
.lawrence.com, ,
, None. . 14.

SESSION_COOKIE_NAME
: sessionid
cookie, . . 14.

SESSION_COOKIE_SECURE
: False
, cookie .
True, cookie secure,

HTTPS-. . 14.

SESSION_EXPIRE_AT_BROWSER_CLOSE
: False

. . 14.

SESSION_SAVE_EVERY_REQUEST
: False

. . 14.

SITEJD
:
,
django_site. ,
. .
16.

TEMPLATE_CONTEXT_PROCESSORS
:
(dj ango. core. context_processors. auth,
django. core. context_processors. debug,
django.core.context_processors.i18n,
django.core.context_processors.media)

482

D.

, ,
, RequestContext.

, . . 9.

TEMPLATE_DEBUG
: False
.
True,
, TemplateSyntaxError.
, ,
, .
, , DEBUG
True. , ,
DEBUG.
. DEBUG.

TEMPLATE_DIRS
: () ( )

. ,
Windows. .
4 9.

TEMPLATE_LOADERS
:
(django. template, loaders. filesystem.load_template_sou rce\
django.template. loaders. app_di rectories. load_template_source)

, ( ),
, . . 9.

TEMPLATE_STRING_IF_INVALID
: ( )
,
, (, - ).
. 9.

TEST_DATABASE_NAME
: None
, .
None, test_ + settings.

483

DATABASE_NAME. Django .
http://docs.djangoproject.com/en/dev/topics/testing/.

TEST_RUNNER
: django.test, simple. run_tests
.
Django, http://docs.
djangoproject.com/en/dev/topics/testing/'.

TIME_FORMAT
no : P (, 4 p.m.)
,
Django, , ,
. ,
now (. , . .2).
. DATE_FORMAT, DATETIME_FORMAT, YEAR_MONTH_
FORMAT MONTH_DAY_FORMAT.

TIME_ZONE
no : America/Chicago
, .
http://
www.postgresql.org/docs/8.1 /static/datetim e-key w ords.htm l#D ATE TIM ETlM EZONE-SET-TABLE.
, , Django
/. ,
Django-,
.
, TIME_Z0NE, Django
os.environ[TZ].
.
(.
DJANGO_
SETTINGS_MODULE), Django
TZ, ,
.
---------------------------------------------------------------------------------------------------- Windows Django
. Windows
.

484

D.

URL_VALI DAT R_US R_AG ENT


no : Django/<version> (http://www.djangoproject.com/ )
, User-Agent
URL (. verify_exists
URLField ).

USE_ETAGS
: False
ETag.
, . ,
CommonMiddleware (.
17).

USEJ18N
: True

Django (. 19).
.
False, Django ,
, .

YEAR_MONTH_FORMAT
: F Y
,
Django, , ,
, , .
, now (.
, . .2).
,
Django ,
.
. , January
2006, - - 2006/January.
. DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT
MONTH DAY FORMAT.



4
. Django
. .


autoescape
.
on of f
.
, HTML-

( ).
escape
.
,
- , ,
safe escape.

block
, .
. 4.

comment
{%comment %} {%endcomment %}.

486

cycle

.
:
{% for in some_list %}
< t class= {% cycle row1 row2 %}>
</tr>
{% endfor %}

. ,
, rowvaluel rowvalue2,
:
{% for in some_list %}
<t class= {% cycle rowvaluel rowvalue2 %} >
</tr>
{% endfor %}


:
{% for in some_list %}
<tr class= {% cycle row1 rowvalue2 row3 % } >
</tr>
{% endfor %}


. {% cycle %} :
{% cycle row1 row2 as rowcolors %}


:
<tr class= {% cycle rowcolors %}">...</tr>
<tr class= {% cycle rowcolors %}">...</tr>

{%cycle %}
, . ,
, ,
- .
{%cycle %}
, Django.
,
, :
{% cycle rowl,row2,row3 %}

487

,
.
. ,
.

debug
,
.

extends
, .
:

{% extends base.html %} ( ) -
base.html.

{% extends variable %} - variable.

, Django
.
, .
. 4.

filter
.
;
. :
{% filter force_escape|lower %}
HTML-
.
{% endfilter %}

firstof
,
False.
False, . :
{% firstof varl var2 var3 %}

:
{% if varl %}
{{ varl }}
{% else %}{% if var2 %}
{{ var2 }}
{% else %}{% if var3 %}

488

.
{{ var3 }}
{% endif %}{% endif %}{% endif %}

,
,
False:
{% firstof varl var2 var3 "fallback value %}

for
. ,
a th lete_ list:
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>

Ter {%for obj in l i s t reversed %}


.
,
. ,
points (.),
:
{% for , in points %}
{{ }},{{ }}
{% endfor %}

,
. , ,
data, ,
:
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}

for ,
. .1.
. , {% for %}

forloop.counter


( 1)

forloop.counterO


( 0)

489

forloop.revcounter

,
( 1)

forloop.revcounterO

,
( 0)

forloop.first

rue,

forloop.last

rue,

forloop.parentloop

for {%empty %},


,
:
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% empty %}
<li>B !</li>
{% endfor %}
</ul>

, ,
, , :
<ul>
{% if athlete_list %}
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
{% else %}
<li>B !</li>
{% endif %}
</ul>

Ter {% if %} ,
true ( ,
False), :
{% if athlete_list %}
: {{ athlete_list|length }}
{% else %}
.
{% endif %}

, a th le te _ list ,
( {{ athlete_list(length }}).

490

, if {%
else %}, , .
if and
, 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 %}

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


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


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

ifchanged
,
.

491

ifchanged ;
:

, , ,
, ,
. , ,
,
:
<11 {{ year }}</h1>
{% for date in days %}
{% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
<a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j }}</a>
{% endfor %}

, , .
,
, , ,
:
{% for date in days %}
{% ifchanged date.date %} {{ date.date }} {% endifchanged %}
{% ifchanged date.hour date.date %}
{{ date.hour }}
{% endifchanged %}
{% endfor %}

ifchanged {% else %},


, :
{% for match in matches %}
<div style="background-color:
{% ifchanged match.ballot_id %}
{% cycle red,blue %}
{% else %}
grey
{% endifchanged %}
">{{ match }}</div>
{% endfor %}

ifequal
, . :
{% ifequal user.id comment.user_id %}
{% endifequal %}

{%if %}, {%else %}.


,
:

492

.
{% ifequal user.username adrian" %}
{% endifequal %}


. Python, ,
True False. if.

ifnotequal
ifequal, .

include
.
.
,
.
foo/bar.html:
{% include "foo/bar.html %}

,
template_name:
{% include template_name %}


. , ":

: person ".

:
{% include name_snippet.html %}

name_snippet. html:
, {{ person }}

. : {%ssi %}.

load
.
. 9.

now
.
, - date()
(http://php.net/date) .
. .2 .

493

.2.

a.m.' p. m. ' ( a.m.


,

)

AM' '

AM

j an

' 01 31'

Fri

12- 1 , 4 : 3 0
.
, .
Django.

January

12-

1 12

24-

0 23

12-

01 12

24-

00 23

00 59

' 1 31

Friday

True False

01 ' 12

Jan

1 12



. Django

' Jan., Feb. ,


' March, May

494

.2. ()

+0200'

12-
,
a .m .7*-1.\
, .

'midnight'
noon .
Django

'1 a.m. , 1:30 p.m. ,

RFC 2822

Thu, 21 Dec 2000


16:01:07 +0200

00 59

st , nd , rd, th

28 31

0 ()
6 ()


ISO-86OI,

1 53

99

1999

0 365

. -43200 43200

UTC ,

midnight, noon,
12:30 p.m.

EST , ' MDT

:
{% now jS F Y H:i %}

,
, .
f

495

.
V ,
:
It is the

{% now MjS o\f F %}

It is the 4th of September.

regroup
.
.
, people - ,
first_name (), last_name (
) gender ():

- [
first_name
fi rst_name
first_name
first_name'
first name

, last_name: , gender: },
, 'last_name: , gender: },
, last_name: , gender: },
, last_name: , gender: },
, last_name: , gender: },

]
, ,
:

{% regroup %},
:
{% regroup people by gender as gender_list %}
<ul>
{% for gender in gender_list %}
<1i>{{ gender.grouper }}
<ul>
{% for item in gender.list %}
<li>{{ item.first_name }} {{ item.last_name }}</li>
{% endfor %}
</ul>
</li>

496
{% endfor %}
</ul>

, . {% regroup %}
: , ; ,
, .
people gender
gender_list.
{% regroup %} ( gender_list)
. :

grouper:

, (,
).

"

list: (, ,
g e n d e r = My>KCK0^).

, {% regroup %} !
, people
gender. ,

. , people (
, ):
people = [
{first_name : , last_name: , gender: },
{fi rst_name: , last_name: , gender: },

{1first_name: , last_name: *, gender: },


{first_name: , last_name: , gender: },
{first_name: , last_name: , gender: },

]
people {%
regroup %}, :

,
.

497

-
dictsort. ,
:
{% regroup people|dictsort:"gender" by gender as gender_list %}

spaceless
HTML- (,
). :
{% spaceless %}
<>
< href="foo/">Foo</a>
</>
{% endspaceless %}

HTML-:
<>< href="foo/">Foo</a></p>

,
. ,
, :
{% spaceless %}
<strong>

</strong>
{% endspaceless %}

ssi
.
include, {%ssi %} ,
:
{% ssi /home/html/ljworld.com/includes/right_generic.html %}

parsed",

:
{% ssi /home/html/ljworld.com/includes/right_geneic.html parsed %}

, {%ssi %}
Django ALLOWED_INCLUDE_ROOTS
.
. {%include %}.

templatetag
.

498

,

{%t e mplatetag %}.
. ..
. . templatetag

openblock

{%

closeblock

%}

openvariable

{{

closevariable

}}

openbrace

closebrace

opencomment

(tt

closecomment

tt}

URL ( URL ),
,
. ,
URL- , ,
DRY:
{% url path.to.some_view arg1,arg2,name1=value1 %}

- package,
package.module.function. .
,
.
, URL,
.
, , app_views. client,
URL ( clie n t ( ) - ,
app_views. ).
:
(1~client/(\d+)/$, 'app_views.client)

URL
URL :
(''clients/' , include(project_name. app_name. urls))

499


:
{% url app_views.client client.id %}

/clients/client/123/.

widthratio

,
. :
<img src=ubar.gif" height=10 width={% widthratio this_value max_value 100

%} />
this_value 175, a max_value 200,
88 ( 175 / 200 = 0.875, 0.875
* 100 = 87.5, 88).

with
. ,
(,
). :
{% with business.employees.count as total %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}

(
{%with %} {%endwith %}.

total)


add
, :
{{ value|add:"2" }}

value

4,

6.

addslashes
. , ,
CSV.

capfirst
.

500

center
.

cut

arg

, :

{{ value|cut: }}

value

date
(
, {%now %}). :
{{ valuo|date:"D d " }}

value - datetime (, ,
datetime.datetime.now()), Wed 09
Jan 2008.

,
DATE_F0RMAT:
{{ value|date }}

default
False,
, . :
{{ val|default:"nothing }}

value

( ),

nothing.

default_if_none
( ) value None,
, - , .
,
, .
default. :
{{ val|default_if_none:"nothing" }}

value

None,

nothing.

dictsort

, :

501

{{ value|dictsort:name }}

value :
[
{name
{name
{'name

1zed
'amy

age 19},
age 2 2
joe age 31},

},

:
[
{ name
{name
{name'

},

1amy , age 2 2
joe, age 31},
zed, age 19},

dictsortreversed

.
, , .

divisibleby

True,

{{ value[divisibleby:3 }}

value

21,

True.

escape
HTML-. , :
<

&lt;

&gt;

>

' ( ) &#39;
( ) &quot;

& &;

,
, escape -
, .
, force_escape.
escape ,
,
.
.

502

,
force_escape.

escapejs
,
JavaS cript-.
HTML-,
JavaS cript- JSON- .

filesizeformat

. .). :

('13 ,

4.1 MB, '102 bytes

{{ value|filesizeformat }}

value

123456789,

117.7 MB.

first
, :
{{ value|first }}

value

[, ', ],

fix_ampersands

&;.

{{ value|fix_ampersands }}

value

& Jerry,

Tom &; Jerry.

floatformat

(
). . . .4.
.4. floatformat

34.23234

{{ value|floatformat }}

34.2

34.00000

{{ value|floatformat }}

34

34.26000

{{ value|floatformat }}

34.3

, floatformat ,
. . . .5.

503

.5. floatformat

34.23234

{{ value|floatformat:3 }}

34.232

34.00000

{{ value)floatformat:3 }}

34.000

34.26000

{{ value|floatformat:3 }}

34.260

floatformat ,
,
. . . .6.
.6. floatformat

34.23234

{{ value|floatformat:-3 }}

34.232

34.00000

{{ value|floatformat:-3 }}

34

34.26000

{{ value|floatformat:-3 }}

34.260

floatformat

-1.

force_escape
HTML- ( . escape).

. ,

. escape.

get_digit
, 1
, 2 - . .
(
1),
. .
:
{{ value|get_digit:2 }}

value

123456789,

8.

iriencode
(Inter
nationalized Resource Identifier - IRI) ,
URL. , URL ,

504

-ASCII .
, urlencode.

join
,
, Python s t r . j o i n ( l i s t ) . :
{{ value|join: // " }}

value [ , \ ],
// b // .

last
, :
{{ val|last }}

value [ , b\ ' , 'd ],


"d.

length
( ,
). :
{{ val|length }}

value [ , \ , d ],
4.

lengthjs
True, ,
Fa lse . :
{{ value|length_is:4 }}

value [ , \ , d ],
True.

linebreaks

HTML-; HTML (<br />), ,
, (</>). :
{{ val|linebreaks }}

value Jo e l\ n is a slug, <p>Joel<br / > is a slug</p>.

505

linebreaksbr
HTML < />.

linenumbers
.

Ijust
.
:

lower
, :
{{ value|lower }}

value S till MADAt Yoko, s t i l l mad at yoko.

makejist
, .
, - .
:
{{ value|make_list }}

value - "Joel, [uJ\ uo\ ue \ ].


value - 123, [1, 2, 3].

phone2numeric
(, )
. , 800-C0LLECT 800-2655328.
,
.

pluralize
, 1.
s . :
You have {{ numjnessages }} message{{ numjnessages|pluralize }}.

s ,
. :
You have {{ num_walruses }} walrus{{ num_walrus|pluralize:es" }}.

506


,
. :
You have {{ num_cherries }} cher{{ num_cherries|pluralize:",ies" }}.

pprint
pprint.pprint Py
thon. .

random
, :
{{ value|random }}

value [, \ , d],
.

removetags
[]-. :
{{ value|removetags:"b span |safe }}

value <b>Joel</b> <button>is</button> a <span>slug</span>, to


Joel <button>is</button> a slug.

rjust
.
:

safe
HTML-.
, .

safeseq
safe .
,
, :
{{ some_list|safeseq|join:, " }}

safe ,
,
.

507

slice
.
, Python
. . http://diveintopython.org/native_data_types/lists.
html#odbchelper.list.slice. :
{{ some_list|sltce:,,:2" }}

slugify
, ,
, ,
. , .
:
{{ value|slugify }}

value Joel is a slug, joel-is-a-slug.

stringformat

. ,
Python , %
. Python . http://docs.python.org/
library/stdtypes.html#string-formatting-operations. :
{{ value|stringformat:"s" }}

value Joel is a slug, Joel is a slug.

striptags
[]-. :
{{ value|striptags }}

value <b>Joel</b> <button>is</button> a <span>slug</span>, to


Joel is a slug.

time
(
, {%now %}). time
, , (
). date.
:
{{ value|time: :i" }}

508

value - datetime.datetime.now(),
01:23. ,
TIME_F0RMAT:
{{ value|time }}

timesince
( 4 days,
6 hours).
,
, (
). ,
blog_date - 1 2006 , comment_date - 08:00 1
2006 , {{ blog_date|timesince:comment_date }} 8 hours.
, ,
. - .

, 0 minutes.

timeuntil
timesince,
, date datetime. , 1 2006 , a conference_date - 29
2006 , {{ conference_date|timeuntil }} 4 weeks.
,
, (
).
, blog_date - 22 2006 , {{ conference_
date | timeuntil:f rom_date }} 1 week.
, ,
. -
.
, 0 minutes.

title
,
.

truncatewords
.
: .

509

:
{{ value|truncatewords:2 }}

value

"Joel is a slug,

Joel is ..

truncatewords_html
truncatewords, HTML-. ,
,
.
, truncatewords,
HTML-.

unorderedjist
HTML <ul>.
, . , var
[, [, [, ], ]], {{
var|unordered_list }} HTML-:
<>
<ul>
<
<ul>
<></>
<></>
</ul>
</li>
<></>
</ul>
</li>

upper
, :
{{ val| }}

value

Joel is a slug,

JOEL IS A SLUG.

urlencode
URL.

urlize
URL .

510

, urlize ,
HTML-, .
. :
{{ value|urlize }}

value

www.djangoproject.com,

< href=http://www.djangoproject.com> w w w .

djangoproject.com</a>.

urlizetrunc
URL , URL,
. urlize,
.
: URL .
:
{{ value|urlizetrunc:15 }}

value

www.djangoproject.com,

< href=http://www.djangoproject.com> w w w .

djangop...</a>,

wordcount
.

wordwrap
,
.
: .
:
{{ value|wordwrap:5 }}

value
Joel
is
slug

Joel is a slug,

yesno
,
True, False () None, ,
(. .7).

511

.7. yesno

True

yeah,no,maybe

yeah

False

yeah,no,maybe

no

None

yeah,no,maybe

maybe

None

yeah,no

"no ( None False,


None )


django-admin
django-admin.py
.
.
django-admin.py -
manage., Django.
django-admin.py,
:

DJANGO_SETTINGS_MODULE
settings, .

sys.path.

django-admin.py
, Django
setup.. ,
site-packages/django/bin,
Python.
- , ,
/usr/local/bin.

Windows ,
django-admin.py , ,
( - - ->
- > ), ,
.
Django
manage..
Django ,
django-admin.py, DJANGO_SETTINGS_
MODULE --settings .

513

dj ango-admin.
, manage. .

django-admin.py

django-admin.py <subcommand> [options]


manage. <subcommand> [options]

subcommand - ,
, a options -
.


,
django-admin.py help.
, django-admin.py help
<subcommand>.



. - ,
. , INSTALLED_APPS
mysite.blog, - blog.


Django,
django-admin.py --version. :
1. 1
1.0
0.96
0.97- re-SVN-6069


--verbosity
, .

cleanup
cron
, (
).

F. django-admin

514

compilemessages
-,
makemessages, mo-,
gettext. . 19.

locale
--locale, -1 .
, . :
django-admin.py compilemessages --locale=br_PT

createcachetable

, . .
15. :
django-admin.py createcachetable my_cache_table

createsuperuser
(
). ,
, -
syncdb,
.

.
,
, .

username
--email. createsuperuser
,
.
,
Django ( INSTALLED_APPS django.
contrib.auth). . 14.

dbshell
,
DATABASE_ENGINE ,
DATABASE_USER, DATABASE_PASSWORD .

PostgreSQL psql.

MySQL mysql.

SQLite

515
sqlite3.

,
, PATH,
(psql, mysql, sqlite3)
. .

diffsettings

Django . ,
, # # # . ,
R00T_URLC0NF, ,
diffsettings, # # # .
,
, , django/conf/
global_settings.py.

dumpdata
,
. ,
, .
dumpdata loaddata.
, dumpdata
.
,
, .
:
django-admin. dumpdata books

--exclude ,
. ,
auth, :
django-admin. dumpdata --exclude=auth

,
:

--exclude

django-admin. dumpdata --exclude=auth --exclude=contenttypes

dumpdata JSON,
.
Django.

--format

dumpdata .
, --indent,
, .

516

F. django-admin

,
appname.Model. dumpdata
, ,
.
.

flush
,
syncdb. ,
, ,
, initial_data.
?,
--noinput. , django-admin.py
, .

inspectdb
,
DATABASE_NAME,
( models.).
, ,
Django.
.
,
. ,
inspectdb :

inspectdb ,
TextField
This field type is a guess. ( ).


Python (, pass, class for), inspectdb
_field. ,
for,
for_field db_column=for. inspectdb
Field renamed because it was a Python reserved
word. ( ,
Python).

,
.

. ,
,
.

517

PostgreSQL, MySQL SQLite inspectdb


primary_
key=True. PostgreSQL
MySQL.

loaddata < ...>



.

?

. ,

.
Django :

fixtures .

, FIXTURE_DIRS.

, ,
.

,
.
, ,
. ,
django-admin.py loaddata mydata.json

JSON- mydata.
(, json xml). . Django.
, Django
. ,
django-admin.py loaddata mydata

mydata.
mydata.json, JSON.
, ,
. . ,
django-admin.py loaddata foo/bar/mydata.json

<appname>/fixtures/foo/bar/mydata.json
, <dirname>/foo/bar/
mydata.json , FIXTURE_DIRS,
, , foo/bar/mydata.json.

F. django-admin

518


. save
pre_save .
, .
,

. ,
.
loaddata,
dumpdata.


zip, gz
bz2. ,
django-admin.py loaddata mydata.json

mydata.json, mydata.json.zip, mydata.json.gz mydata.


json.bz2.
.
,
, (,
mydata.json mydata.xml.gz),
, ,
loaddata, .

MySQL
, MySQL
Django. MylSAM
, ,

.
InnoDB
, MySQL ,

.

makemessages

, .
( ) conf/locale (
Django) locale ( ).

519

compilemessages, gettext.
. 19.

all
--a ll, -,
. :
django-admin.py makemessages --all

extension
--extension, -,
( .html). :
django-admin.py makemessages --locale=de --extension xhtml


- --extension :
django-admin.py makemessages --locale=de extension=html,txt --extension xml

locale
--locale, -1, .
:
django-admin.py makemessages --locale=br_PT

domain
--domain, -d,
. :

django - . .html ( )

djangojs - .js.

reset <appname appname ...>


, sqlreset .

noinput
?,
--noinput. , django-admin.py
, .

runfcgi []
FastCGI, -,
FastCGI. . 12.
Python- FastCGI,
http://trac.saddi.com /flup.

F. django-admin

520

runserver
- .
8000 1- 127.0.0.1,
.

()
1024.
(root).
.
.
( . , -,
, ,
Django.)
Python-
, .
, .
, Python-,
(.
validate ).
, .
,
. django-admin.py runserver
.
, 1- 127.0.0.1
.
, (, 192.168.2.1)
0.0.0.0 ( )1.
--adminmedia Django, CSS- JavaS cript, .

Django, - ,
.
:
django-admin.py runserver --adminmedia=/tmp/new-admin-style/

--noreload .
, , P ython-
, ,
.
1

Django IP-
. - . . .

521

:
django-admin.py runserver --noreload

IP-
8000 1- 127.0.0.1:
django-admin.py runserver

8000 IP - 1.2.3.4:
django-admin.py runserver 1.2.3.4:8000

7000 1- 127.0.0.1:
django-admin.py runserver 7000

7000 IP - 1.2.3.4:
django-admin.py runserver 1.2.3.4:7000



(CSS-, , , URL
MEDIAJJRL, . .).

shell
shell Python.
Django IPython (http://ipython.scipy.org/ ),
. IPython ,
Python, --plain:
django-admin.py shell --plain

sql <appname appname ...>


SQL- CREATE TABLE .

sqlall <appname appname ...>


SQL- CREATE TABLE
. .
sqlcustom.

sqlclear <appname appname ..>


SQL- DROP TABLE .

sqlcustom <appname appname ...>


SQL- .

522

F. django-admin

<appname>/sql/<modelname>.sql, <> -
, a <modelname> - , .
, news Story, sqlcustom
news/sql/story.sql.
, SQL. .
,
SQL-.
, SQL- .

sqlflush
SQL-,
flush.

sqlindexes <appname appname ...>


SQL- CREATE INDEX .

sqlreset <appname appname ...>


SQL- DROP TABLE, CREATE TABLE
.

sqlsequencereset <appname appname ...>


SQL-
.

startapp <appname>

Django .

startproject <projectname>

Django . ,
django-admin. --settin g s
DJANGO_SETTINGS_MODULE. ,
--settin g s, DJANGO_SETTINGS_
MODULE.

syncdb
,
INSTALLED_APPS, .
,
- .

523

, Django,
INSTALLED_APPS.
, .

Syncdb
syncdb ,
.
ALTER TABLE, ,
.
, Django
, ,
.

, sql
,
.
django.contrib.auth syncdb
.
syncdb initial_ d ata
(, json xml). ,
, . , loaddata,
Django.

noinput
?,
--noinput. , django-admin.py
, .

test
.
. Django.

noinput
?,
--noinput. , django-admin.py
, .

testserver <fixture fixture ...>


Django ( runserver),
. .
Django.

F. django-admin

524

validate
(
INSTALLED_APPS) .


,
.

pythonpath
Python.
, django-admin.py
PYTHONPATH.
:
django-admin. syncdb --pythonpath^/home/djangoprojects/myproject

, manage. ,
Python .

settings
, .
, Python,
m ysite.settings. , django-admin.py
DJANGO_SETTINGS_MODULE.
:
django-admin.py syncdb --settings=mysite.settings

, manage. ,
se ttin g s. .

traceback
django-admin.py
. --traceback,
.
:
django-admin.py syncdb --traceback

verbosity
,
.

0 - .

1 - ( ).

525

- .

:
django-admin.py syncdb --verbosity 2



django-admin.py manage.,
SQL-, ,
ANSI-.
.

Bash
Bash,
,
extras/django_bash_completion Django.
django-admin.py manage,
, , :

django-admin.py.

Tab,
.

sql, Tab ,
sql.

G


Django .
Django HttpRequest,
. Django ,
HttpRequest .
HttpResponse.
,
API .

HttpRequest
HttpRequest HTTP-,
.
(. G.1). , session,
.
G.I. HttpRequest

path

,
, , , /music/bands/
the_beatles/n.

method

, HTTP-,
. . :
if request.method == 'GET':
do_something()
elif request.method == POST:
do_something_else()

527

HttpRequest

encoding

, ( None,
DEFAULT_CHARS).
,
.
(,
GET- POST-) .
, ,
DEFAULT_CHARSET.

GET

, GET-.
. QueryDict .

POST

, POST-.
. QueryDict .
, ,
POST, POST , - , ,
.
if request. POST, ,
POST;
if request.method == POST" (.
method ).
: POST
. . FILES.

REQUEST

, :
POST, GET.
$_REQUEST .
, GET = {"name : "john } POST = {"age : 34},
REQUEST["name ] "john", a REQUESTf "age] - "34".

GET POST, REQUEST.

COOKIES

Python, cookie.
.
cookie . 14.

FILES

,
UploadedFile. .
Django.

META

Python, -. .
:
CONTENT_LENGTH
CONTENT_TYPE
QUERY_STRING:

G.

528
G.I. ( )

REMOTE_ADDR: IP -
REM0TE_H0ST:
SERVER_NAME:
SERVER_PORT:
HTTP-
_, ;
. :
HTTP_ACCEPT_ENCODING
HTTP_ACCEPT_LANGUAGE
HTTP_H0ST: Host,
HTTP_REFERER: ,
HTTP_USER_AGENT: ,

HTTP_X_BENDER: X-Bender,
django. contrib. auth. models. User,
.
, user - django. contrib.
auth. models. AnonymousUser.
is_authenticated():
if request. user.is_authenticated():
tt

else:
tt

user ,
AuthenticationMiddleware.

. 14.
session

, ,
.
,
. . 14.

raw_post_
data

POST-.
.

,
. G.2.

529

HttpRequest

G.2. HttpRequest

__getitem_(key)

GET- POST-
, .
POST, GET. ,
.
HttpRequest
. , request["foo" ] -
, request. P0ST[ "foo ],
request.GET[foo"].

has_key()

rue, request.GET request.POST


, False
.

get_host()

,
, HTTP_X_FORWARDED_HOST
HTTP_H0ST ( ).
, SERVER_NAME
SERVER_PORT.

get_full_path()

, ,
URL. , "/music/bands/
the_beatles/?print=true .

is_secure()

rue,
HTTPS.

QueryDict
GET POST HttpRequest
django.http.QueryDict. ,
.
, HTML- ,
, <select multiple=multiple>,
.
QueryDict ,
(). , request.POST
request.GET .
QueryDict ,
.
. G.3.

G.

530

G.3. QueryDict

_getitem_

,
. ,
.

setitem

[value]
( P y th o n ,
value). , ,
,
,
QueryDict ( ()).

get()


, gct( ), _getitem__,
.

update()

QueryDict
. update
,
:
>>> q = QueryDict(=1')
>>> q = q.copyO tt
>>> q.update({ : ' 2 ' } )
> q .getlist( )
[',

2']

>>> q[' ] tt
[2 ]
items()

, iterns()
,
, _getitem() __ :
>>> q = QueryDict(a=1&a=2&a=3')
> q. items()
[(a , 3 )]

values()

, values( )
,
, __getitem()__.

QueryDict ,
. G.4.

531

HttpRequest

G.4. QueryDict
( )

,
copy. deepcopy()
P y th o n . ,
.

getl1st(key)

,
, P y th o n .
, .
,
- .

set1ist(key, 1ist_)

list_
( __setitem__()).

appendlist (key, item)

item
, key.

setlistdefault(key, a)

setdefault,
, .

lists()

items(),

, :
>>> q = QueryDict(a=1&a=2&a=3)
> q. lists()
[(a', [ T ,

urlencode()

2 , 3 ])]


( , a=2&b=3&b::5).


HTML-:
<form action^'/foo/bar/" method=,,post">
<input type=text name="your_name />
<select multiple=,,multiple" name=,,bands">
<option value=nbeatles">The Beatles</option>
<option value=who>The Who</option>
<option value=nzombies>The Zombies</option>
</select>
<input type=submit />
</form>

your_name John Smith


The Beatles The Zombies,
:

532

G.
>

request.GET

{}
>>> request.POST
{your_name: [John Smith], bands: [beatles, zombies]}
>>> request.P0ST[your_name]
John Smith
>>> request.P0ST[bands]
1zombies
> request.POST. getlist( bands)
[beatles* , zombies]
>>> request.POST.get(your_name, Adrian)
John Smith
>>> request.POST.get(nonexistent_field, Nowhere Man)
Nowhere Man

----------------------------------------------------------------------------------------------- GET, POST, COOKIES, FILES, META, REQUEST, raw_post_data user


. , Django
, .

HttpResponse
HttpRequest, Django
, HttpResponse .
, HttpResponse.
HttpResponse django.http. HttpResponse.

HttpResponse
HttpResponse
:
> response = HttpResp0nse("3T0 -. )
>>> response = HttpResponse(TeKCT ., mimetype=text/plain")

,
response :
>>> response = HttpResponse()
> response.write(<p> -.</p>)
>>> response.write("<> .</p> )

HttpResponse ,
. , , :

HttpResponse ,
- .

HttpResponse

533

, , HttpResponse write(),
,
. . 8.


:
> response = HttpResponse()
> response[X-DJANGO] = .
>>> del response[-]
>>> response[X-DJANG0]
."

has_header (header).
Cookie ; ,
cookie Django, 14.

HttpResponse
Django HttpResponse,
HTTP- (. G.5). HttpResponse,
django.http.
G.5. HttpResponse

HttpResponseRedi rect


: ,
. U RL
( , http://search,yahoo, com/)
U R L (
, /search/).
3 0 2 .

HttpResponsePermanentRedirect

HttpResponseRedi rect,
3 01 (
), 3 0 2 ( ).

HttpResponseNotMod ified

.
, ,


.

HttpResponseBadRequest

HttpResponse,
4 0 0 .

HttpResponseNotFound

HttpResponse,
4 0 4 .

534

G.

G.5. ()

HttpResponseForbidden

HttpResponse,
403.

HttpResponseNotAllowed

HttpResponse,
405.
:
(, [ GET, POST]).

HttpResponseGone

HttpResponse,
410.

HttpResponseServerError

HttpResponse,
500.

, HttpResponse
.


Django HTTP- .
HttpResponseNotFound, HttpResponseForbidden,
HttpResponseServerError . ,
,
HttpResponse, :
def my_view(request):
tt .. .

if foo:
return HttpResponseNotFound( <> </1>)
else:
return HttpResponse( <1> </>)

404 ,
.
HttpResponseNotFound HTML-
:
return HttpResponseNotFound( <> </1>)

, , Django
Http404. ,
Django
404. :
from django.http import tt404
def detai1(request, poll_id):
try:
p = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:

HttpResponse

535

raise Http404
return render_to_response( polls/detail.html , {poll: p})


Http404, ,
404. 404.html
.

404 ( )
Http404 Django
. django.views.defaults.
page_not_found,
404. html.

,
404. html.
page_not_found 99% -,
,
URL handler404:
from django.conf.urls.defaults import *
urlpatterns = patternsC ,

)
handler404 = 'mysite.views.my_custom_404_view

Django , 404,
handler404.
URL :
from django.conf.urls.defaults import *

handler404 . django/
conf/urls/defaults.py, , handler404
django. views, def aults. page_not_found.
404 :

404 , Django
URL
URL.

404,
(),
404.html .

404.

DEBUG True ( ),
404 ,
.

536

G.

500 ( )
Django
. ,
Django django.views.defaults.server_error,
500. html. ,
.
server_error 99% -,
,
URL handle500:
from django.conf.urls.defaults import *
urlpatterns = patternsC,

)
handler500 = mysite.views.my_custom_error_view


Symbols
{1,3} (), 45
404.htm l , , 248
404 ( ), , 535
404 , 45, 534
500.htm l , , 249
500 ( ), ,
536
.. ( ), 398
_ ( ), 438
% ( ), 438
. (), , 45
* (), , 45
+ (), , 45
" ( ),
, 473, 476, 478, 482
() (),
, 472, 476, 477
{} ( ),
, 472

/a b o u t/, , 195
ABSOLUTE_URL_OVERRIDES,
, 472
abstract, , 418
/a c co u n ts/lo g in /, , 193
active, , 143
add(objl, obj2, ...), , 444
add(), , 328
admindocs, , 335
ADMIN MEDIA PREFIX, , 472
-adm inm edia, , 520
adm in., , 130
ADMINS, , 472
admin, , 335
all, , 519
ALLOWED INCLUDE ROOTS,
, 473
allow_em pty, , 449
allow _future, , 457, 458, 461,
465
allow_lazy(), , 377

alters_data, , 71
ALTER TABLE, , 229
Anonym ousU ser, , 305
Apache,
Django
, 263
Django, 253
appendlist, , 531
A PPEND SLASH, , 44, 359, 473
ap plication/pd f, MIME, 279
archive_day, ,
462
archive_index, ,
456
archive_m onth,
, 459
archive_today, ,
464
archive_w eek, ,
461
archive_year, ,
458
article_detail, , 33*9
A rticle, , 339
A tom , -, 281
authenticate(), , 308, 366
AUTHENTICATION BACKENDS,
, 366
A uthenticationM iddlew are, , 359
A uthor, , 220
auth_perm ission, ,
316
auth, , 336

base.htm l, , 92
blank, , 130, 411
blocktrans, , 375
block, , 92
BookManager, , 231
book_snippet.htm l, , 220
Book, , 153

538

C A C H EBA C K EN D , , 320, 323,


3 2 8 ,4 7 3
Cache-Control, , 325
cache_control(), , 333
cache.get(), , 328
CACHE_MIDDLEWARE_ANONYMOUS_
ONLY, , 325
C A C H E M ID D L E W A R E K E Y P R E F IX ,
, 3 2 5 ,4 7 3
C A C H E M ID D L E W A R E SE C O N D S,
, 324
C A C H E M ID D L E W A R E SE T T IN G S,
, 333
cache_page, , 325
cache
, 328
, 327
Canvas, , 279
CGI ( ), 20, 58
changefreq, , 291
check_password(), , 307, 313
choices, , 411
cleaned_data, , 165
cleanup, , 513
clear(), , 445
closeblock, , 498
closebrace, , 498
closecom m ent, , 498
closevariable, , 498
cm emcache, , 320
com m ents, , 336
CommonMiddleware, , 250, 356, 476
com pilem essages, , 514
ConditionalGetM iddleware, , 334,
360
configure(), , 471
C ontent-D isposition, , 277
C ontent-Length, , 361
con ten ttypes, , 336
Content-Type, , 351
con text_instan ce, , 201
context_processors.py, , 204
context_processors, , 449
C ontext, , 65, 86, 199
cookies, 294, 300
COOKIES, , 295, 527
Cookie, , 295
()> , 531
count(), , 435
createcachetable, , 514
create(**kwargs), , 434

createsuperuser, , 514
CREATE TABLE, , 107
create_user, ,
312
create(), , 109
csrfm iddlew aretoken, , 350
CsrfM iddleware, , 350
CSRF-, 349, 395
c sr f, , 336
cStringlO , , 280
CSV, , 276
cull_percentage, , 324
CurrentSiteM anager, ,
341
cut, , 211
cx_O racle, , 35

D
DATABASE ENGINE, , 98,
3 6 4 .4 7 3
DATABASE HOST, , 99, 265,
3 6 4 .4 7 3
DATABASE NAME, , 47, 99,
474
DATABASE OPTIONS, , 474
D A T A B A SE P A SSW O R D , , 99,
3 6 4 .4 7 4
DATABASE PORT, , 364, 474
DATABASE_SERVER, , 108
DATABASE USER, , 99, 364,
474
databrowse, , 336
date_field , , 457, 460, 461, 465
DateField, , 166
DATE_FORMAT, , 474
d ates(field, kind, order), , 431
datetim e.datetim e.now (), , 49, 56
datetim e.datetim e, , 49, 56, 405
d atetim e.date, , 68, 166, 188, 405
DATETIME FORMAT, , 474
d atetim e.tim edelta, , 56
datetim e, , 48
Date, , 361
db_colum n, , 365, 413
db_index, , 413
dbshell, , 514
db_tablespace, , 419
db_tablespace, , 413
db_table, , 418
d e b u g ,, 203
/d eb u g in fo /, , 178
decim al_place, , 405


DEFA U LTC H A R SET, , 223,
475
DEFAULT CONTENT TYPE, ,
475
DEFAULT_FROM_EMAIL, ,
475
default, , 413
delete_first_token(), , 218
d elete_test_cookie(), , 300
delete(), , 329, 447
d iffsettin g s, , 515
<D irectory>, , 254
direct_to_tem plate, , 237,
450
DISALLOWED USER AGENTS,
, 359, 476
distinct(), , 431
Django
Python, 26, 28
-, 19
, 27
, 33
, 24
, 513
, 35

D J A N G O SE T T IN G SM O D U L E ,
252

, 250
, 264
Apache, 253
FastCGI, 258
, 247

, 270

, 247
, 27
, 29
MVC, 22
#django, IRC-, 27
django-admin, , 31, 36, 252, 469

Bash, 525
,512
, 524
, 513
, 525
, 513
django.contrib,
, 352
CSRF-, 349

539
, 122, 335
, 343
, 347
, 337
, 353
django.db.connection, , 234
django.form s, , 163
d jango.http, , 40
DJANGO SETTINGS MODULE,
, 63, 223, 252, 469
d jango_site, , 338
django.tem plate, , 63
D ocum entR oot, , 256
dum pdata, , 515

E
editable, , 413
EM A I L H O S T P ASS W ORD, ,
2 5 0 ,4 7 6
EMAIL_HOST_USER, , 250,
476
EMAIL_HOST, , 250, 476
EMAIL PORT, , 250, 476
EMA I L S U B J E C T P R E F IX , ,
476
em ail_user(subj, m sg), , 307
EMAIL_USE_TLS, , 250
encoding, , 527
endupper, , 218
error log, , 257
errors, , 165
error, , 155
escape(), , 413
exception, , 358
exclude(), , 427, 430
Expires, , 325
extra_con text, , 241, 244, 450

F
False, , 72
FastCGI
Django Apache
+ FastCGI, 261
Django Apache
,
263
, 259
, 258
ligh ttp d, 262
FastCG IExternalServer, , 261
Feed, , 282

540
FetchFromCacheM iddleware, , 324,
334, 361
Field, , 163
FILES, , 527
filter_horizon tal, , 142
filter_ v ertical, , 142
filter(), , 114, 212, 427, 430
FIXTURE DIRS, , 476
FlatpageFallbackM iddleware, , 344
FlatPageSitem ap, , 291
flatpages, , 336, 344
F latPage, , 344
flu sh , , 516
forloop, , 75
< form >, , 150, 164, 349
form s., , 163
form tools, , 336
for, , 62
Freenode, IRC-, 27

G
GenericSitem ap, , 291
get_absolute_url(), , 284, 472
get_all_perm issions(), , 307
get_and_delete_m essages(), , 307,
318
get_current(), , 340
get_decoded(), , 301
g et_full_nam e(), , 306
get_full_path(), , 529
get_group_perm issions(), , 307
get_h ost(), , 529
__ getitem __ (key), , 529
__ getitem __ , , 530
g et_latest_b y, , 419
getlist(k ey), , 531
g et_ list_ o r_404(), , 448
get(**lookup), , 433
get_m any(), , 329
get_object(), , 285
get_object_or_404(), , 448
get_or_create(**kw args), , 434
get_tem plate(), , 84, 87, 208
g ettex t, , 379, 387, 478
get_user(), , 366
GET, , 527
get(), , 115, 149, 160, 530
GET, , 152, 155, 189,
1 9 1 ,2 9 6 ,3 1 0 ,3 4 9 , 527
g is, , 336
g lob al_settin gs.p y, , 467
grouper, , 496


groups, , 307
GZipMiddleware, , 334, 350, 360

has_header(), , 533
has_key(), , 529
has_m odule_perm s(app_label), ,
307
h as_next, , 453
has_perm (perm), , 307
has_perm s(perm _list), , 307
has_previous, , 453
header.htm l, , 90
HEAD, , 361
h elp _text, , 413
h its, , 454
htaccess, , 263
H ttp 404, , 534
httpd .conf, , 263, 368
HTTP_REFERER, , 148
H ttpR equest,
, 526
QueryDict, 529
, 531
H ttpR esponse,
,
534
, 533
, 532
, 526
, 533
404 ( ), 535
500 ( ),
536
HTTP USER AGENT, , 148
HTTP X FORWARDED FOR,
, 361
hum anize, , 336

I
ifcon fig, , 38
< ifram e> , , 349
IGNORABLE 404 ENDS, , 477
IGNORABLE 404 STARTS, ,
477
in _bulk(id_list), , 436
include, , 207
include(), , 194
inclusion_tag(), , 220
__ in it__ ., , 36, 210
inspectdb, , 363, 516
INSTALLED A PPS, , 105, 108,
209, 298, 305, 338, 352, 477


IN T E R N A L IP S , , 203
int(), , 55, 189
ipconfig, , 38
is_anonym ous(), , 306
is_authenticated(), , 194, 306, 310
isdigit(), , 69
is_paginated, , 453
is_secure(), , 529
is_usable, , 222
is_valid(), , 165
item s(), , 530

J
JavaScript
, 385
, 156
javascript_catalog, , 386

Keep-Alive, , 270
KeyError, , 149, 152
keys(), , 150, 299
kill, , 260
kwargs.pop(), , 192

L
L A N G U A G EB ID I, , 376
LANGUAGECODE, , 204,
376, 3 8 2 ,4 7 7
LANGUAGES, , 204, 376,
3 8 2 ,4 7 7
Last-M odified, , 325
lastmod, , 291
ldconfig, , 258
1(), , 169
Library.filter(), , 212
lighttpd, , 262
link(), , 285
lists(), , 531
loaddata, , 517
load, , 210
LocaleMiddleware, , 381, 383
localflavor, , 336
locals(), , 86
location, , 290
<Location>, , 255, 368
<LocationM atch>, , 256
login(), , 308
login, , 309
logout(), , 309
logout, , 309

541

m akem essages, , 518


m ake_object_list, , 458
managed, , 419
m anage., , 37, 47, 252, 259,
4 2 6 ,5 1 2
MANAGERS, , 250, 478
Manager, , 419
M anyToM anyField, , 338, 342, 364,
416
markup, , 336
m atplotlib, , 281
m ax_digits, , 405
m ax_entries, , 324
m ax_length, , 167, 405
M axR equestsPerC hild, , 255
M ED IA R O O T, , 406, 478
M E D IA U R L , , 479
m edia, , 256
memcached, , 271,
320
, , 527
Meta, , 418
m ethod, , 526
MIDDLEWARE CLASSES, ,
105, 298, 305, 324, 334, 346, 356, 479
M iddlew areN otUsed, , 357
m iddlew are., , 350
m im etype, , 450
MIME, , 276
M odelAdmin,
, 133
, 134
, 140
m odels., , 22, 364, 415
Model, , 104
m od_fastcgi, Apache, 262
m od_proxy, Apache, 268
m od_python, Apache, 253, 470
m od_rew rite, A pache, 261
m od_w sgi, Apache, 258
MONTH DAY FORMAT, , 479
MTV, , 97
MVC, , 22, 96
M ySpace, , 394
MySQL, 35, 269, 518

N
__ name__ , , 185
never_cache, , 333
n ext, , 453
n gettex t, , 387

542
N odeList, , 217
Node, , 214
NOT NULL, 131
now, , 50
NULL, , 131
null, , 410
n um _latest, , 457

objects, , 113
object, , 456, 466
openblock, , 498
openbrace, , 498
opencom m ent, , 498
openvariable, , 498
Oracle, 35
order_by(), , 116, 430
ordering, , 420
o s.en v iro n fT Z ], , 483

p age_not_found, , 535
pages, , 454
page, , 453
parser, , 214
parse(), , 217
patch_vary_headers(), , 332
p a th ,, 526
patterns(), , 41, 176
PDF, , 278
perm ission_required(), , 312
perm issions, , 307
pickle, , 303, 322
ping_google(), , 293
pkg_resources, , 222
plural, , 376
PostgreSQL, 33, 269
post_save, , 424
POST, , 527
-, 378, 383, 388
PREPEND W W W , , 359, 479
pre_save, , 423
previous, , 453
prim ary_key, , 414
priority, , 291
p rocess_exception(), , 358
process_request(), , 357
process_response(), , 358
process_view (), , 357
proxy, , 420
psycopg, , 34
psycopg2, , 34
P ublisher, , 103, 109


pygraphviz, , 281
pysqlite, , 34
Python
, 372
, 32

, 348

, 346
, 28
, 102
, 26
PythonA utoR eload, , 254
PythonDebug, , 254
Python Im aging Library, ,
409
P ythonlnterpreter, , 255
python-mem cached, , 320

Q
QueryDict, , 529
queryset, , 450
QuerySet,
, 427
, QuerySet,
430
, QuerySet,
433
, 231
, 429
Q-, 441

R
raw _id_fields, , 142
raw _post_data, , 528
R edirectFallbackM iddleware, , 347
redirects, , 336
redirect_to, , 451
R eferer, , 303
register, , 211
REMOTE ADDR, , 148
rem ove(objl, obj2, ...)> , 445
render_to_response(), , 86, 161, 200
render(), , 62, 65, 66, 213, 215
ReportLab, , 278
repr(), , 428
R equestC ontext, , 199, 345
REQUEST, , 527
requires_login(), , 193
reset, , 519
results_per_page, , 453
R OOTURLCO NF, , 47, 82, 253,
480


RSS-, 281, 287
runfcgi, , 260
runfcgi, , 519
runserver, , 37, 50, 247, 520

S
save(), , 1 0 9 ,1 1 2 , 119, 280, 423
<script> , , 393
search(), , 1 5 4 ,1 5 7 , 159
SEC R E TK E Y , , 480
select_related(), , 432
self.cleaned_data, , 169
SEND BROKEN LINK EMAILS,
, 480
SERIALIZATION MODULES, ,
480
SERVER_EMAIL, , 480
server_error, , 536
S E SSIO N C O O K IE A G E , , 480
SESSION COOKIE DOMAIN, ,
481
SESSION COOKIE N , ,
481
SESSION_COOKIE_SECURE, ,
481
SESSION_EXPIRE_AT_BROW SER_
CLOSE, , 481
S E S S IO N S A V E E V E R Y R E Q U E S T ,
, 481
sessions, , 336
session, , 528
Set-Cookie, , 295
set_cookie(), , 296
__setitem __ , , 530
set_language, , 385
setlistdefault(key, ), , 531
setlist(key, list_), , 531
SetRemoteAddrFromForwardedFor,
, 361
set_test_cookie(), , 300
se ttin g s., , 37, 47, 50, 82, 247,
250, 367
setu p., , 30, 36
set(), , 329
shell, , 521
silent_variable_failure, , 70
SITE_ID, , 340, 342, 345, 481
sitem aps, , 336
sitem ap.xm l, , 289
Sitem ap-, 290
site-packages, , 31
sites, , 336
Site, , 338, 341, 343

543
socket, , 252
split(), , 169
sqlall <appname appname ...> ,
, 521
sql <appname appname ...> , ,
521
sqlcustom <appname appname ...> ,
, 521
sq lflush , , 522
sqlindexes <appname appname ...> ,
, 522
SQLite, 34, 98
sqlite-python, , 35
sql_queries, , 203
sqlreset <appname appname ...> ,
, 522
sqlsequencereset <appname appname ...> ,
, 522
Squid, 320
startapp <appnam e>, , 522
startproject <projectnam e>, ,
522
strftim e, , 213, 406
string_concat(), , 377
sym m etrical, , 417
syncdb, , 108, 226, 522
syndication, , 336

T
tag(), , 215
T E M PLA T EC O N TE X T PR O C E SSO R S,
, 202, 315, 481
T EM PLA TED EBUG , , 223,
248, 482
TEMPLATE DIRS, , 47, 82, 93,
208, 222, 223, 289, 482
T em plateD oesN otE xist, , 85,
89, 208, 238
TEMPLATE LOADERS, , 209,
2 2 1 ,4 8 2
tem plate_loader, , 450
tem piate_nam e, , 450
tem plate_object_nam e, , 450
T E M PL A T E ST R IN G I F I N VALID,
, 482
Tem plateSyntaxError, , 64,
69, 74
TEMPLATE ZIP FILES, , 222
Template, , 65, 84
test_cookie_w orked(), , 300
TEST_DATABASE_NAM E, ,
482
TEST_RUNNER, , 483

544
testserver < fix tu re fix tu re ...> ,
, 523
test, , 523
< textarea> , , 167
TIME FORMAT, , 483
TIME_ZONE, , 483
TINYINT, , 404
TransactionM iddleware, , 361

U
u g ettext_lazy(), , 373
ugettext_n oop(), , 373
u gettext(), , 372, 382
u n gettext(), , 374
Unicode, , 111
__Unicode__(), , 1 1 0 ,1 3 4
unique_for_date, , 414
unique_for_m onth, , 414
unique_for_year, , 414
unique_together, ,
420
unique, , 414
UpdateCacheM iddleware, , 324, 334,
361
update(), , 119, 530
upperQ, , 69
urlencode(), , 531
urlpatterns, , 42, 178
U R L V A L ID A T O R U S E R A G E N T ,
, 484
U S E E T A G S , , 484
U SE _I18N , , 484
u ser_passes_test, , 311
user, , 528
User, , 308

V
validate, , 106
V alidationError, , 169
ValueError, , 55, 189, 329
values(), , 150, 431, 530
Vary, , 330
vary_on_cookie, , 331
vary_on_headers, , 332
verbose_nam e_plural,
, 3 7 4 ,4 2 1
verbose_nam e, , 133,
1 6 9 ,3 7 4 ,4 2 1
v iew s., , 23, 39, 49, 56, 163
view s, , 151, 176
< V irtualH ost> , , 254


W
w ebdesign, , 337

X
X-Forwarded-For, , 355

Y
YEAR MONTH FORMAT, ,
484

Z
ZIP-, 280


, 424
Bash,
525
, 223

ModelAdmin,
, 133
, 134
, 140
,122
, 144
, 128
, 132

, 348

, 346
, 130
, 1 2 1 ,1 2 3
, 143
, 144
, 143
, 129
, (django.
contrib.sessions), 122
,
, 186
, 79, 208

, 314
, 297
, 304
, 305
, 308
, 313



, 365
, 315

, 311

, 310

U ser, 305
, 312

, 359
, 314

, 91

Django, 33
, 97
, , 226
, , 363
, 267

cookies, , 395
,
395
SQL, 391
, 393
, 396
, 390
, 398
,
399
, 468
, 395
HTTP- (CSRF), 395
, 396
-, 80, 96
, 64

545


398
, 207
, 454
, 281
, 185
URL-, 51
, 281
, 48

, 359
, 356
, 354
, 355
, 356
, 96, 108
, 91

(_), 438
(% ), 438

Google, 293
, 513
, 373, 387
, 178, 192
, 178
, 259

g ettex t, 388
JavaScript, 385
set_lan gu age, , 385
, 372
, 370
, , 378
, 381
, 102

-, 19
, 129, 225, 443
, 112

(), 28
,281
, 144, 304, 317

,
URL-, 287
, 286
, 282
, 281

A tom RSS, 287
, 283
, 287

546
,
Sitem ap-, 290
, 292
, 289
Google, 293
, 288
, 291
, 289
, 37
, 62, 65, 199
, 199

, 47, 82
URL
include(), , 194

, 180
, 178
, 326
, 39, 175
, 47

, 188
, 51
URL, 189
, 56

,
189
, 193

, 181
, 175
, 46

M emcached, 320
CACHE BACKEND, , 323
MIDDLEWARE CLASSES, ,
334
, 321
, 322
, 322
Vary, 330
QuerySet, 427
, 325
, 324
A PI, 328
, 323
, 330
, 332
, 323
, 327
-, 330

, 370

, 267
, 265
, 265
, 264
, 267
(XSS), 205, 393

, , 230

QuerySet, 231
, 230
, 113

. (), 45
*
(), 45
+ (), 45
, , 169
--
, 129
, 140, 225, 229
,446
, , 374

SQL-, 234

, 226
, 97
, 112

, 113

, 118
, 117
, 115
, 117
, 116
, 114
, 108
, 230
, 418
, 233
, 112

Python, 102
, 102
, 224
, 109


, 119
, 105
MTV
MVC, 96

547

ForeignK ey, 415


M anyToM anyField, 416
OneToOneField, 417

, 32

, 124
, 168

, 193

, 449

, 462
, 459
, 461
, 464
, 458

, 464
, 456
, 456
,
240
, 237
, 236
, 238
, 450

, 240
, 241

, 242

, 243
/, 452
, 238, 398
, 428

, 426
, 442
, 423
, 425
, 447
,
, 250
, , 249
, 399
, 373, 377

, 392

, 468
-, 468
, 467
, 468

DJANGO_
SETTINGS MODULE, 470
DJANGO_
SETTINGS_MODULE, 469
, 467
, 472
, 469
, , 313
,
, 424
, , 347
, 371
, 525
, 373, 387
, 192
, 68

contains, 437
d a y ,439
endsw ith, 439
exact, 437
gt, 438
gte, 438
icontains, 438
iendsw ith, 439
in, 439
isn ull, 440
istartsw ith , 439
lexact, 437
It, 438
lte, 438
m onth, 439
range, 439
search, 440
startsw ith , 439
year, 439
pk, 440
, 305
, 143
, 311
, 312

548

A utoF ield, 404


BooleanField, 404
CharField, 167, 405
C om m aSeparatedlntegerField, 405
D ateField, 405
D ateTim eField, 405
D ecim alField, 405
Em ailField, 406
FileField, 406
FileP athF ield, 408
FloatField, 408
ForeignK ey, 339, 342, 415
Im ageField, 408
IntegerField, 409
IPA ddressField, 409
N ullBooleanField, 409
P ositiveln tegerF ield , 409
P ositiveSm allln tegerF ield, 409
S lugField, 409
Sm alllntegerF ield, 409
T extField, 410
Tim eField, 410
U RLField, 410
XM LField, 410
, 227
, 130
, 131
, 403
, 229
, 423

, 39
, 298, 301
, 81
, 357
,
HTML, 275
, 56
, 80, 96
, , 101
, 156, 168

, 37
, 35
, 100
, , 270
, 330
, 359
, 473, 476, 478, 482
, 472, 476, 477
, 472

, 314
, 454
, 143, 304, 316
, 316
-, ,
361
, 314
, 45
, 46, 178, 203, 247, 475,
513
, 267

,
CurrentSiteM anager,
, 341
, 338
Django, 343
, 337
,313
,313

, 446
, 224, 442
, 443

, 225
--, 225
, 442

, 443
--, 446

, 301
, 298
, 298
, 302
, 298
cookies, 300
, 37
, 518
, 317
, 23
, 116
URL, 188

, 125, 134
, 452
, 335
, 56


, , 152
, 208
, 123, 144

, , 107

autoescape, 206, 485


block, 485
com m ent, 78, 218, 485
cycle, 486
debug, 487
else, 73
em pty, 75
endcom ment, 218
endif, 72
endifequal, 77
extends, 487
filter, 487
firsto f, 487
for, 74, 218, 488
if, 72, 218, 489
ifchanged, 218, 490
if equal, 77, 218, 491
ifnotequal, 492
include, 88, 492
load, 492
now, 492
regroup, 495
spaceless, 497
ssi, 497
tem platetag, 497
trans, 375
upper, 218
url, 498
w idthratio, 499
w ith, 499
, 219

, 218
, 485
, 212
,
217
, 215
, , 399

, 119, 447
, 348
, 346
, 212

549
, 410
, 144

Django, 29
P y th o n ,28
ReportLab, 278
, 356
,105

, 378
, 517

QuerySet
, 430, 433
, 429
, 243
, 114, 427
, 428

a d d ,499
addslashes, 79, 499
cap first, 499
center, 500
cut, 500
date, 62, 79, 500
d efault, 500
d efault_if_non e, 500
d ictsort, 500
d ictsort re versed, 501
d ivisibleby, 501
escape, 205, 208, 501
escapejs, 502
filesizeform at, 502
first, 502
fix_am persands, 502
floatform at, 502
force_escape, 503
get_ d ig it, 503
iriencode, 503
join, 504
last, 504
length, 504
len gth _is, 504
linebreaks, 504
linebreaksbr, 505
linenum bers, 505
ljust, 505
lower, 505
m ake_list, 505
phone2num eric, 505
pluralize, 505
pprint, 506

550
random, 506
rem ovetags, 506
rjust, 506
safe, 506
safeseq, 506
slice, 507
slu g ify , 507
strin gform at, 507
strip tags, 507
tim e, 507
tim esince, 508
tim etim eun til, 508
title, 508
truncatewords, 508
truncatew ords_htm l, 509
unordered list, 509
upper, 509
urlencode, 509
urlize, 509
urlizetrunc, 510
wordcount, 510
wordwrap, 510
yesno, 510
, 393

, 158


, 168

,167
,
166
,
170
, 163

,167
, 169
, 147

, 147
, 156
, 150
, 125, 140

, 117

R equestC ontext, , 199


Tem plate, , , 63

HTML, 205
, 82, 208, 221
, 79
, 81

, 315
, 78
, 71
, 199
, 82

, 223
, 60, 198
,79
, 346
, 68

, 219

, 218
,
215
, 209

, 217
, 215
, 210
, 214
, 212
, 213
, 65
, 67
, 221
, 72, 88
, 198
, 78

HTML, 501
, 205

, 391
, 397

, , 378

Django.


H i
1> Djngo. 0<i
. EveryBloc*.. .
' .

-


Django.
Revolution Syitem,
*

D jango -
- Python,
-
.
Django
.

- ,

.
D ja n g o
.
.

- D jango - .
PDF RSS, ,
. .
P ython
- .

CipmiMai
uai iiui

Not. fccoc
tophau

- ;

n ty > a < l

ItllM H Itlli

ii PfJu

Hfwutyto
U

IlM lv


lo r^a

farerofv* -
! * * nCUTOrOBKJ (P f& U U

. n | l l l f M ll li c
|0 1

iiii

Apress
IS8N 978-5-93286-187-5

80\

www.symbol.ru
-

(812) 324-5353. (495) 945-8100

i ifc a