Code

Changes between Version 6 and Version 7 of DjangoDocumentKoreanTranslation/tutorial03


Ignore:
Timestamp:
01/29/10 21:44:23 (4 years ago)
Author:
sangho
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • DjangoDocumentKoreanTranslation/tutorial03

    v6 v7  
    1 .. _intro-tutorial03: 
    2  
    3 ===================================== 
    4 세번째 : views 작성하기 
    5 ===================================== 
    6  
    7 이 페이지는 "views"라는 public interface에 대해 중점을 두고 Web-poll 어플리케이션을 다룹니다. 
    8  
    9 개념 
    10 ========== 
    11 뷰(view)는 장고 어플리케이션에서 구체적인 기능을 수행하고, 특정한 템플릿을 가지고 있기도 한 웹페이지의 "형태"중 한가지 입니다. 예를들어, 만약 당신이 블로그 어플리케이션을 만든다면, 아래와 같은 뷰를 사용해야 할 것입니다. 
    12  
    13     * 블로그 홈페이지 -- 최근에 올라온 글 몇개를 보여줍니다. 
    14  
    15     * 글 "자세히" 페이지 -- 한 개의 글에 대한 바로 가기 페이지 
    16  
    17     * 1년 기준 문서 페이지 -- 1년 동안의 모든 글을 보여줍니다. 
    18  
    19     * 한달 기준 문서 페이지 -- 한달 동안의 모든 글을 보여줍니다. 
    20  
    21     * 하루 기준 문서 페이지 -- 하루 동안의 모든 글을 보여줍니다. 
    22  
    23     * 댓글 처리 -- 글에 대한 댓글을 작성하는 작업을 합니다. 
    24  
    25  
    26 우리의 poll 어플리케이션에서는 아래의 네가지 뷰를 쓸 것 입니다. 
    27  
    28     * Poll "문서" 페이지 -- 최근 몇개의 poll들을 보여줍니다. 
    29  
    30     * Poll "자세히" 페이지 -- poll의 제목과, 투표를 하기위한 폼을 보여줍니다. (결과는 없음) 
    31  
    32     * Poll "결과" 페이지 -- 특정한 poll의 결과를 보여줍니다. 
    33  
    34     * 투표 처리 -- 특정한 poll에 대한 특정한 선택에 대한 투표를 처리합니다. 
    35  
    36 장고에서 각각의 뷰는 간단한 파이썬 함수로 만들 수 있습니다. 
    37  
    38  
    39 URL 디자인 하기 
    40 ================ 
    41 뷰를 작성하기 위한 첫 번째 단계는 URLconf라는 파이썬 모듈을 작성해서 URL 구조를 설계하는 것입니다. 
    42 URLconf는 특정 URL을 그에 주어진 파이썬 코드로 연결시킵니다. 
    43  
    44 유저가 장고기반 페이지를 요청하면 시스템은 Python dotted 문법의 문자열을 포함한 :setting:`ROOT_URLCONF` 세팅을 불러들이고, 
    45 아래와 같은 튜플 형태인 ``urlpatterns`` 라는 모듈레벨의 변수를 찾습니다.:: 
    46  
    47     (정규표현식, 파이썬 콜백 함수, [, 부가적인 사전자료형]) 
    48  
    49 장고는 요청된 URL을 나타내는 정규표현식이 나올 때 까지 첫 번째 정규표현식부터 아래로 쭉 훑습니다. 
    50  
    51 적합한 정규표현식을 찾았다면, 장고는 :class:`~django.http.HttpRequest`를 첫번째 인자로 하는 파이썬 콜백 함수를 호출합니다. 
    52 정규표현식에 의해 "걸려진" 값들도 키워드 인자로 전달되고, 위의 사전자료형 (세번째로 받은 튜플값)에서도 인자가 전달됩니다. 
    53  
    54 :class:`~django.http.HttpRequest`에 대한 더 많은정보는 :ref:`ref-request-response`이곳에서, URLconfs에 관한 정보는 :ref:`topics-http-urls`이 곳을 참고 하세요 
    55  
    56 만약 여러분이 튜토리얼1 에서 ``django-admin.py startproject mysite`` 커맨드를 실행하셨다면 URLconf가 ``mysite/urls.py``에 기본적으로 생겼을 것이고, 
    57 :setting:`ROOT_URLCONF`세팅또한 ``setting.py``에 생겼을 것입니다.:: 
    58  
    59     ROOT_URLCONF = 'mysite.urls' 
    60  
    61 이제 예를들기위해 ``mysite/urls.py`` 를 수정해보겠습니다. 대략 아래와 같이 생겼습니다:: 
    62  
    63     from django.conf.urls.defaults import * 
    64  
    65     from django.contrib import admin 
    66     admin.autodiscover() 
    67  
    68     urlpatterns = patterns('', 
    69         (r'^polls/$', 'mysite.polls.views.index'), 
    70         (r'^polls/(?P<poll_id>\d+)/$', 'mysite.polls.views.detail'), 
    71         (r'^polls/(?P<poll_id>\d+)/results/$', 'mysite.polls.views.results'), 
    72         (r'^polls/(?P<poll_id>\d+)/vote/$', 'mysite.polls.views.vote'), 
    73         (r'^admin/', include(admin.site.urls)), 
    74     ) 
    75  
    76 This is worth a review. When somebody requests a page from your Web site -- say, 
    77 "/polls/23/", Django will load this Python module, because it's pointed to by 
    78 the :setting:`ROOT_URLCONF` setting. It finds the variable named ``urlpatterns`` 
    79 and traverses the regular expressions in order. When it finds a regular 
    80 expression that matches -- ``r'^polls/(?P<poll_id>\d+)/$'`` -- it loads the 
    81 function ``detail()`` from ``mysite/polls/views.py``. Finally, 
    82 it calls that ``detail()`` function like so:: 
    83  
    84  
    85     detail(request=<HttpRequest object>, poll_id='23') 
    86  
    87 The ``poll_id='23'`` part comes from ``(?P<poll_id>\d+)``. Using parenthesis 
    88 around a pattern "captures" the text matched by that pattern and sends it as an 
    89 argument to the view function; the ``?P<poll_id>`` defines the name that will be 
    90 used to identify the matched pattern; and ``\d+`` is a regular expression to 
    91 match a sequence of digits (i.e., a number). 
    92  
    93 Because the URL patterns are regular expressions, there really is no limit on 
    94 what you can do with them. And there's no need to add URL cruft such as ``.php`` 
    95 -- unless you have a sick sense of humor, in which case you can do something 
    96 like this:: 
    97  
    98     (r'^polls/latest\.php$', 'mysite.polls.views.index'), 
    99  
    100 But, don't do that. It's silly. 
    101  
    102 Note that these regular expressions do not search GET and POST parameters, or 
    103 the domain name. For example, in a request to ``http://www.example.com/myapp/``, 
    104 the URLconf will look for ``myapp/``. In a request to 
    105 ``http://www.example.com/myapp/?page=3``, the URLconf will look for ``myapp/``. 
    106  
    107 If you need help with regular expressions, see `Wikipedia's entry`_ and the 
    108 `Python documentation`_. Also, the O'Reilly book "Mastering Regular Expressions" 
    109 by Jeffrey Friedl is fantastic. 
    110  
    111 Finally, a performance note: these regular expressions are compiled the first 
    112 time the URLconf module is loaded. They're super fast. 
    113  
    114 .. _Wikipedia's entry: http://en.wikipedia.org/wiki/Regular_expression 
    115 .. _Python documentation: http://docs.python.org/library/re.html 
    116  
    117 Write your first view 
    118 ===================== 
    119  
    120 Well, we haven't created any views yet -- we just have the URLconf. But let's 
    121 make sure Django is following the URLconf properly. 
    122  
    123 Fire up the Django development Web server: 
    124  
    125 .. code-block:: bash 
    126  
    127     python manage.py runserver 
    128  
    129 Now go to "http://localhost:8000/polls/" on your domain in your Web browser. 
    130 You should get a pleasantly-colored error page with the following message:: 
    131  
    132     ViewDoesNotExist at /polls/ 
    133  
    134     Tried index in module mysite.polls.views. Error was: 'module' 
    135     object has no attribute 'index' 
    136  
    137 This error happened because you haven't written a function ``index()`` in the 
    138 module ``mysite/polls/views.py``. 
    139  
    140 Try "/polls/23/", "/polls/23/results/" and "/polls/23/vote/". The error 
    141 messages tell you which view Django tried (and failed to find, because you 
    142 haven't written any views yet). 
    143  
    144 Time to write the first view. Open the file ``mysite/polls/views.py`` 
    145 and put the following Python code in it:: 
    146  
    147     from django.http import HttpResponse 
    148  
    149     def index(request): 
    150         return HttpResponse("Hello, world. You're at the poll index.") 
    151  
    152 This is the simplest view possible. Go to "/polls/" in your browser, and you 
    153 should see your text. 
    154  
    155 Now lets add a few more views. These views are slightly different, because 
    156 they take an argument (which, remember, is passed in from whatever was 
    157 captured by the regular expression in the URLconf):: 
    158  
    159     def detail(request, poll_id): 
    160         return HttpResponse("You're looking at poll %s." % poll_id) 
    161  
    162     def results(request, poll_id): 
    163         return HttpResponse("You're looking at the results of poll %s." % poll_id) 
    164  
    165     def vote(request, poll_id): 
    166         return HttpResponse("You're voting on poll %s." % poll_id) 
    167  
    168 Take a look in your browser, at "/polls/34/". It'll run the `detail()` method 
    169 and display whatever ID you provide in the URL. Try "/polls/34/results/" and 
    170 "/polls/34/vote/" too -- these will display the placeholder results and voting 
    171 pages. 
    172  
    173 Write views that actually do something 
    174 ====================================== 
    175  
    176 Each view is responsible for doing one of two things: Returning an 
    177 :class:`~django.http.HttpResponse` object containing the content for the 
    178 requested page, or raising an exception such as :exc:`~django.http.Http404`. The 
    179 rest is up to you. 
    180  
    181 Your view can read records from a database, or not. It can use a template 
    182 system such as Django's -- or a third-party Python template system -- or not. 
    183 It can generate a PDF file, output XML, create a ZIP file on the fly, anything 
    184 you want, using whatever Python libraries you want. 
    185  
    186 All Django wants is that :class:`~django.http.HttpResponse`. Or an exception. 
    187  
    188 Because it's convenient, let's use Django's own database API, which we covered 
    189 in :ref:`Tutorial 1 <intro-tutorial01>`. Here's one stab at the ``index()`` 
    190 view, which displays the latest 5 poll questions in the system, separated by 
    191 commas, according to publication date:: 
    192  
    193     from mysite.polls.models import Poll 
    194     from django.http import HttpResponse 
    195  
    196     def index(request): 
    197         latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] 
    198         output = ', '.join([p.question for p in latest_poll_list]) 
    199         return HttpResponse(output) 
    200  
    201 There's a problem here, though: The page's design is hard-coded in the view. If 
    202 you want to change the way the page looks, you'll have to edit this Python code. 
    203 So let's use Django's template system to separate the design from Python:: 
    204  
    205     from django.template import Context, loader 
    206     from mysite.polls.models import Poll 
    207     from django.http import HttpResponse 
    208  
    209     def index(request): 
    210         latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] 
    211         t = loader.get_template('polls/index.html') 
    212         c = Context({ 
    213             'latest_poll_list': latest_poll_list, 
    214         }) 
    215         return HttpResponse(t.render(c)) 
    216  
    217 That code loads the template called "polls/index.html" and passes it a context. 
    218 The context is a dictionary mapping template variable names to Python objects. 
    219  
    220 Reload the page. Now you'll see an error:: 
    221  
    222     TemplateDoesNotExist at /polls/ 
    223     polls/index.html 
    224  
    225 Ah. There's no template yet. First, create a directory, somewhere on your 
    226 filesystem, whose contents Django can access. (Django runs as whatever user your 
    227 server runs.) Don't put them under your document root, though. You probably 
    228 shouldn't make them public, just for security's sake. 
    229 Then edit :setting:`TEMPLATE_DIRS` in your ``settings.py`` to tell Django where 
    230 it can find templates -- just as you did in the "Customize the admin look and 
    231 feel" section of Tutorial 2. 
    232  
    233 When you've done that, create a directory ``polls`` in your template directory. 
    234 Within that, create a file called ``index.html``. Note that our 
    235 ``loader.get_template('polls/index.html')`` code from above maps to 
    236 "[template_directory]/polls/index.html" on the filesystem. 
    237  
    238 Put the following code in that template: 
    239  
    240 .. code-block:: html+django 
    241  
    242     {% if latest_poll_list %} 
    243         <ul> 
    244         {% for poll in latest_poll_list %} 
    245             <li>{{ poll.question }}</li> 
    246         {% endfor %} 
    247         </ul> 
    248     {% else %} 
    249         <p>No polls are available.</p> 
    250     {% endif %} 
    251  
    252 Load the page in your Web browser, and you should see a bulleted-list 
    253 containing the "What's up" poll from Tutorial 1. 
    254  
    255 A shortcut: render_to_response() 
    256 -------------------------------- 
    257  
    258 It's a very common idiom to load a template, fill a context and return an 
    259 :class:`~django.http.HttpResponse` object with the result of the rendered 
    260 template. Django provides a shortcut. Here's the full ``index()`` view, 
    261 rewritten:: 
    262  
    263     from django.shortcuts import render_to_response 
    264     from mysite.polls.models import Poll 
    265  
    266     def index(request): 
    267         latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] 
    268         return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list}) 
    269  
    270 Note that once we've done this in all these views, we no longer need to import 
    271 :mod:`~django.template.loader`, :class:`~django.template.Context` and 
    272 :class:`~django.http.HttpResponse`. 
    273  
    274 The :func:`~django.shortcuts.render_to_response` function takes a template name 
    275 as its first argument and a dictionary as its optional second argument. It 
    276 returns an :class:`~django.http.HttpResponse` object of the given template 
    277 rendered with the given context. 
    278  
    279 Raising 404 
    280 =========== 
    281  
    282 Now, let's tackle the poll detail view -- the page that displays the question 
    283 for a given poll. Here's the view:: 
    284  
    285     from django.http import Http404 
    286     # ... 
    287     def detail(request, poll_id): 
    288         try: 
    289             p = Poll.objects.get(pk=poll_id) 
    290         except Poll.DoesNotExist: 
    291             raise Http404 
    292         return render_to_response('polls/detail.html', {'poll': p}) 
    293  
    294 The new concept here: The view raises the :exc:`~django.http.Http404` exception 
    295 if a poll with the requested ID doesn't exist. 
    296  
    297 We'll discuss what you could put in that ``polls/detail.html`` template a bit 
    298 later, but if you'd like to quickly get the above example working, just:: 
    299  
    300     {{ poll }} 
    301  
    302 will get you started for now. 
    303  
    304 A shortcut: get_object_or_404() 
    305 ------------------------------- 
    306  
    307 It's a very common idiom to use :meth:`~django.db.models.QuerySet.get` and raise 
    308 :exc:`~django.http.Http404` if the object doesn't exist. Django provides a 
    309 shortcut. Here's the ``detail()`` view, rewritten:: 
    310  
    311     from django.shortcuts import render_to_response, get_object_or_404 
    312     # ... 
    313     def detail(request, poll_id): 
    314         p = get_object_or_404(Poll, pk=poll_id) 
    315         return render_to_response('polls/detail.html', {'poll': p}) 
    316  
    317 The :func:`~django.shortcuts.get_object_or_404` function takes a Django model 
    318 as its first argument and an arbitrary number of keyword arguments, which it 
    319 passes to the module's :meth:`~django.db.models.QuerySet.get` function. It 
    320 raises :exc:`~django.http.Http404` if the object doesn't exist. 
    321  
    322 .. admonition:: Philosophy 
    323  
    324     Why do we use a helper function :func:`~django.shortcuts.get_object_or_404` 
    325     instead of automatically catching the 
    326     :exc:`~django.core.exceptions.ObjectDoesNotExist` exceptions at a higher 
    327     level, or having the model API raise :exc:`~django.http.Http404` instead of 
    328     :exc:`~django.core.exceptions.ObjectDoesNotExist`? 
    329  
    330     Because that would couple the model layer to the view layer. One of the 
    331     foremost design goals of Django is to maintain loose coupling. 
    332  
    333 There's also a :func:`~django.shortcuts.get_list_or_404` function, which works 
    334 just as :func:`~django.shortcuts.get_object_or_404` -- except using 
    335 :meth:`~django.db.models.QuerySet.filter` instead of 
    336 :meth:`~django.db.models.QuerySet.get`. It raises :exc:`~django.http.Http404` if 
    337 the list is empty. 
    338  
    339 Write a 404 (page not found) view 
    340 ================================= 
    341  
    342 When you raise :exc:`~django.http.Http404` from within a view, Django will load 
    343 a special view devoted to handling 404 errors. It finds it by looking for the 
    344 variable ``handler404``, which is a string in Python dotted syntax -- the same 
    345 format the normal URLconf callbacks use. A 404 view itself has nothing special: 
    346 It's just a normal view. 
    347  
    348 You normally won't have to bother with writing 404 views. By default, URLconfs 
    349 have the following line up top:: 
    350  
    351     from django.conf.urls.defaults import * 
    352  
    353 That takes care of setting ``handler404`` in the current module. As you can see 
    354 in ``django/conf/urls/defaults.py``, ``handler404`` is set to 
    355 :func:`django.views.defaults.page_not_found` by default. 
    356  
    357 Four more things to note about 404 views: 
    358  
    359     * If :setting:`DEBUG` is set to ``True`` (in your settings module) then your 
    360       404 view will never be used (and thus the ``404.html`` template will never 
    361       be rendered) because the traceback will be displayed instead. 
    362  
    363     * The 404 view is also called if Django doesn't find a match after checking 
    364       every regular expression in the URLconf. 
    365  
    366     * If you don't define your own 404 view -- and simply use the default, which 
    367       is recommended -- you still have one obligation: To create a ``404.html`` 
    368       template in the root of your template directory. The default 404 view will 
    369       use that template for all 404 errors. 
    370  
    371     * If :setting:`DEBUG` is set to ``False`` (in your settings module) and if 
    372       you didn't create a ``404.html`` file, an ``Http500`` is raised instead. 
    373       So remember to create a ``404.html``. 
    374  
    375 Write a 500 (server error) view 
    376 =============================== 
    377  
    378 Similarly, URLconfs may define a ``handler500``, which points to a view to call 
    379 in case of server errors. Server errors happen when you have runtime errors in 
    380 view code. 
    381  
    382 Use the template system 
    383 ======================= 
    384  
    385 Back to the ``detail()`` view for our poll application. Given the context 
    386 variable ``poll``, here's what the "polls/detail.html" template might look 
    387 like: 
    388  
    389 .. code-block:: html+django 
    390  
    391     <h1>{{ poll.question }}</h1> 
    392     <ul> 
    393     {% for choice in poll.choice_set.all %} 
    394         <li>{{ choice.choice }}</li> 
    395     {% endfor %} 
    396     </ul> 
    397  
    398 The template system uses dot-lookup syntax to access variable attributes. In 
    399 the example of ``{{ poll.question }}``, first Django does a dictionary lookup 
    400 on the object ``poll``. Failing that, it tries attribute lookup -- which works, 
    401 in this case. If attribute lookup had failed, it would've tried calling the 
    402 method ``question()`` on the poll object. 
    403  
    404 Method-calling happens in the ``{% for %}`` loop: ``poll.choice_set.all`` is 
    405 interpreted as the Python code ``poll.choice_set.all()``, which returns an 
    406 iterable of Choice objects and is suitable for use in the ``{% for %}`` tag. 
    407  
    408 See the :ref:`template guide <topics-templates>` for more about templates. 
    409  
    410 Simplifying the URLconfs 
    411 ======================== 
    412  
    413 Take some time to play around with the views and template system. As you edit 
    414 the URLconf, you may notice there's a fair bit of redundancy in it:: 
    415  
    416     urlpatterns = patterns('', 
    417         (r'^polls/$', 'mysite.polls.views.index'), 
    418         (r'^polls/(?P<poll_id>\d+)/$', 'mysite.polls.views.detail'), 
    419         (r'^polls/(?P<poll_id>\d+)/results/$', 'mysite.polls.views.results'), 
    420         (r'^polls/(?P<poll_id>\d+)/vote/$', 'mysite.polls.views.vote'), 
    421     ) 
    422  
    423 Namely, ``mysite.polls.views`` is in every callback. 
    424  
    425 Because this is a common case, the URLconf framework provides a shortcut for 
    426 common prefixes. You can factor out the common prefixes and add them as the 
    427 first argument to :func:`~django.conf.urls.defaults.patterns`, like so:: 
    428  
    429     urlpatterns = patterns('mysite.polls.views', 
    430         (r'^polls/$', 'index'), 
    431         (r'^polls/(?P<poll_id>\d+)/$', 'detail'), 
    432         (r'^polls/(?P<poll_id>\d+)/results/$', 'results'), 
    433         (r'^polls/(?P<poll_id>\d+)/vote/$', 'vote'), 
    434     ) 
    435  
    436 This is functionally identical to the previous formatting. It's just a bit 
    437 tidier. 
    438  
    439 Decoupling the URLconfs 
    440 ======================= 
    441  
    442 While we're at it, we should take the time to decouple our poll-app URLs from 
    443 our Django project configuration. Django apps are meant to be pluggable -- that 
    444 is, each particular app should be transferable to another Django installation 
    445 with minimal fuss. 
    446  
    447 Our poll app is pretty decoupled at this point, thanks to the strict directory 
    448 structure that ``python manage.py startapp`` created, but one part of it is 
    449 coupled to the Django settings: The URLconf. 
    450  
    451 We've been editing the URLs in ``mysite/urls.py``, but the URL design of an 
    452 app is specific to the app, not to the Django installation -- so let's move the 
    453 URLs within the app directory. 
    454  
    455 Copy the file ``mysite/urls.py`` to ``mysite/polls/urls.py``. Then, change 
    456 ``mysite/urls.py`` to remove the poll-specific URLs and insert an 
    457 :func:`~django.conf.urls.defaults.include`:: 
    458  
    459     # ... 
    460     urlpatterns = patterns('', 
    461         (r'^polls/', include('mysite.polls.urls')), 
    462         # ... 
    463  
    464 :func:`~django.conf.urls.defaults.include`, simply, references another URLconf. 
    465 Note that the regular expression doesn't have a ``$`` (end-of-string match 
    466 character) but has the trailing slash. Whenever Django encounters 
    467 :func:`~django.conf.urls.defaults.include`, it chops off whatever part of the 
    468 URL matched up to that point and sends the remaining string to the included 
    469 URLconf for further processing. 
    470  
    471 Here's what happens if a user goes to "/polls/34/" in this system: 
    472  
    473     * Django will find the match at ``'^polls/'`` 
    474  
    475     * Then, Django will strip off the matching text (``"polls/"``) and send the 
    476       remaining text -- ``"34/"`` -- to the 'mysite.polls.urls' URLconf for 
    477       further processing. 
    478  
    479 Now that we've decoupled that, we need to decouple the 'mysite.polls.urls' 
    480 URLconf by removing the leading "polls/" from each line, and removing the 
    481 lines registering the admin site:: 
    482  
    483     urlpatterns = patterns('mysite.polls.views', 
    484         (r'^$', 'index'), 
    485         (r'^(?P<poll_id>\d+)/$', 'detail'), 
    486         (r'^(?P<poll_id>\d+)/results/$', 'results'), 
    487         (r'^(?P<poll_id>\d+)/vote/$', 'vote'), 
    488     ) 
    489  
    490 The idea behind :func:`~django.conf.urls.defaults.include` and URLconf 
    491 decoupling is to make it easy to plug-and-play URLs. Now that polls are in their 
    492 own URLconf, they can be placed under "/polls/", or under "/fun_polls/", or 
    493 under "/content/polls/", or any other URL root, and the app will still work. 
    494  
    495 All the poll app cares about is its relative URLs, not its absolute URLs. 
    496  
    497 When you're comfortable with writing views, read :ref:`part 4 of this tutorial 
    498 <intro-tutorial04>` to learn about simple form processing and generic views. 
     1