Django Step by Step 2010 版(基于 Django 1.1.1 )


Django Step by Step 2010 ‡(Äu Django 1.1.1 ) chinakr 2010.08.03 ÁÁÁ‡‡‡µ limodou Œc3 2006 ce Django Step by Step §–8§E´ Django \€²;á" ØLž§´Äu Django 0 . 9 . 5 §²L 3 cõuЧX8 Django ®²uÐ 1 . 1 . 1 § Ù¥kéõ•#Ø´•eoN"žXÆSÚ¦^DjangoŬ§·OÄuDjango 1 . 1 . 1 • ùŸ§(Ù¢•Ò´·ÆS)P§Øпg§…Ò§ Django Step by Step 2010 ‡§3ùp • limodou Œc—¹§F"†Œ[ž" Contents 1 111˜˜˜ùùù 2 1.1 mŸ: Django \€N .....................................2 1.2 SC.................................................2 1.3 )¤‘88¹( Project )......................................3 1.4 éÄ Web ÑÖì( Web Server )..................................3 1.5 m©·‚1˜‡A^ Hello World !( app )...........................3 1.6 ?U urls.py............................................4 1.7 (.................................................4 2 111ùùù 4 2.1 Úó .................................................4 2.2 Mï add.py ©‡..........................................4 2.3 ?U urls.py............................................5 2.4 3 Web èAì¥ÿÁ.......................................5 2.5 (.................................................5 3 111nnnùùù 5 3.1 Úó .................................................5 3.2 Mï list.py ©‡..........................................6 3.3 Mï templates 8¹ ........................................6 3.4 ?U settings.py..........................................6 3.5 Mï list.html ©‡.........................................6 3.6 ?U urls.py............................................7 3.7 3 Web èAì¥ÿÁ.......................................7 3.8 (.................................................7 4 111oooùùù 7 4.1 Úó .................................................7 4.2 ?U list.html...........................................7 4.3 Mï csv-test.py ©‡........................................7 4.4 Mï csv.html ©‡.........................................8 4.5 ?U urls.py............................................8 4.6 3 Web èAì¥ÿÁ.......................................8 4.7 (.................................................8 1 5 111ÊÊÊùùù 8 5.1 Úó .................................................8 5.2 Mï login.py ©‡.........................................9 5.3 Mï login.html ©‡........................................9 5.4 ?U urls.py............................................ 10 5.5 ?U settings.py.......................................... 10 5.6 Щzê⥠............................................ 10 5.7 3 Web èAì¥ÿÁ....................................... 10 5.8 (................................................. 10 6 111888ùùù 10 6.1 Úó ................................................. 10 6.2 Mï wiki app........................................... 11 6.3 ?U wiki/models.py........................................ 11 6.4 SC wiki app........................................... 11 6.5 ?U settings.py.......................................... 11 6.6 Щzê⥠............................................ 11 6.7 Mï wiki Ä•.......................................... 12 6.8 ?U wiki/views.py........................................ 12 6.9 Mï templates/wiki/page.html ©‡............................... 13 6.10 Mï templates/wiki/edit.html ©‡............................... 13 6.11 ?U urls.py............................................ 13 6.12 3 Web èAì¥ÿÁ....................................... 14 6.13 (................................................. 14 7 django ˜˜˜‡‡‡~~~fff 14 7.1 #ó§ ............................................ 14 7.2 #ï¬ .............................................. 15 7.3 #ïêâ¥^rÚê⥠..................................... 15 7.4 ¢ymodels§êâ¥N'X................................... 15 7.5 ¢y views §é–....................................... 17 7.6 ¢yw«†............................................ 17 1 111˜˜˜ùùù 1.1 mmmŸŸŸ: Django \\\€€€NNN Django ´ Python e•9€ Web muµe( Web Framework )§§õUrŒ!«¹!A^ ¯õ!uÐׄ§¯õpÃwЧÉ 2Œ Python ^rUO" Django ‘8(•Jø ˜ \€ §§^{áŸÌЫ Django ̇AÚ"ØLéuÐÆö5`§ÆSù §˜e> õÀ ܧ J±žz"3ùp§·‚‡‹»ù«•ª§l˜‡•{ü~f‰å§P¹eù‡L§§/¤˜ Ÿ§" 1.2 SSSCCC ·ÿÁ‚¸´ Ubuntu 9.10 §ù´8c•61 Linux S¡öŠXÚ"l(•^‡ ¥S C Python Ú Django µ $ sudo aptitude install python $ sudo aptitude install python-django 5µ/$0´ Ubuntu 9.10 ªà( Terminal )·-1J«Î§eÓ ·‚w˜e§‚‡Òµ $ aptitude show python $ aptitude show python-django Python ‡Ò´ 2.6.4 § Django ‡Ò´ 1.1.1 " 2 1.3 )))¤¤¤‘‘‘888888¹¹¹( Project ) ·‚3[8¹ (home) e# workspace 8¹§^5• “è" $ mkdir workspace $ cd workspace $ mkdir django $ cd django e5·‚¤kÿÁÑ3 /workspace/django/ 8¹e?1" Django Jø django-admin ù‡óä5 Mï‘88¹µ $ django-admin startproject newtest ù¬3c8¹e#ï newtest 8¹§ newtest 8¹ek 4 ‡©‡µ ~__init__.py~: L«ù´˜‡Python•" ~manage.py~: Œ‰1©‡"^u‘8+n{Bó䧌±gÄ?n~DJANGO_SETTINGS_MODULESÚPYTHONPATH~" ~settings.py: Django~˜©‡" ~urls.py~: ?nURLN" 1.4 éééÄÄÄ Web ÑÑÑÖÖÖììì( Web Server ) Django S˜ ˜‡. Web ÑÖ짌Œ•B §SNÁ"·‚y3ÒŒ±3 newtest 8¹eé Äù‡S˜ Web ÑÖì" $ ./manage.py runserver ~œ¹eòÑye¡J«µ Validating models... 0 errors found Django version 1.1.1, using settings ’newtest.settings’ Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. ·‚3èA쥅\µ http://127.0.0.1:8000/ It worked! Congratulations on your first Django-powered page. Of course, you haven’t actually done any work yet. Here’s what to do next: * If you plan to use a database, edit the DATABASE_* settings in newtest/settings.py. * Start your first app by running python newtest/manage.py startapp [appname]. You’re seeing this message because you have DEBUG = True in your Django settings file and you haven’t configured any URLs. Get to work! öU\§ù`²\ Django ®²m©óŠ œ4·‚UYjœ 1.5 mmm©©©···‚‚‚111˜˜˜‡‡‡AAA^^^ Hello World !( app ) Django ¥A^´± app /ª•3§ù´ Django ̇AÚ§ÏL§\Œ±”´/¢y“è •^Ú•uÙ" ØL• •Ð/t˜Ù Django 3ZŸo§·‚k7L app §†)¤˜‡ URL N( URL N‰ ¯œÒ´N^˜‡ Python •{5?n˜‡URLž¦§^rŽ‡(J)"3 newtest 8¹e# ï helloworld.py ©‡§SN•µ from django.http import HttpResponse def index(request): return HttpResponse(’Hello World!’) 3 1.6 ???UUU urls.py from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns(’’, # Example: # (r’^newtest/’, include(’newtest.foo.urls’)), # Uncomment the admin/doc line below and add ’django.contrib.admindocs’ # to INSTALLED_APPS to enable admin documentation: # (r’^admin/doc/’, include(’django.contrib.admindocs.urls’)), # Uncomment the next line to enable the admin: # (r’^admin/’, include(admin.site.urls)), ) ·‚r§?U•µ from django.conf.urls.defaults import * urlpatterns = pattern(’’, (r’^$’, ’newtest.helloworld.index’), ) þ¡r5ºÑŽÑ "r’^$’´˜‡š˜iÎGKLˆª§\–¯ http://127.0.0.1:8000/ žÒ ¬N^þ˜!·‚Mïhelloworld.py¬¥index•{"XJ\®²éÄ Django S˜ Web ÑÖ ì§@ož3WebèA쥖¯˜e http://127.0.0.1:8000/ "´Ø´w/ Hello World! 0 §%œ- Äíº‡·1˜gw§žÿ§%œ´é-Ä. 5 Django •Œ±ùo{üB" 1.7 ((( Django ´˜«tÑ Web muµe|ܧ§Q{üqE,"{ü´Ï•§éN´þ猱¯„ muÑp Web A^"E,´Ï•‡Ýº§gÄz!p?õU\I‡ÆSéõÀÜ"e5§ ·‚UY˜:˜:/÷ Django õUA5j" 2 111ùùù 2.1 ÚÚÚóóó e5·‚‡ÆS˜‡' Hello World !E,˜ ~f3 Web •¡¥¢y˜‡\{ì"•‡ (JXeµ http://www.woodpecker.org.cn/obp/django/django-stepbystep/newtest/doc/tut02_01.jpg ü‡^uÑ\©µ§˜‡Ò´JUܧ±9˜‡w«\{(J©µ"ÏL¢yù‡~f§· ‚òƬXÛ?n Web •¡Jêâµ¼^rÑ\§¿‰Ñ(‡"" 2.2 MMMïïï add.py ©©©‡‡‡ Django µe.¡• MTV§•Ò´ Model + Template + View §§Ú˜„ MVC ¹ÂÙ¢´ ˜§•´¡ØÓ" Model ¢y éê⥖¯§ Template ¢y Web •¡†§ View K ´?n URL !¤•ª•¡•{"·‚ùpMï add.py Ù¢Ò´ View " add.py SNXeµ 4 from django.http import HttpResponse html = ’’’
+
’’’ def index(request): if request.POST.has_key(’a’): a = int(request.POST[’a’]) b = int(request.POST[’b’]) else: a = 0 b = 0 return HttpResponse(html % (a, b, a+b)) J«µ action ƒ¤±´ //add/0 Ø´ //add0 §´• ;•Ø POST êâ (\Öµ~http://code.djangoproject.com/wiki/NewbieMistakes~) ¤k View ¥•{§1˜‡ëêÑ´ request é–§§Šd Django gÄ)¤§k GET Ú POST ü «á5§©O•ØÓ•ªJêâ"ùü‡á5ÑŒ±”i;˜óŠ (\Öµ~http://www.djangoproject.com/documentation/request_response/~)" 2.3 ???UUU urls.py ?U urls.py SN•µ from django.conf.urls.defaults import * urlpatterns = patterns(’’, (r’^add/$’, ’newtest.add.index’), ) 2.4 333 Web èèèAAAìì쥥¥ÿÿÿÁÁÁ kéÄ Django S˜WebÑÖì§,3\ Web èAì¥Ñ\ http://127.0.0.1:8000/add/ §w w\´Ø´ ((J" 2.5 ((( 3ù˜ù§·‚{ü/Ы Django  MTV e¥ Template Ú View §\Œ±r add ¬  html á5wŠ Template §r add ¬ index •{wŠ View "ÏL?U urls.py §4A½ View • {?nA½ URL §l ·‚Ž‡(J§ùÒ´ Django ÄóŠn"3 form ¥·‚¦ ^ post Ø´get§ù´• ÚDjangoOº‚Ú˜"DjangoOº‚@•µ¦^POSTL«‡éêâ ?1?U§¦^GET•´¼"@Œù‡º‚§¿¤ƒÓS.§´˜‡š~Яœ"'u URL N \Öµ ~http://www.djangoproject.com/documentation/url_dispatch/~ 3 111nnnùùù 3.1 ÚÚÚóóó þ˜ù¥§·‚†^ add.index() ˆ£ HTML “è§ù«·Ü•ª(• Template Ú View ·Ü3˜ å)Ø·ÜuŒ.mu"ù˜ù·‚‡ÆS Template (†)¦^" Django g‘†XÚ§,\•Œ 5 ±¦^gC†XÚµ3 return c¦^gCU•†XÚ?1?n§,ˆ£"ØL Django g‘ †XÚkéõA:§·‚e5Ò¦^§"·‚¦^~f´µ^˜‡L‚5w«ÏÕ¹êâ"3ù p·‚E,kئ^ê⥧ ´rêâ•3 View ¥" 3.2 MMMïïï list.py ©©©‡‡‡ list.py SNXeµ #-*- coding: utf-8 -*- from django.shortcuts import render_to_response address = [ {’name’:’Ün’, ’address’:’/Œ˜’}, {’name’:’oo’, ’address’:’/Œ’} ] def index(request): return render_to_response(’list.html’, {’address’:address}) J«µXJ “è¥Ñy ¥©iΧ©‡mÞÒ‡\þ ~/#-*- coding: utf-8 -*-0~ ù˜1§L«¦^~UTF-8~?è" ùp¦^ ~render_to_response~ù‡•{§§N^ ~list.html~ù‡†§^i;W¿†(•Ò´ r†¥CþO†¤ƒASN§ùq¡•/)§,ˆ£)¤©"ù«•ªÚ‚ªziÎG (~Xµ~print ’Hello %s!’ % ’World’)~š~ƒq" 3.3 MMMïïï templates 888¹¹¹ 3 newtest 8¹eMï templates 8¹§^5•˜†©‡" $ mkdir templates 3.4 ???UUU settings.py é~TEMPLATE_DIRS~§?1Xe?Uµ TEMPLATE_DIRS = ( ’./templates’, ) XJkõ‡†8¹§Œ±Ñ\\~TEMPLATE_DIRS~ù‡|( tuple )§ Django ¬U^S|¢ù 8 ¹" 3.5 MMMïïï list.html ©©©‡‡‡ 3 newtest/templates/ 8¹eMï list.html §SNXeµ

ÏÕ¹

{% for user in address %} {% endfor %}
{{ user.name }} {{ user.address }}
ù‡†©‡¬)¤˜‡üL‚"3 Django †¥§ 6 {% %}L«“èN^§{{ }}L«CþÚ^"~for ... in~¡•†I\(tag)§Django†kéõõU rŒI\§¿…Œ±?1*Ð" 'u†Šó\Öµ ~http://www.djangoproject.com/documentation/templates/~ 3.6 ???UUU urls.py é urlpatterns §?U•µ urlpatterns = pattern(’’, (r’^list/$’, ’newtest.list.index’), ) 3.7 333 Web èèèAAAìì쥥¥ÿÿÿÁÁÁ kéÄ Django S˜ Web ÑÖì§,3\èAì¥Ñ\ http://127.0.0.1:8000/list/ §\ATw Xe(Jµ 3.8 ((( 3ù˜ù¥§·‚ým©¦^ Django †( Template )XÚ "{ü£˜e·‚щ Ÿo§ ·‚kMï View §3 View ¥¦^ †§,Mï†8¹!?U settings.py ¿Mï †©‡§ e5?U urls.py "3†©‡¥§·‚¦^ †I\( Tag )§}Á “èN^ÚCþÚ^"qc? ˜Ú§4·‚UYjœ 4 111oooùùù 4.1 ÚÚÚóóó £ƒcSN§·‚Œ±w Django Œ—mu6§µV\ View •{-> V\†-> ? U urls.py 2\þê⥃'.( Model )Ü©§ù‡6§3Ü6þÒ "ØL3·‚m© ÆS.ƒc§·‚2ý˜eƒcÆ•£"3ù˜ù§·‚‡U?þ˜ùÏÕ¹§Jø CSV ‚ ªÏÕ¹e1" 4.2 ???UUU list.html 3 templates/list.html ©‡"—\þ˜1µ

csv‚ªe1

ù “è¬3ÏÕ¹L‚ew«˜‡•• CSV ‚ªÏÕ¹©‡‡ó" 4.3 MMMïïï csv-test.py ©©©‡‡‡ 3 newtest 8¹eMïcsv_test.py©‡§SNXeµ #-*- coding: utf-8 -*- from django.http import HttpResponse from django.template import loader, Context address = [ (’Ün’, ’/Œ˜’), (’oo’, ’/Œ’) ] def output(request, filename): response = HttpResonse(mimetype=’text/csv’) response[’Content-Disposition’] = ’attachment; filename =%s.csv’ % filename 7 t = loader.get_template(’csv.html’) c = Context({’data’:address}) response.write(t.render(c)) return response J«µØ‡¦^ csv.py Š•©‡¶§§¬ÚXÚ csv ¬•¶" ùpvk¦^~render_to_response~§Ï•·‚I‡?U response é–Š§ ~render_to_response~µ C response ¦·‚Ã{?U§"¢SóŠ6§´µMï response é–( HttpResonse a˜ ‡¢~)§?U response á5§\1†(k)¤ template é–§2)¤ Context é–)!/ †( t.render(c) )§ˆ£OÐ response é–"5¿§ùp address Ø´i;L§ ´| L§¢Sþ•‡´S§ Django †ÑU?n"'u request Ú response \Öµ ~http://www.djangoproject.com/documentation/request_response/~ 4.4 MMMïïï csv.html ©©©‡‡‡ 3 newtest/templates/ 8¹eMï csv.html ©‡§SNXeµ {% for row in data %} "{{ row.0|addslashes }}", "{{ row.1|addslashes }}" {% endfor %} P4 data ´˜‡L§ ù‡Lƒ´|§Ïd row.0 Ú row.1 Ò´|1˜‡Ú1‡ ƒ"—´LÈÎÒ§L«òc¡?n(JŠ•Ñ\D\¡?n§ addslashes ´ Django †S˜ LÈI\( Tag )§§Š^´‰AÏiÎ\þ‡‚" Django ¥Œ±g½ÂI\§äNŒ±Öµ ~http://www.djangoproject.com/documentation/templates_python/~ 4.5 ???UUU urls.py éurlpatterns§?U•µ urlpatterns = pattern(’’, (r’list/$’, ’newtest.list.index’), (r’csv/(?P\w+)/$’, ’newtest.csv_test.output’), ) O\ ù‡ URL N§XJ\–¯ /csv/address/ §òN^ csv.output(filename=’address’) " 4.6 333 Web èèèAAAìì쥥¥ÿÿÿÁÁÁ kéÄ Django S˜ Web ÑÖì§,3\èAì¥Ñ\ http://127.0.0.1:8000/list/ §w• ‡ó í§:˜eww´Ø´¬J«\e1Ú• address.csv ù‡©‡" 4.7 ((( Django †XÚ! View •{! URL N´š~rŒÚ´u¦^§3ù˜ùp·‚2gw ù˜:"e5·‚Ò‡ÆS¬( Template )§m©Úê⥋ " 5 111ÊÊÊùùù 5.1 ÚÚÚóóó ù˜ù·‚‡ÆS session §¿m©>.( Model )" session •Ò´¬{§´• 3 Web •¡ m†êâ )§§•3èAì cookie ¥"3 Django ¥¦^ session š~{ü§•I‡– ¯ request é– session á5§\Œ±r§Š˜‡i;5¦^"·‚êþm©Á"‰^rJø˜‡ ¹•¡§þ¡k˜‡©µ^5Ñ\^r¶§„k˜‡JUÜ^5Jêâ"^rÑ\^r¶§: ÂJUܧÒw«^r®²¹§¿…‹<Ñ^rÑ\^r¶§ÓžJø˜‡5•UÜ"XJ^r : 5•Uܧң™¹•¡"™¹GÚ¹G´PÁ§•Ò´\¹¤õ§¿… 8 vk5•ž§\2g–¯E,w«´¹¤õ•¡"\vk¹½ö5•§\2g–¯Ò´™ ¹¤õ•¡" 5.2 MMMïïï login.py ©©©‡‡‡ 3 newtest /8¹eMï login.py ©‡§SNXeµ from django.http import HttpResponseRedirect from django.shortcuts import render_to_response def login(request): username = request.POST.get(’username’, None) if username: request.session[’username’] = username username = request.session.get(’username’, None) if username: return render_to_response(’login.html’, {’username’:username}) else: return render_to_response(’login.html’) def logout(request): try: del request.session[’username’] except KeyError: pass return HttpResponseRedirect(’/login’) ùp½Â ü‡ View •{§ login() Ú logout() " login() Jø¹•¡§?n^rJêâ§ä^ r´Ä¹" logout() l session ¥íØ^r¶§ò•¡•#½•¹•¡" Django †|±^‡ ä§ÏdùpŒ±ÏLD\ØÓi;5››†)¤" login() äNóŠ6§´ùµ 1. lPOST¥Ñusername§POST¥êâ´dHTML•¡Lü(form)Jø"XJ¤õ username§Òr§\\session¥(¢SþÒ´öŠsessionù‡i;§XJusernameù‡…Ø •3§Ò#ïù‡…Šé§XJusernameù‡…®•3§ÒCXù‡…Šé)" 2. lsession¥Ñusername"XJ¤õ username§Òˆ£®¹•¡§XJvkusername§ Òˆ£™¹•¡"ùpN^ØÓ•¡Ò´ÏL †D\ØÓi;5¢y" logout() óŠ6§•{üµ}ÁíØ session §,•½•™¹•¡" 5.3 MMMïïï login.html ©©©‡‡‡ Mï newtest/templates/login.html ©‡§SNXeµ {% if not username %}
^r¶µ
{% else %} {{ username }}§s®²¹ œ
{% endif %} Django †¥ if ^{Ú Python ¥ƒq§Œ±¦^ not, and, or "3ùp§XJ username Ø•3§ Kw«˜‡Lü§w«^r¶Ñ\©µÚ¹UÜ"XJ username •3§Kw«^r¶Ú5•UÜ" 9 5.4 ???UUU urls.py é urlpatterns §?U•µ urlpatterns = patterns(’’, (r’login/$’, ’newtest.login.login’), (r’logout/$’, ’newtest.login.logout’), ) 5.5 ???UUU settings.py Django  session I‡¦^ê⥧ Python 2.6 ¥S˜ sqlite3 ê⥧Ïd·‚3ùp†¦ ^ sqlite3 " sqlite3 †¦^/©‡•;ê⥧ÏdØ•3ÑÖì!à•!^r¶!—è!• ˜¯K§êþÒŒ±m©¦^§{ü•B"é newste/settings.py ?1Xe?Uµ [quote]DATABASE_ENGINE = ’sqlite3’ DATABASE_NAME = ’./data.db’ DATABASE_USER = ’’ DATABASE_PASSWORD = ’’ DATABASE_HOST = ’’ DATABASE_PORT = ’’ 5.6 ÐÐЩ©©zzzêêêââ⥥¥ I‡Ãĉ1 syncdb ·-5¤êâ¥ЩzöŠ§•)Mïêâ¥!êâL"·-Xeµ $ ./manage.py syncdb Ñy´Ä‡Mï‡?^rJ«žµ You just installed Django’s auth system, which means you don’t have any superusers defined. Would you like to create one now? (yes/no): ·‚ÀJ yes §,M^r¶Ú—èÑ´ test ‡?^r"ù‡‡?^r3±¬^" 5.7 333 Web èèèAAAìì쥥¥ÿÿÿÁÁÁ kéÄ Django S˜ Web ÑÖì§,3\èAì¥Ñ\ http://127.0.0.1:8000/login/ "e5 ÿÁ˜e¹Ú5•" 5.8 ((( ù˜ù¥§·‚ÆS Django ¥ session ¦^§}Á †( template )/( render ),˜«• ª§¿…ÐÚ> .(model) "ù SN3Õmu¥ò¬²~^" 6 111888ùùù 6.1 ÚÚÚóóó ù˜ù·‚‡¢y˜‡{ü Wiki §•)XeõUµ 1. Œ±?Uc•¡"3•¡e•Jø˜‡?6Uܧü§Œ±?6c•¡" 2. £O•¡ƒ†:§•¡ƒ†:´ü‡Äi1Œücë3˜å§:§‚ò?\®k•¡½ö Mï#•¡" ·‚‡M Django  app 5¢yù‡ Wiki " app ´˜‡õU8ܧ§PkgC .( Model )! View Ú†( Template )§„Œ±PkgC urls.py(URL N)" app ´˜‡Õá8 ¹§§Œ±ÕáSC§•Ò´`\Œ±r§SCÙ§ Django ÑÖì¥" app (´ Django Ø% A5ƒ˜§ Django Jø éõé app (gÄõU" 10 6.2 MMMïïï wiki app 3 newtest 8¹e‰1e·-µ $ ./manage.py startapp wiki ù‡·-¬3 newtest 8¹eMï wiki 8¹§¿3 wiki 8¹eMï4‡©‡µ __init__.py: L«wiki8¹´˜‡•" models.py : ^5•˜.(Model)“è(£ãêâ¥(Úêâ•)" views.py : ^5•˜View“è(?nURLž¦View•{)" tests.py : ü«ü«º‚ÿÁ“è§^uDjango appNÁ" 6.3 ???UUU wiki/models.py Django ¥.( Model )¢S´ÏL ORM(Object Relation Mapping §é–'XN)5¶-êâ ¥.[!§±é–/ª5?nêâ".¥z‡ model ÑéAê⥥˜ÜL§ model z ‡á5éAL¥˜‡iã"ùØêâ–¯š~•B§ …\I‡¦^ØÓê⥞•Ø7? Uù “è(~Xl sqlite 3[£ PostgreSQL )" ?U wiki/models.py SNXeµ from django.db import models #Create your models here. class Wiki(models.Model): pagename = models.CharField(max_length=20, unique=True) content = models.TextField() 3ùp§ Wiki ´ model ¶i§§´ models.Model fa§§ü‡á5©O´ models.CharField Ú mod- els.TextField ¢~" pagename ^5••¡¶i§•Œ•Ý•20‡iΧ¿…ØU•E(Ï•§‡ Š••¡ƒ†:)" content ^5••¡SN" 'u.( Model )\Öµ ~http://www.djangoproject.com/documentation/model_api/~ 'uê⥠API \Öµ ~http://www.djangoproject.com/documentation/db_api/~ 6.4 SSSCCC wiki app z‡ app MïÑI‡ÃÄSC§•)?U settings.py ÚЩzêâ¥üÚ" 6.5 ???UUU settings.py 3 settings.py é~INSTALLED_APPS~§?U•µ INSTALLED_APPS = ( ’django.contrib.auth’, ’django.contrib.contenttypes’, ’django.contrib.sessions’, ’django.contrib.sites’, ’newtest.wiki’, ) ù˜Ú´5þ wiki app " 6.6 ÐÐЩ©©zzzêêêââ⥥¥ $ ./manage.py syncdb ù˜Ú´Šâ wiki/models.py 3ê⥥MïƒAL" 11 6.7 MMMïïï wiki ÄÄÄ••• ·‚¦^·-15M¶• FrontPage Ä•" $ ./manage.py shell ^ù‡·-¬?\ Python )ºì§,‰1µ >>> from newtest.wiki.models import Wiki >>> page = Wiki(pagename=’FrontPage’, content=’Welcome to Easy Wiki’) >>> page.save() >>> Wiki.objects.all() [] >>> p = Wiki.objects.all()[0] >>> p.pagename u’FrontPage’ >>> p.content u’Welcome to EasyWiki’ 3 Django ¥öŠêâ¥kü«•ªµ˜«´8ÜöŠ•ª§˜«´é–öŠ•ª"·‚3ùp¦^´ 8ÜöŠ•ª§•Ò´¦^ model.objects 5?nê⧠all() ¬ˆ£Üê⧠filter() ¬ˆ£ÎÜ^‡ P¹" 6.8 ???UUU wiki/views.py ?U wiki/views.py §SNXeµ [quote]# Create your own views here. #-*- coding: utf-8 -*- from newtest.wiki.models import Wiki from django.template import loader, Context from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response def index(request, pagename=’’): ’’’w«˜„•¡§é•¡SN‰ó?n’’’ if pagename: #XJJø •¡¶i§Ké•¡´Ä®²•3 pages = Wiki.objects.filter(pagename=pagename) if pages: #XJ•¡®•3§KN^†5w« return process(’wiki/page.html’, pages[0]) else: #XJ•¡Ø•3§K?\?6•¡ return render_to_response(’wiki/edit.html’, {’pagename’:pagename}) else: #XJvkJø•¡¶i§Kw«Ä• page = Wiki.objects.get(pagename=’FrontPage’) return process(’wiki/page.html’, page) def edit(request, pagename): ’’’w«?6•¡’’’ page = Wiki.objects.get(pagename=pagename) return render_to_response(’wiki/edit.html’, {’pagename’:pagename, ’content’:page.content}) def save(request, pagename): ’’’••¡SN¿=•#•¡§XJ•¡®•3K•#§SN§XJ•¡Ø•3K#ïù ‡•¡’’’ content = request.POST[’content’] pages = Wiki.objects.filter(pagename=pagename) 12 if pages: pages[0].content = content pages[0].save() else: page = Wiki(pagename=pagename, content=content) page.save() return HttpResponseRedirect(’/wiki/%s’ % pagename) import re r = re.compile(r’\b(([A-Z]+[a-z]+){2,})\b’) def process(template, page): ’’’?n•¡ó§¿ò†1Î=†•
’’’ t = loader.get_template(template) content = r.sub(r’\1’, page.content) content = re.sub(r’[\n\r]+’, ’
’, content) c = Context({’pagename’:page.pagename, ’content’:content}) return HttpResponse(t.render(c)) Wiki.objects é–k filter() Ú get() •{§cöˆ£˜‡(J8Ü(XJéجˆ£˜8)§öˆ£ •½é–(XJéجÑÉ~)"†1Î=†•Œ±3†¥^ filter 5¤" N^†ž¦^ wiki/edit.html Ø´ edit.html §L«·‚ò3 templates 8¹¥Mï wiki f8¹"• ØÓ app MïØÓf8¹§ù•B«©!´u‘o"\ATP wiki/models.py ¥ pagename ´ •˜§Ïd filter ()ˆ£Š˜½´1‡½0‡ƒ§•‡ pages Ø´˜8§·‚ÒŒ±^ pages [0]5– ¯·‚Ž‡é–"J«µ3 Django ¥§?Ué–ƒI‡N^§ save() •{â¬r§•ê⥠¥" 6.9 MMMïïï templates/wiki/page.html ©©©‡‡‡ kMï templates/wiki 8¹µ $ mkdir ./templates/wiki Mï templates/wiki/page.html ©‡§SNXeµ

{{ pagename }}

{{ content|safe }}


w«˜„•¡§•)•¡IKÚSN§3©•‚e•w«?6UÜ"J«µùpé content Cþ¦^ safe I\( Tag )§ùŒ±;•†/žgÄ=Â"XJØ\ù‡I\§@o3)¤•¡ƒ†: žÒ¬Ñy†Ø§< Ø´<§Ã{)¤‡ó" 6.10 MMMïïï templates/wiki/edit.html ©©©‡‡‡ Mï templates/wiki.html ©‡§SNXeµ

?6µ{{ pagename }}


6.11 ???UUU urls.py é urlpatterns §?U•µ 13 urlpatterns = patterns(’’, (r’^wiki/$’, ’newtest.wiki.views.index’), (r’^wiki/(?P\w+)/$’, ’newtest.wiki.views.index’), (r’^wiki/(?P\w+)/edit/$’, ’newtest.wiki.views.edit’), (r’^wiki/(?P\w+)/save/$’, ’newtest.wiki.views.save’), ) ùp URL ´ùOµ wiki/pagename ´w«˜‡•¡§ wiki/pagename/edit ´?6ù‡• ¡§ wiki/pagename/save ´•ù‡•¡" 6.12 333 Web èèèAAAìì쥥¥ÿÿÿÁÁÁ kéÄ Django S˜ Web ÑÖì§,3\èAì¥Ñ\ http://127.0.0.1:8000/wiki/ §\ò? \ Wiki Ä•µ http://www.woodpecker.org.cn/obp/django/django-stepbystep/newtest/doc/tut06_01.jpg :Â?6§\ò?\ FrontPage ?6•¡µ http://www.woodpecker.org.cn/obp/django/django-stepbystep/newtest/doc/tut06_02.jpg\\ ·‚\þ˜1/ TestPage 0§,•" TestPage ´ü‡Äi1Œücë3˜å§§¬£O• •¡ƒ†:"y3Ä•´ùµ http://www.woodpecker.org.cn/obp/django/django-stepbystep/newtest/doc/tut06_03.jpg\\ ·‚:Â/ TestPage 0ò?\/ TestPage 0?6•¡µ http://www.woodpecker.org.cn/obp/django/django-stepbystep/newtest/doc/tut06_04.jpg\\ ·‚rSN•: ù´#•¡ ˆ£Ä• FrontPage ¿•"ùž TestPage •¡Xeµ http://www.woodpecker.org.cn/obp/django/django-stepbystep/newtest/doc/tut06_05.jpg\\ 3ùp:Â/ FrontPage 0qò£ Wiki Ä•" 6.13 ((( 3ù˜ù¥§·‚ŠÃMï ˜‡ Wiki §Ù¥¦^ n‡ URL N!n‡ View •{Úü‡n‡ †©‡"ù‡~f¥·‚/Ы Django ¥ Model Template View ¦^" 7 django ˜˜˜‡‡‡~~~fff 3Nþ˜‡ django ¢S~f§Š•o(œ£5 µhttp://jackhf.blog.sohu.com/110535674.html¤ 7.1 ###ïï˜‡‡‡óó󧧧 ?\Ž‡MïA^8¹…\ django-admin.py startproject news ·-§N^ Django ››· -#¶• news 󧧆dÓž Django „3#Mï news ©‡Ye)¤±eo‡©óØÓ ©‡µ __init__.py µ ©‡__init__.pyŒ±•Python?ÈìL²c©‡YeSN´Pythonó§¬" 2.manage.py µ manage.py´Python ©‡§†Django·-1óädjango-admin.pyܧŒ±éïáó§?1+ n˜" 14 settings.py µ ù´Django󧘩‡§†ó§ƒ'ó§¬Úêâ¥Û˜&EÑ3settings.py¥˜" urls.py µ ©‡urls.pyKI˜URL/ŒN±9+nURL/Œ‚ª" …\·- manage.py runserver §ÒŒ±éÄ Web ÑÖì5ÿÁ#ïáó§ http://127.0.0.1:8000/0 L «c󧮲Œ±ÏLÅ 8000 à•–¯ 7.2 ###ïïשּׁ¬ 3ó§ïáЃ§e5ÒŒ±? Django A^¬"…\·- python manage.py star- tapp article §·-¬3có§e)¤˜‡¶• article ¬§8¹eØ I£ Python ¬  __init__.py ©‡§„k ü‡©‡ models.py Ú views.py " 7.3 ###ïïïêêêââ⥥¥^^^rrrÚÚÚêêêââ⥥¥ 7.4 ¢¢¢yyymodels§§§êêêââ⥥¥NNN'''XXX /Ï Django SÜé–'XNÅ›§Œ±^ Python Šó¢yéêâ¥L¥¢N?1öŠ§¢N .£ãI‡3©‡ models.py ¥˜"3c󧥧I‡kü‡ Models .§©OéA List L Ú Item L§^5•;#ª©aÚ#ª^8§z‡ Item ‘Ѭk˜‡ …5IP©Ù8á©a" e¡‹m Django Mï models.py ©‡§U쩇5º¥J«¬V\ ˜§?Xe“èµ from django.db import models # Create your models here. class List(models.Model): title = models.CharField(max_length=250,unique=True) def __str__(self): return self.title def __unicode__(self): return self.title class Meta: ordering = [’title’] import datetime class Item(models.Model): title = models.CharField(max_length=250) created_date = models.DateTimeField(default=datetime.datetime.now) completed = models.BooleanField(default=False) article_list = models.ForeignKey(List) def __str__(self): return self.title def __unicode__(self): return self.title class Meta: ordering = [’-created_date’, ’title’] =M¶• List L‚§L‚Sü‡iã©O´ Django gÄ)¤.Ì… id Ú•Œ°Ý • 250 ‡iÎ VARCHAR a.iã title §¿…3 title iãþ½Â •˜5å§5y#ª©a جkƒÓ¶¡" Item êâLéA Models “è‡E,˜ §¿Ø©Û"“èpÄkÚ \ datetime a.§^u½ÂL«©ÙMïFÏ ~created_date~ 15 i㧿…ÏL Python IO¼ê datetime.datetime.now ˆ£XÚcFÏ5˜iã%@Š"3 P¹üS ordering ˜¥§ÎÒ/-0L«UìFÏS?1ü§XJ©ÙMïFσӧK2U ì title i1SSü" 3 Django ¥§†ó§Ûƒ'˜ÑI‡3˜©‡ settings.py ¥V\")ö¦^ MySQL Š• ê⥠DATABASE_ENGINE = ’mysql’ # ’postgresql_psycopg2’, ’postgresql’, ’mysql’, ’sqlite3’ or ’oracle’. DATABASE_NAME = ’django’ # Or path to database file if using sqlite3. DATABASE_USER = ’django’ # Not used with sqlite3. DATABASE_PASSWORD = ’django’ # Not used with sqlite3. DATABASE_HOST = ’localhost’ # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = ’3306’ # Set to empty string for default. Not used with sqlite3. • ¦ Django £OmuöV\A^¬§3 settings.py ©‡ ~INSTALLED_APPS~ Ü©¥§I‡½Â Django ó§\1A^L"%@œ¹e§L¥®²V\ Django ó§$1¤ IÜ©g‘¬§·‚„I‡rfâ?ÐA^¬ news.article \\Ù¥§ÓžV\ Django g‘  django.contrib.admin A^¬ INSTALLED_APPS = ( ’django.contrib.auth’, #’django.contrib.contenttypes’, #’django.contrib.sessions’, ’django.contrib.sites’, ’news.article’, ’django.contrib.admin’, ’django.contrib.contenttypes’, ’django.contrib.sessions’, ) V\ admin ¬„ØUá=¦^ Django  admin +n.¡§I‡‹m News ó§Š8¹e  urls.py ©‡§ò /# Uncomment this for admin:0 ¡#5ºK§¦ Django é+n.¡ URL =• /(r’^admin/(.*)’, admin.site.root),0 Œ^§ù–¯ admin ¬ž Django ÒŒ±^|)Û–¯/Œ¿=•+n.¡" from django.contrib import admin admin.autodiscover() (r’^admin/(.*)’, admin.site.root), ?6 admin.py §5þ‡+né–£3 article ©‡Y¥¤ from django.contrib import admin from models import List,Item admin.site.register(List) admin.site.register(Item) ˜©‡UĤƒ§ÒŒ±3 News ó§·-J«Îe‰1 manage.py syncdb •-" Django ¬ Šâ.½ÂgĤ ORM êâ¥N󊧶- .êâ¥[!Ú SQL Î?" 16 ‘X·-‰1EÄJ«§ Django ®²Šâ·‚fâ3 models p½ÂN©‡§gÄ3ê⥠pMïÐéALÚiã"·-‰1Óž¬J«^rMï/ superuser ”âr§5º Django gÄMï Ð+n.¡é.?1+n" 3 admin +n.¡¥§w« A^¥®²½Âˆ‡ models ¬§:Âwž§K¬w« mod- els ¥•3êâ¥é–L"V\é–§êâ¥Ò¬kêâ í" 7.5 ¢¢¢yyy views §§§ééé––– ?1ùp§ Django ó§¥.®²?n¤§e¡‡‰Ò´XÛ^“è5† models ¥ ½Âiã?1p§ùÒ´ Django ¥ View Ü©"†DÚ MVC ©½ÂÑkØÓ´§ 3 Django ¥§ View õU´é•¡ž¦?1•AÚÜ6››§ •¡SNL«Kd Django  Tem- plate †5¤"·‚Œ±r Django  View n)•¢yˆ«õU Python ¼ê§ View KI É URL ˜©‡ urls.py ¥½ÂURL=u¿•A?n§ Django ž¦ƒN^ƒA View ¼ê 5¤õU§ article ¬¥ views.py ©‡“è½ÂXeµ # Create your views here. from django.shortcuts import render_to_response from news.article.models import List def news_report(request): article_listing = [] for article_list in List.objects.all(): article_dict = {} article_dict[’news_object’] = article_list article_dict[’item_count’] = article_list.item_set.count() article_dict[’items_title’] = article_list.title article_dict[’items_complete’] = article_list.item_set.filter (completed=True).count() article_dict[’percent_complete’] = int(float(article_dict[’items_complete’]) / article_dict[’item_count’] * 100) article_listing.append(article_dict) return render_to_response(’news_report.html’,{’article_listing’:article_listing}) ù´˜ã{' Python “è§4·‚ww3ùã“èp¡ Django ¼ê‰ = óŠjµ 1. List.objects.all •{ˆ£ news L¥¤kP¹‘§ Django Œ±Šâêâ¥=†¤ƒA  SQL Šé§3ê⥥‰1¿ˆ£Î(J" 2. z˜^ article ©ÙÑkitem_set á5§“Lnews#ª^8¥z˜‡ item ‘"XJI‡˜Î ^‡§•Œ±¦^item_set.filter •{5ˆ£ÎÜA½‡¦ item ‘" 3. render_to_response¼êˆ£èA약 HTML •¡§•¡• Django  Template †§KI Ыž¦•¡SN" 7.6 ¢¢¢yyywww«««††† 3 view Ü©“襧®²•½ •¡w«†•~news_report.html~"Ù¢§3 Django ó§ ¥M˜‡š~•B¯œ§e¡‡3 article 8¹SMïù‡†•¡§Äk#¶ • templates ©‡Y§,3ù‡†8¹pMï¤I~news_report.html~†©‡§†“è Xeµ£©‡‚ª7L´utf-8¤ #ªÚOL

#ªÚOL

17 {% for list_dict in article_listing %}
  • #ª©a: {{ list_dict.items_title }}
  • #ªê8: {{ list_dict.item_count }}
  • ®uÙ#ªê8: {{ list_dict.items_complete }} ({{ list_dict. percent_complete }}%)
{% endfor %} 3þ¡†“èp¡§^ IP{% for news_dict in article_listing %}±9{% endfor %}" ùIPwŠ Django †?nś̂Ñ news ¥ item ‘ÑÑ3•¡¥§3 for Ì‚Sܧ ÏLarticle_listingá5 View ¥éAêâ‘i㊿w«z‡ news ‘ Title IK± 9 news ¥ item ‘ê8"Uì~A^(§TEMPLATE_DIRSëêSN˜•µ ’./article/templates’, ùp؇#PDjangoI‡3´»•"—V\˜‡ÏÒ"e5=I‡˜–¯ article ž URL =• /ŒÒŒ±"‹m urls.py ©‡§3 admin +n=•/Œe˜1V\XeŠéµ (r’^report/$’, ’news.article.views.news_report’), 18
还剩17页未读

继续阅读

下载pdf到电脑,查找使用更方便

pdf的实际排版效果,会与网站的显示效果略有不同!!

需要 8 金币 [ 分享pdf获得金币 ] 0 人已下载

下载pdf

pdf贡献者

jim_zs

贡献于2014-10-25

下载需要 8 金币 [金币充值 ]
亲,您也可以通过 分享原创pdf 来获得金币奖励!
下载pdf