Changes between Version 3 and Version 4 of DjangoDocumentKoreanTranslation/tutorial03


Ignore:
Timestamp:
01/29/2010 11:36:33 PM (5 years ago)
Author:
sangho
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • DjangoDocumentKoreanTranslation/tutorial03

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