From a927c51f766206ec7aaeb7403b36a45d214d4051 Mon Sep 17 00:00:00 2001 From: raccoonyy Date: Sat, 14 Jul 2012 13:17:31 +0900 Subject: [PATCH 001/128] Update master --- index.txt | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/index.txt b/index.txt index a5d2e13..5b34d02 100644 --- a/index.txt +++ b/index.txt @@ -1,21 +1,20 @@ - .. _index: ==================== -Django documentation +Django 문서(한국어판) ==================== -.. rubric:: Everything you need to know about Django (and then some). +.. rubric:: 장고에 관해 알아야 할 모든 것(and then some). -Getting help +도움말 ============ -Having trouble? We'd like to help! +문제가 있나요? 도와드리고 싶어요! -* Try the :doc:`FAQ ` -- it's got answers to many common questions. +* :doc:`FAQ ` 문서를 참고하세요 -- 가장 흔한 질문에 대한 답변들입니다. -* Looking for specific information? Try the :ref:`genindex`, :ref:`modindex` or - the :doc:`detailed table of contents `. +* 특정 주제를 찾으신다면, 다음 문서를 둘러보세요. :ref:`genindex`, :ref:`modindex`, + :doc:`detailed table of contents `. * Search for information in the `archives of the django-users mailing list`_, or `post a question`_. From 7e5a15e3bc3d1fcb6416bbc38cd7faa6ba9c8ae1 Mon Sep 17 00:00:00 2001 From: Prographer Date: Thu, 2 Aug 2012 11:35:24 +0900 Subject: [PATCH 002/128] Update intro/tutorial01.txt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 앞부분 일부 번역하여 테스트로 올려 봅니다 --- intro/tutorial01.txt | 68 +++++++++++++++++++------------------------- 1 file changed, 30 insertions(+), 38 deletions(-) diff --git a/intro/tutorial01.txt b/intro/tutorial01.txt index d375640..5402977 100644 --- a/intro/tutorial01.txt +++ b/intro/tutorial01.txt @@ -1,65 +1,57 @@ ===================================== -Writing your first Django app, part 1 +첫번째 장고 앱 만들기! part1 ===================================== -Let's learn by example. +예제로 배워봅시다. -Throughout this tutorial, we'll walk you through the creation of a basic -poll application. +이 자습서를 통하여, 우리는 기초적인 설문조사 애플리케이션을 만들어 나갈 것입니다. -It'll consist of two parts: +이 애플리케이션은 두 부분으로 구성되어집니다. -* A public site that lets people view polls and vote in them. -* An admin site that lets you add, change and delete polls. +* 공개된 사이트는 사람들이 설문조사를 볼 수 있으며 설문조사에 투표 할 수 있는 곳 입니다. +* 어드민 사이트는 당신(관리자)이 설문조사에 대하여 추가, 수정, 삭제를 할 수 있는 곳 입니다. -We'll assume you have :doc:`Django installed ` already. You can -tell Django is installed by running the Python interactive interpreter and -typing ``import django``. If that command runs successfully, with no errors, -Django is installed. +우리는 이미 :doc:`Django 설치를 ` 완료 하였다고 가정합니다. 당신은 파이썬 인터프리터를 실행하여 ``import django``를 입력해 봄으로써 Django가 설치 되어 있는지 확인 할 수 있습니다. 만약 에러없이 실행된다면, Django 설치가 완료된 것입니다. -.. admonition:: Where to get help: +.. admonition:: 도움말은 어디서 얻을 수 있나요?: - If you're having trouble going through this tutorial, please post a message - to `django-users`__ or drop by `#django on irc.freenode.net`__ to chat - with other Django users who might be able to help. + 만약 당신이 이 자습서를 따라하는 도중 문제가 발생 할 경우 + `django-users`__ 로 메시지를 보내 주시거나 또는 `#django on irc.freenode.net`__ 에서 + 당신에게 도움을 줄 다른 Django 사용자와 채팅을 할 수 있습니다. __ http://groups.google.com/group/django-users __ irc://irc.freenode.net/django -Creating a project +프로젝트 만들기 ================== -If this is your first time using Django, you'll have to take care of some -initial setup. Namely, you'll need to auto-generate some code that establishes a -Django :term:`project` -- a collection of settings for an instance of Django, -including database configuration, Django-specific options and -application-specific settings. +만약 당신이 지금 처음으로 Django를 사용 하는 것이라면, 당신은 몇가치 초기 설정에 신경을 써야 합니다. 즉, 당신은 Django :term:`project` 를 구축하는데 몇가지 자동 생성되는 코드를 필요로 합니다 -- Django의 인스턴스를 위한 세팅들(데이터베이스 설정을 포함), +Django의 특별한 옵션과 애플리캐이션의 특별한 설정들. -From the command line, ``cd`` into a directory where you'd like to store your -code, then run the following command: +명령행에서 , ``cd`` 디렉토리 (코드가 생성될 디렉토리) 그리고 다음 명령어 실행: .. code-block:: bash django-admin.py startproject mysite -This will create a ``mysite`` directory in your current directory. +이것은 현재 디렉토리에 ``mysite`` 라는 디렉토리를 생성합니다 . -.. admonition:: Script name may differ in distribution packages +.. admonition:: 스크립트의 이름은 배포 패키지에 따라 다를 수 있습니다 - If you installed Django using a Linux distribution's package manager - (e.g. apt-get or yum) ``django-admin.py`` may have been renamed to - ``django-admin``. You may continue through this documentation by omitting - ``.py`` from each command. + 만약 당신이 리눅스 배포판 패키지 관리자를 이용하여 Django를 설치 하였다면 + (e.g. apt-get or yum) ``django-admin.py`` 파일의 이름을 + ``django-admin``로 변경 되었을 수도 있습니다. 당신은 이 문서에서 계속적으로 각 명령에 + ``.py`` 을 생략하여 사용 할 수 있습니다. -.. admonition:: Mac OS X permissions +.. admonition:: Mac OS X 권한 - If you're using Mac OS X, you may see the message "permission denied" when - you try to run ``django-admin.py startproject``. This is because, on - Unix-based systems like OS X, a file must be marked as "executable" before it - can be run as a program. To do this, open Terminal.app and navigate (using - the ``cd`` command) to the directory where :doc:`django-admin.py - ` is installed, then run the command - ``sudo chmod +x django-admin.py``. + 만약 당신이 Mac OS X를 사용 한다면, 당신은 ``django-admin.py startproject``를 실행 할 때 + "permission denied" 메시지를 볼 수 있을 것입니다.. 이것은 + OS X와 같은 유닉스 기반 시스템은, 프로그램을 실행하기 전에 해당 파일에 "executable(실행)" + 표시를 해줘야 하기 때문입니다. 실생 표시를 하기 위해서는, 터미널 앱을 열고 + :doc:`django-admin.py` 가 설치되어 있는 디렉토리로 이동합니다. (``cd``명령을 사용) + 그리고 + ``sudo chmod +x django-admin.py`` 명령어를 실행합니다. .. note:: @@ -724,4 +716,4 @@ full details on the database API, see our :doc:`Database API reference `. When you're comfortable with the API, read :doc:`part 2 of this tutorial -` to get Django's automatic admin working. +` to get Django's automatic admin working. \ No newline at end of file From c265268c5493da79e5adb9eb50487fa896b9e4d6 Mon Sep 17 00:00:00 2001 From: shchoi Date: Sun, 5 Aug 2012 02:18:48 +0900 Subject: [PATCH 003/128] 52 segments is tranlated52 segments is tranlated52 segments is tranlated52 segments is tranlated52 segments is tranlated --- intro/tutorial02.txt | 84 ++++++++++++++++++++------------------------ 1 file changed, 39 insertions(+), 45 deletions(-) diff --git a/intro/tutorial02.txt b/intro/tutorial02.txt index ee9e3d0..c4ae67e 100644 --- a/intro/tutorial02.txt +++ b/intro/tutorial02.txt @@ -1,42 +1,39 @@ ===================================== -Writing your first Django app, part 2 +ù° ! part 2 ===================================== -This tutorial begins where :doc:`Tutorial 1 ` left off. We're -continuing the Web-poll application and will focus on Django's -automatically-generated admin site. + ڽ :doc:`Tutorial 1 ` ̾ ӵ˴ϴ. ռ ø̼ǰ Բ ڵ Ǵ Ʈ ˾ƺ ϰڽϴ. -.. admonition:: Philosophy +.. admonition:: ö - Generating admin sites for your staff or clients to add, change and delete - content is tedious work that doesn't require much creativity. For that - reason, Django entirely automates creation of admin interfaces for models. + ڳ ߰, , ִ Ʈ ϴ + ״ â ۾ Դϴ. ̷ ۾ + ؼ ̽ ڵȭ Ͽϴٴϴ. - Django was written in a newsroom environment, with a very clear separation - between "content publishers" and the "public" site. Site managers use the - system to add news stories, events, sports scores, etc., and that content is - displayed on the public site. Django solves the problem of creating a - unified interface for site administrators to edit content. + غϴ ȯ , + " " "" Ʈ Ϻ иϿ. Ʈ ڵ + ο 丮 ̺Ʈ, ߰ϱ ý ̿ϸ, + ̷ Ʈ ˴ϴ. Ʈ ڵ ִ + ̽ μ ذմϴ. - The admin isn't intended to be used by site visitors. It's for site - managers. + Ʈ Ʈ 湮ڸ ƴմϴ. ̴ + ڵ Դϴ. -Activate the admin site + Ʈ Ȱȭ ϱ ======================= -The Django admin site is not activated by default -- it's an opt-in thing. To -activate the admin site for your installation, do these three things: + Ʈ Ʈ Ȱȭ ʽϴ. -- û Դϴ. Ʈ Ȱȭ Ű ۾ ʿմϴ: -* Uncomment ``"django.contrib.admin"`` in the :setting:`INSTALLED_APPS` setting. +* :setting:`INSTALLED_APPS` ִ ``"django.contrib.admin"`` ּ ϼ. -* Run ``python manage.py syncdb``. Since you have added a new application - to :setting:`INSTALLED_APPS`, the database tables need to be updated. +* ``python manage.py syncdb`` ɾ ϼ. :setting:`INSTALLED_APPS` + ο ø̼ ġϿ ͺ̽ ̺ Ʈ ؾ մϴ. -* Edit your ``mysite/urls.py`` file and uncomment the lines that reference - the admin -- there are three lines in total to uncomment. This file is a - URLconf; we'll dig into URLconfs in the next tutorial. For now, all you - need to know is that it maps URL roots to applications. In the end, you - should have a ``urls.py`` file that looks like this: +* ``mysite/urls.py`` Ʈ õ ּ + ϼ -- ּ ؾ մϴ. + URL (URLconf) ̸ ڽ ڼ ˾ƺڽϴ. ˾ƾ κ + URL roots ø̼ǿ Ű Դϴ. + Ʒ ``urls.py`` ȮϽ ֽϴ: .. parsed-literal:: @@ -58,48 +55,45 @@ activate the admin site for your installation, do these three things: **url(r'^admin/', include(admin.site.urls)),** ) - (The bold lines are the ones that needed to be uncommented.) + ( ǥõ ּ ŵ Դϴ.) -Start the development server + ϱ ============================ -Let's start the development server and explore the admin site. + Ű Ʈ Ž ϰڽϴ. -Recall from Tutorial 1 that you start the development server like so: +ù ° ڽ Ͽ Ʒ : .. code-block:: bash python manage.py runserver -Now, open a Web browser and go to "/admin/" on your local domain -- e.g., -http://127.0.0.1:8000/admin/. You should see the admin's login screen: + ϰ "/admin/" ̵ϼ -- : +http://127.0.0.1:8000/admin/. Ʈ α ȭ Դϴ: .. image:: _images/admin01.png - :alt: Django admin login screen + :alt: Ʈ α ȭ -.. admonition:: Doesn't match what you see? +.. admonition:: п ̴ ٸ? - If at this point, instead of the above login page, you get an error - page reporting something like:: + ̴ α ſ Ʒ + error page reporting δٸ:: ImportError at /admin/ cannot import name patterns ... - then you're probably using a version of Django that doesn't match this - tutorial version. You'll want to either switch to the older tutorial or the - newer Django version. + Ͻô ڽ + ֽϴ. Ͻô ´ ڽ ϰų, + ο Ͻñ ٶϴ. -Enter the admin site + Ʈ  ==================== -Now, try logging in. (You created a superuser account in the first part of this -tutorial, remember? If you didn't create one or forgot the password you can -:ref:`create another one `.) You should see -the Django admin index page: +, α . (ù° ڽ ְ Ͻó? ʾҰų, йȣ ﳪ ʴ´ٸ :ref:`ٸ `.) Ƹ Ʈ ʱ Ȯ Դϴ: .. image:: _images/admin02t.png - :alt: Django admin index page + :alt: Ʈ ʱ You should see a few types of editable content, including groups, users and sites. These are core features Django ships with by default. From 1c21b0ac3bc35dffebe44d88d8d9f41494d82edf Mon Sep 17 00:00:00 2001 From: shchoi Date: Sun, 5 Aug 2012 02:18:48 +0900 Subject: [PATCH 004/128] 52 segments is tranlated --- intro/tutorial02.txt | 84 ++++++++++++++++++++------------------------ 1 file changed, 39 insertions(+), 45 deletions(-) diff --git a/intro/tutorial02.txt b/intro/tutorial02.txt index ee9e3d0..c4ae67e 100644 --- a/intro/tutorial02.txt +++ b/intro/tutorial02.txt @@ -1,42 +1,39 @@ ===================================== -Writing your first Django app, part 2 +ù° ! part 2 ===================================== -This tutorial begins where :doc:`Tutorial 1 ` left off. We're -continuing the Web-poll application and will focus on Django's -automatically-generated admin site. + ڽ :doc:`Tutorial 1 ` ̾ ӵ˴ϴ. ռ ø̼ǰ Բ ڵ Ǵ Ʈ ˾ƺ ϰڽϴ. -.. admonition:: Philosophy +.. admonition:: ö - Generating admin sites for your staff or clients to add, change and delete - content is tedious work that doesn't require much creativity. For that - reason, Django entirely automates creation of admin interfaces for models. + ڳ ߰, , ִ Ʈ ϴ + ״ â ۾ Դϴ. ̷ ۾ + ؼ ̽ ڵȭ Ͽϴٴϴ. - Django was written in a newsroom environment, with a very clear separation - between "content publishers" and the "public" site. Site managers use the - system to add news stories, events, sports scores, etc., and that content is - displayed on the public site. Django solves the problem of creating a - unified interface for site administrators to edit content. + غϴ ȯ , + " " "" Ʈ Ϻ иϿ. Ʈ ڵ + ο 丮 ̺Ʈ, ߰ϱ ý ̿ϸ, + ̷ Ʈ ˴ϴ. Ʈ ڵ ִ + ̽ μ ذմϴ. - The admin isn't intended to be used by site visitors. It's for site - managers. + Ʈ Ʈ 湮ڸ ƴմϴ. ̴ + ڵ Դϴ. -Activate the admin site + Ʈ Ȱȭ ϱ ======================= -The Django admin site is not activated by default -- it's an opt-in thing. To -activate the admin site for your installation, do these three things: + Ʈ Ʈ Ȱȭ ʽϴ. -- û Դϴ. Ʈ Ȱȭ Ű ۾ ʿմϴ: -* Uncomment ``"django.contrib.admin"`` in the :setting:`INSTALLED_APPS` setting. +* :setting:`INSTALLED_APPS` ִ ``"django.contrib.admin"`` ּ ϼ. -* Run ``python manage.py syncdb``. Since you have added a new application - to :setting:`INSTALLED_APPS`, the database tables need to be updated. +* ``python manage.py syncdb`` ɾ ϼ. :setting:`INSTALLED_APPS` + ο ø̼ ġϿ ͺ̽ ̺ Ʈ ؾ մϴ. -* Edit your ``mysite/urls.py`` file and uncomment the lines that reference - the admin -- there are three lines in total to uncomment. This file is a - URLconf; we'll dig into URLconfs in the next tutorial. For now, all you - need to know is that it maps URL roots to applications. In the end, you - should have a ``urls.py`` file that looks like this: +* ``mysite/urls.py`` Ʈ õ ּ + ϼ -- ּ ؾ մϴ. + URL (URLconf) ̸ ڽ ڼ ˾ƺڽϴ. ˾ƾ κ + URL roots ø̼ǿ Ű Դϴ. + Ʒ ``urls.py`` ȮϽ ֽϴ: .. parsed-literal:: @@ -58,48 +55,45 @@ activate the admin site for your installation, do these three things: **url(r'^admin/', include(admin.site.urls)),** ) - (The bold lines are the ones that needed to be uncommented.) + ( ǥõ ּ ŵ Դϴ.) -Start the development server + ϱ ============================ -Let's start the development server and explore the admin site. + Ű Ʈ Ž ϰڽϴ. -Recall from Tutorial 1 that you start the development server like so: +ù ° ڽ Ͽ Ʒ : .. code-block:: bash python manage.py runserver -Now, open a Web browser and go to "/admin/" on your local domain -- e.g., -http://127.0.0.1:8000/admin/. You should see the admin's login screen: + ϰ "/admin/" ̵ϼ -- : +http://127.0.0.1:8000/admin/. Ʈ α ȭ Դϴ: .. image:: _images/admin01.png - :alt: Django admin login screen + :alt: Ʈ α ȭ -.. admonition:: Doesn't match what you see? +.. admonition:: п ̴ ٸ? - If at this point, instead of the above login page, you get an error - page reporting something like:: + ̴ α ſ Ʒ + error page reporting δٸ:: ImportError at /admin/ cannot import name patterns ... - then you're probably using a version of Django that doesn't match this - tutorial version. You'll want to either switch to the older tutorial or the - newer Django version. + Ͻô ڽ + ֽϴ. Ͻô ´ ڽ ϰų, + ο Ͻñ ٶϴ. -Enter the admin site + Ʈ  ==================== -Now, try logging in. (You created a superuser account in the first part of this -tutorial, remember? If you didn't create one or forgot the password you can -:ref:`create another one `.) You should see -the Django admin index page: +, α . (ù° ڽ ְ Ͻó? ʾҰų, йȣ ﳪ ʴ´ٸ :ref:`ٸ `.) Ƹ Ʈ ʱ Ȯ Դϴ: .. image:: _images/admin02t.png - :alt: Django admin index page + :alt: Ʈ ʱ You should see a few types of editable content, including groups, users and sites. These are core features Django ships with by default. From 5a9e00034a97441c284eedfd1d0ba354e008a3ab Mon Sep 17 00:00:00 2001 From: shchoi Date: Sun, 5 Aug 2012 02:42:57 +0900 Subject: [PATCH 005/128] character set is changed to UTF-8 --- intro/tutorial02.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/intro/tutorial02.txt b/intro/tutorial02.txt index c4ae67e..95e6c32 100644 --- a/intro/tutorial02.txt +++ b/intro/tutorial02.txt @@ -14,7 +14,7 @@ " " "" Ʈ Ϻ иϿ. Ʈ ڵ ο 丮 ̺Ʈ, ߰ϱ ý ̿ϸ, ̷ Ʈ ˴ϴ. Ʈ ڵ ִ - ̽ μ ذմϴ. + ̽ μ ذմϴٴ. Ʈ Ʈ 湮ڸ ƴմϴ. ̴ ڵ Դϴ. From dee311920bbe9b53f3ef87e09f296c87d9376437 Mon Sep 17 00:00:00 2001 From: shchoi Date: Sun, 5 Aug 2012 02:52:07 +0900 Subject: [PATCH 006/128] Character-set is changed to UTF-8 --- intro/tutorial02.txt | 78 ++++++++++++++++++++++---------------------- 1 file changed, 39 insertions(+), 39 deletions(-) diff --git a/intro/tutorial02.txt b/intro/tutorial02.txt index 95e6c32..69122f3 100644 --- a/intro/tutorial02.txt +++ b/intro/tutorial02.txt @@ -1,39 +1,39 @@ ===================================== -ù° ! part 2 +첫번째 장고 앱 만들기! part 2 ===================================== - ڽ :doc:`Tutorial 1 ` ̾ ӵ˴ϴ. ռ ø̼ǰ Բ ڵ Ǵ Ʈ ˾ƺ ϰڽϴ. +본 자습서는 :doc:`Tutorial 1 ` 에 이어 계속됩니다. 앞서 개발한 설문조사 애플리케이션과 함께 장고에서 자동으로 생성되는 관리자 사이트에 대해 알아보도록 하겠습니다. -.. admonition:: ö +.. admonition:: 철학 - ڳ ߰, , ִ Ʈ ϴ - ״ â ۾ Դϴ. ̷ ۾ - ؼ ̽ ڵȭ Ͽϴٴϴ. + 관리자나 고객들이 컨텐츠를 추가, 변경, 삭제할 수 있는 관리자 사이트를 생성하는 것은 + 그다지 창조적이지 않은 지루한 작업 입니다. 이러한 작업을 + 위해서 장고는 모델을 위한 관리자 인터페이스 생성을 완전히 자동화 하였습니다니다. - غϴ ȯ , - " " "" Ʈ Ϻ иϿ. Ʈ ڵ - ο 丮 ̺Ʈ, ߰ϱ ý ̿ϸ, - ̷ Ʈ ˴ϴ. Ʈ ڵ ִ - ̽ μ ذմϴٴ. + 장고는 뉴스를 준비하는 환경을 위해 만들어졌으며, + "컨텐츠 발행인"과 "공개" 사이트를 완벽히 분리하였습니. 사이트 관리자들은 + 새로운 스토리나 이벤트, 스포츠 점수 결과 등을 추가하기 위해 시스템을 이용하며, + 이런 컨텐츠들은 공개 사이트에 노출됩니다. 장고는 사이트 관리자들이 컨텐츠를 수정할 수 있는 + 통합 인터페이스를 제공함으로서 문제를 해결합니다다. - Ʈ Ʈ 湮ڸ ƴմϴ. ̴ - ڵ Դϴ. + 관리자 사이트는 사이트 방문자를 위한 것이 아닙니다. 이는 + 관리자들을 위한 것 입니다. - Ʈ Ȱȭ ϱ +관리자 사이트 활성화 하기 ======================= - Ʈ Ʈ Ȱȭ ʽϴ. -- û Դϴ. Ʈ Ȱȭ Ű ۾ ʿմϴ: +관리자 사이트는 디폴트로 활성화 되지 않습니다. -- 선택사항 입니다. 관리자 사이트를 활성화 시키기 위해 다음 세 가지의 작업이 필요합니다: -* :setting:`INSTALLED_APPS` ִ ``"django.contrib.admin"`` ּ ϼ. +* :setting:`INSTALLED_APPS` 설정에 있는 ``"django.contrib.admin"`` 의 주석을 제거하세요. -* ``python manage.py syncdb`` ɾ ϼ. :setting:`INSTALLED_APPS` - ο ø̼ ġϿ ͺ̽ ̺ Ʈ ؾ մϴ. +* ``python manage.py syncdb`` 명령어를 실행하세요. 여러분이 :setting:`INSTALLED_APPS` 에 + 새로운 어플리케이션을 설치하였기 때문에 데이터베이스 테이블을 업데이트 해야 합니다. -* ``mysite/urls.py`` Ʈ õ ּ - ϼ -- ּ ؾ մϴ. - URL (URLconf) ̸ ڽ ڼ ˾ƺڽϴ. ˾ƾ κ - URL roots ø̼ǿ Ű Դϴ. - Ʒ ``urls.py`` ȮϽ ֽϴ: +* ``mysite/urls.py`` 파일을 열어 관리 사이트와 관련된 행의 주석을 + 제거하세요 -- 총 세 개 행의 주석을 제거해야 합니다. 이 파일은 + URL 설정(URLconf) 파일이며 다음 자습서에서 보다 자세히 알아보겠습니다. 지금 여러분이 알아야 할 부분은 + URL roots 를 어플리케이션에 연결시키는 것 입니다. 연결 후 여러분은 + 아래와 같은 ``urls.py`` 파일을 확인하실 수 있습니다: .. parsed-literal:: @@ -55,45 +55,45 @@ **url(r'^admin/', include(admin.site.urls)),** ) - ( ǥõ ּ ŵ Դϴ.) + (굵게 표시된 행이 주석이 제거된 행 입니다.) - ϱ +개발 서버 실행하기 ============================ - Ű Ʈ Ž ϰڽϴ. +이제 개발 서버를 실행 시키고 본격적으로 관리자 사이트를 탐험해 보도록 하겠습니다. -ù ° ڽ Ͽ Ʒ : +첫 번째 자습서에서 배운 내용을 참고하여 아래와 같이 개발 서버를 실행 해 보세요: .. code-block:: bash python manage.py runserver - ϰ "/admin/" ̵ϼ -- : -http://127.0.0.1:8000/admin/. Ʈ α ȭ Դϴ: +이제 웹 브라우저를 실행하고 로컬 도메인의 "/admin/" 으로 이동하세요 -- 예: +http://127.0.0.1:8000/admin/. 관리자 사이트의 로그인 화면을 볼 수 있을 것 입니다: .. image:: _images/admin01.png - :alt: Ʈ α ȭ + :alt: 장고 관리자 사이트 로그인 화면 -.. admonition:: п ̴ ٸ? +.. admonition:: 여러분에게 보이는 페이지와 다른가요? - ̴ α ſ Ʒ - error page reporting δٸ:: + 만약 위에서 보이는 로그인 페이지 대신에 아래와 같은 + error page reporting이 보인다면:: ImportError at /admin/ cannot import name patterns ... - Ͻô ڽ - ֽϴ. Ͻô ´ ڽ ϰų, - ο Ͻñ ٶϴ. + 여러분이 사용하시는 장고의 버젼이 본 자습서의 버젼과 + 맞지 않을 수 있습니다. 사용하시는 장고 버젼과 맞는 자습서를 참고 하거나, + 새로운 버젼의 장고를 사용하시기 바랍니다. - Ʈ  +관리자 사이트 들어가기 ==================== -, α . (ù° ڽ ְ Ͻó? ʾҰų, йȣ ﳪ ʴ´ٸ :ref:`ٸ `.) Ƹ Ʈ ʱ Ȯ Դϴ: +자, 이제 로그인 해 보세요. (첫번째 자습서에서 최고 관리자 계정을 생성한 것을 기억 하시나요?만약 생성하지 않았거나, 비밀번호가 기억나지 않는다면 :ref:`다른 계정을 생성 해 보세요 `.) 아마 장고 관리자 사이트의 초기 페이지를 확인할 수 있을 것 입니다: .. image:: _images/admin02t.png - :alt: Ʈ ʱ + :alt: 장고 관리자 사이트 초기 페이지 You should see a few types of editable content, including groups, users and sites. These are core features Django ships with by default. From d825f2579ddd3ecb1c6aa22625aa603f1534c2a8 Mon Sep 17 00:00:00 2001 From: Yong Choi Date: Sun, 5 Aug 2012 09:48:40 +0900 Subject: [PATCH 007/128] translate api-stability --- misc/api-stability.txt | 183 +++++++++++++---------------------------- 1 file changed, 57 insertions(+), 126 deletions(-) diff --git a/misc/api-stability.txt b/misc/api-stability.txt index 75fa6b4..70166ce 100644 --- a/misc/api-stability.txt +++ b/misc/api-stability.txt @@ -1,42 +1,28 @@ -============= -API stability -============= +========== +API 안정성 +========== -:doc:`The release of Django 1.0 ` comes with a promise of API -stability and forwards-compatibility. In a nutshell, this means that code you -develop against Django 1.0 will continue to work against 1.1 unchanged, and you -should need to make only minor changes for any 1.X release. +:doc:`Django 1.0 릴리스 `\ 는 API 안정성과 상위 호환성을 약속으로 내걸었습니다. 간단히 말해서, 이는 여러분이 Django 1.0에서 개발한 코드는 1.1에서도 수정 없이 동작하며, 다른 1.X 릴리스에서도 사소한 수정만 하면 된다는 것을 의미합니다. -What "stable" means -=================== +"안정성"이란 +============ -In this context, stable means: +여기서 안정성이란 다음과 같은 뜻을 가집니다. -- All the public APIs -- everything documented in the linked documents below, - and all methods that don't begin with an underscore -- will not be moved or - renamed without providing backwards-compatible aliases. +- 모든 공개된 API -- 아래에 링크된 문서에 있는 모든 것, 그리고 밑줄로 시작하지 않는 모든 메소드 -- 는 하위 호환성을 제공하는 별칭을 제공하지 않은 채로 삭제하거나 이름을 바꾸지 않습니다. -- If new features are added to these APIs -- which is quite possible -- - they will not break or change the meaning of existing methods. In other - words, "stable" does not (necessarily) mean "complete." +- 이러한 API에 새로운 기능이 추가되는 경우 -- 충분히 있음직한 일입니다 -- 기존 메소드의 의미를 파괴하거나 변경하지 않습니다. 달리 말해서, "안정적"이라는 말이 (반드시) "완전함"을 의미하는 것은 아닙니다. -- If, for some reason, an API declared stable must be removed or replaced, it - will be declared deprecated but will remain in the API for at least two - minor version releases. Warnings will be issued when the deprecated method - is called. +- 만약, 어떠한 이유로 인해, 안정적이라고 선언한 API를 삭제하거나 변경해야할 일이 생긴다면, 사용을 금지하되 최소 두 번의 마이너 버전 릴리스가 일어나는 동안은 남겨둘 것입니다. 사용 금지된 메소드가 호출될 때에는 경고가 발생합니다. - See :ref:`official-releases` for more details on how Django's version - numbering scheme works, and how features will be deprecated. + Django의 버전 번호 규칙 및 어떻게 해서 기능이 사용 금지되는지에 대하여 자세히 알고 싶다면 :ref:`official-releases`를 참고하십시오. -- We'll only break backwards compatibility of these APIs if a bug or - security hole makes it completely unavoidable. +- 이러한 API들의 하위 호환성을 깨뜨리는 것은 버그 또는 보안상의 헛점으로 인하여 불가피한 경우에 한합니다. -Stable APIs -=========== +안정적인 API +============ -In general, everything covered in the documentation -- with the exception of -anything in the :doc:`internals area ` is considered stable as -of 1.0. This includes these APIs: +일반적인 경우에, -- :doc:`internals area `_에 있는 어떠한 예외도 포함하여 이 문서에서 다루는 모든 것은 1.0에서 안정적인 것으로 간주합니다. 여기에는 다음과 같은 API를 포함합니다. - :doc:`Authorization ` @@ -51,8 +37,7 @@ of 1.0. This includes these APIs: - :doc:`Forms ` -- :doc:`HTTP request/response handling `, including file - uploads, middleware, sessions, URL resolution, view, and shortcut APIs. +- :doc:`HTTP request/response handling `. including 파일 업로드, 미들웨어, 세션, URL resolution, 뷰 및 shortcut API를 포함. - :doc:`Generic views `. @@ -64,12 +49,8 @@ of 1.0. This includes these APIs: - :doc:`Signals ` -- :doc:`Templates `, including the language, Python-level - :doc:`template APIs `, and :doc:`custom template tags - and libraries `. We may add new template - tags in the future and the names may inadvertently clash with - external template tags. Before adding any such tags, we'll ensure that - Django raises an error if it tries to load tags with duplicate names. +_- :doc:`Templates `, 언어 포함, 파이썬 수준의 :doc:`template APIs ` 및 :doc:`custom template tags + and libraries `. 앞으로 새로운 템플릿 태그를 추가할 수 있으며 그 이름은 의도하지 않게 외부의 템플릿 태그와 충돌할 수 있습니다. 그러한 태그를 추가하기 전에, Django 중복되는 이름을 가진 태그를 로드하려고 할 때에는 오류를 일으키게끔 할 것입니다. - :doc:`Testing ` @@ -79,27 +60,22 @@ of 1.0. This includes these APIs: - :doc:`Request/response objects `. -- :doc:`Settings `. Note, though that while the :doc:`list of - built-in settings ` can be considered complete we may -- and - probably will -- add new settings in future versions. This is one of those - places where "'stable' does not mean 'complete.'" +- :doc:`Settings `. :doc:`list of + built-in settings `이 완전하다고 여기고는 있지만 새로운 설정이 미래에 추가될 가능성이 다분합니다. 그러한 점에서 "'안정적'이라는 말이 '완전함'을 의미하지는 않는다."고 하겠습니다. -- :doc:`Built-in signals `. Like settings, we'll probably add - new signals in the future, but the existing ones won't break. +- :doc:`Built-in signals `. settings와 마찬가지로, 앞으로 새로운 시그널을 추가하게 될 수는 있지만, 기존에 사용되던 것들은 해치지 않을 것입니다. - :doc:`Unicode handling `. -- Everything covered by the :doc:`HOWTO guides `. +- :doc:`HOWTO guides `에서 다루는 것들. ``django.utils`` ---------------- -Most of the modules in ``django.utils`` are designed for internal use. Only -the following parts of :doc:`django.utils ` can be considered stable: +``django.utils``에 있는 대부분의 모듈은 내부적인 사용을 위하여 디자인하였습니다. :doc:`django.utils ` 중 다음에 대해서만 안정적이라고 볼 수 있습니다. - ``django.utils.cache`` -- ``django.utils.datastructures.SortedDict`` -- only this single class; the - rest of the module is for internal use. +- ``django.utils.datastructures.SortedDict`` -- 단일 클래스에 한하며, 모듈 내의 나머지 것들은 내부적으로 쓰임. - ``django.utils.encoding`` - ``django.utils.feedgenerator`` - ``django.utils.http`` @@ -107,48 +83,33 @@ the following parts of :doc:`django.utils ` can be considered stable - ``django.utils.translation`` - ``django.utils.tzinfo`` -Exceptions -========== +예외 +==== -There are a few exceptions to this stability and backwards-compatibility -promise. +이러한 안정성과 하위 호환성을 약속함에 있어 몇 가지 예외가 있습니다. -Security fixes --------------- +보안 픽스 +--------- -If we become aware of a security problem -- hopefully by someone following our -:ref:`security reporting policy ` -- we'll do -everything necessary to fix it. This might mean breaking backwards compatibility; security trumps the compatibility guarantee. +:ref:`security reporting policy `에 따라 보안상의 문제점을 발견한 경우, 그것을 고치기 위해 필요한 모든 조치를 취할 것이며 이는 하위 호환성을 깨뜨릴 수도 있습니다. 호환성을 보장하는 것보다 보안이 더 중요하기 때문입니다. -Contributed applications (``django.contrib``) ---------------------------------------------- +공헌받은 애플리케이션 (``django.contrib``) +------------------------------------------ -While we'll make every effort to keep these APIs stable -- and have no plans to -break any contrib apps -- this is an area that will have more flux between -releases. As the Web evolves, Django must evolve with it. +이러한 API 안정성에 대하여 모든 노력을 다할 것이며, 어떠한 contrib 앱에 대하여도 깨뜨릴 계획이 없지만, 릴리스가 거듭되는 동안 외부의 상황이 달라질 수도 있습니다. 웹은 진화해가므로, Django도 그에 발맞추어야 하는 것입니다. -However, any changes to contrib apps will come with an important guarantee: -we'll make sure it's always possible to use an older version of a contrib app if -we need to make changes. Thus, if Django 1.5 ships with a backwards-incompatible -``django.contrib.flatpages``, we'll make sure you can still use the Django 1.4 -version alongside Django 1.5. This will continue to allow for easy upgrades. +그렇다 하더라도, contrib 앱에 대한 어떠한 변화가 일어나든 중요한 보장을 할 것입니다. 우리는 contrib 앱의 변화가 필요할 때에는 항상 그것의 이전 버전을 사용할 수 있음을 확실히 할 것입니다. 따라서, 만약 Django 1.5가 하위 호환성이 없는 ``django.contrib.flatpages``를 탑재한다면, Django 1.4 버전을 Django 1.5와 함께 사용할 수 있도록 할 것입니다. 이는 계속 업그레이드를 쉽게 할 수 있도록 해줄 것입니다. -Historically, apps in ``django.contrib`` have been more stable than the core, so -in practice we probably won't have to ever make this exception. However, it's -worth noting if you're building apps that depend on ``django.contrib``. +과거를 살펴볼 때, ``django.contrib``에 있는 앱이 core에 비하여 오히려 더 안정적이었기 때문에, 사실상 이러한 예외가 발생하지는 않을 것입니다. 그렇다 하더라도, ``django.contrib``에 의존적인 앱을 만들지 않는 것이 좋습니다. -APIs marked as internal ------------------------ +내부용으로 표시된 API +--------------------- -Certain APIs are explicitly marked as "internal" in a couple of ways: +어떤 API에 대해서는 두 가지 방법으로 "내부용"임을 명시합니다. -- Some documentation refers to internals and mentions them as such. If the - documentation says that something is internal, we reserve the right to - change it. +- 어떤 문서는 내부용 API를 다루며, 그에 대하여 언급합니다. 만약 문서에 어떤 것이 내부용이라고 되어 있다면, 그것들은 변경할 수 있습니다. -- Functions, methods, and other objects prefixed by a leading underscore - (``_``). This is the standard Python way of indicating that something is - private; if any method starts with a single ``_``, it's an internal API. +- 밑줄(``_``)로 시작하는 함수, 메소드 및 그외의 개체. 이는 비공개인 것들을 다루는 파이썬의 표준적인 방법이므로, ``_`` 한 개로 시작하는 것들은 내부 API입니다. .. _misc-api-stability-localflavor: @@ -157,50 +118,20 @@ Local flavors .. versionchanged:: 1.3 -:mod:`django.contrib.localflavor` contains assorted pieces of code -that are useful for particular countries or cultures. This data is -local in nature, and is subject to change on timelines that will -almost never correlate with Django's own release schedules. For -example, a common change is to split a province into two new -provinces, or to rename an existing province. - -These changes present two competing compatibility issues. Moving -forward, displaying the names of deprecated, renamed and dissolved -provinces in a selection widget is bad from a user interface -perspective. However, maintaining full backwards compatibility -requires that we support historical values that may be stored in a -database -- including values that may no longer be valid. - -Therefore, Django has the following policy with respect to changes in -local flavor: - -* At the time of a Django release, the data and algorithms - contained in :mod:`django.contrib.localflavor` will, to the best - of our ability, reflect the officially gazetted policies of the - appropriate local government authority. If a province has been - added, altered, or removed, that change will be reflected in - Django's localflavor. - -* These changes will *not* be backported to the previous stable - release. Upgrading a minor version of Django should not require - any data migration or audits for UI changes; therefore, if you - want to get the latest province list, you will either need to - upgrade your Django install, or backport the province list you - need. - -* For one release, the affected localflavor module will raise a - ``RuntimeWarning`` when it is imported. - -* The change will be announced in the release notes as a backwards - incompatible change requiring attention. The change will also be - annotated in the documentation for the localflavor module. - -* Where necessary and feasible, a migration script will be provided - to aid the migration process. - -For example, Django 1.2 contains an Indonesian localflavor. It has a -province list that includes "Nanggroe Aceh Darussalam (NAD)" as a -province. The Indonesian government has changed the official name of -the province to "Aceh (ACE)". As a result, Django 1.3 does *not* -contain "Nanggroe Aceh Darussalam (NAD)" in the province list, but -*does* contain "Aceh (ACE)". +:mod:`django.contrib.localflavor`는 특정 국가 및 문화권에 대하여 유용한 다양한 코드를 담고 있습니다. 이 자료는 지역적인 것이며 Django의 릴리스 일정과는 별개로 변경이 일어납니다. 한 지방을 둘로 분할한다거나, 기존의 지명이 변경되는 것을 예로 들 수 있습니다. + +이러한 변경은 두 가지 상반된 호환성 문제를 가집니다. 이름이 바뀌어서 더 이상 쓰이지 않는 지명을 선택 위젯에 표시하는 것은 사용자 인터페이스 측면에서는 좋지 못합니다. 그렇지만 하위 호환성을 최대한 유지하려면 더 이상 유효하지 않은 것들까지 포함한 과거 기록을 데이터베이스 내에 남겨두어야 할 수도 있습니다. + +그리하여, Django는 지역적 특성을 갖는 API에 대해서는 다음과 같은 정책을 따릅니다. + +* Django를 릴리스할 때에는, :mod:`django.contrib.localflavor`에 포함된 자료와 알고리즘은, 힘이 닿는 한 최선을 다해서, 지역의 정부 부처에서 공식적으로 발표된 정책을 반영합니다. 지방이 추가, 변경, 삭제되는 경우에는 Django의 localflavor에 반영합니다. + +* 이러한 변경은 이전의 안정적인 릴리스에 백포팅하지 않습니다. 마이너 버전을 업그레이드하는 경우 자료의 마이그레이션이나 UI 변경을 위한 감사를 요구하지 않습니다. 그러므로, 최근의 지방 목록을 얻고자 한다면, Django를 업그레이드하거나, 지방 목록을 직접 백포트하셔야 합니다. + +* 하나의 릴리스에 대하여, 영향을 받는 localflavor 모듈이 임포트되면 ``RuntimeWarning``을 일으킵니다. + +* 하위 호환되지 않는 변경이 일어남으로써 주의를 요하는 사항은 릴리스 노트에서 발표할 것입니다. 또한 localflavor 모듈의 문서에도 표시합니다. + +* 마이그레이션 스크립트가 꼭 필요하고 구현이 가능한 경우에는 마이그레이션 절차를 도울 수 있도록 이를 제공할 것입니다. + +예를 들어, Django 1.2의 인도네시아 localflavor에는 "Nanggroe Aceh Darussalam (NAD)"가 포함됩니다. 인도네시아 정부에서 지명을 "Aceh (ACE)"로 변경함에 따라, Django 1.3에서는 지방 목록에 "Nanggroe Aceh Darussalam (NAD)"을 *포함하지 않고*, "Aceh (ACE)"를 *포함합니다*. From 58e0d6dec982617a0e5f484028df275611f2a13f Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Sun, 5 Aug 2012 10:18:16 +0900 Subject: [PATCH 008/128] fix links on api-stability --- misc/api-stability.txt | 272 ++++++++++++++++++++--------------------- 1 file changed, 135 insertions(+), 137 deletions(-) diff --git a/misc/api-stability.txt b/misc/api-stability.txt index 70166ce..b1f7e80 100644 --- a/misc/api-stability.txt +++ b/misc/api-stability.txt @@ -1,137 +1,135 @@ -========== -API 안정성 -========== - -:doc:`Django 1.0 릴리스 `\ 는 API 안정성과 상위 호환성을 약속으로 내걸었습니다. 간단히 말해서, 이는 여러분이 Django 1.0에서 개발한 코드는 1.1에서도 수정 없이 동작하며, 다른 1.X 릴리스에서도 사소한 수정만 하면 된다는 것을 의미합니다. - -"안정성"이란 -============ - -여기서 안정성이란 다음과 같은 뜻을 가집니다. - -- 모든 공개된 API -- 아래에 링크된 문서에 있는 모든 것, 그리고 밑줄로 시작하지 않는 모든 메소드 -- 는 하위 호환성을 제공하는 별칭을 제공하지 않은 채로 삭제하거나 이름을 바꾸지 않습니다. - -- 이러한 API에 새로운 기능이 추가되는 경우 -- 충분히 있음직한 일입니다 -- 기존 메소드의 의미를 파괴하거나 변경하지 않습니다. 달리 말해서, "안정적"이라는 말이 (반드시) "완전함"을 의미하는 것은 아닙니다. - -- 만약, 어떠한 이유로 인해, 안정적이라고 선언한 API를 삭제하거나 변경해야할 일이 생긴다면, 사용을 금지하되 최소 두 번의 마이너 버전 릴리스가 일어나는 동안은 남겨둘 것입니다. 사용 금지된 메소드가 호출될 때에는 경고가 발생합니다. - - Django의 버전 번호 규칙 및 어떻게 해서 기능이 사용 금지되는지에 대하여 자세히 알고 싶다면 :ref:`official-releases`를 참고하십시오. - -- 이러한 API들의 하위 호환성을 깨뜨리는 것은 버그 또는 보안상의 헛점으로 인하여 불가피한 경우에 한합니다. - -안정적인 API -============ - -일반적인 경우에, -- :doc:`internals area `_에 있는 어떠한 예외도 포함하여 이 문서에서 다루는 모든 것은 1.0에서 안정적인 것으로 간주합니다. 여기에는 다음과 같은 API를 포함합니다. - -- :doc:`Authorization ` - -- :doc:`Caching `. - -- :doc:`Model definition, managers, querying and transactions - ` - -- :doc:`Sending email `. - -- :doc:`File handling and storage ` - -- :doc:`Forms ` - -- :doc:`HTTP request/response handling `. including 파일 업로드, 미들웨어, 세션, URL resolution, 뷰 및 shortcut API를 포함. - -- :doc:`Generic views `. - -- :doc:`Internationalization `. - -- :doc:`Pagination ` - -- :doc:`Serialization ` - -- :doc:`Signals ` - -_- :doc:`Templates `, 언어 포함, 파이썬 수준의 :doc:`template APIs ` 및 :doc:`custom template tags - and libraries `. 앞으로 새로운 템플릿 태그를 추가할 수 있으며 그 이름은 의도하지 않게 외부의 템플릿 태그와 충돌할 수 있습니다. 그러한 태그를 추가하기 전에, Django 중복되는 이름을 가진 태그를 로드하려고 할 때에는 오류를 일으키게끔 할 것입니다. - -- :doc:`Testing ` - -- :doc:`django-admin utility `. - -- :doc:`Built-in middleware ` - -- :doc:`Request/response objects `. - -- :doc:`Settings `. :doc:`list of - built-in settings `이 완전하다고 여기고는 있지만 새로운 설정이 미래에 추가될 가능성이 다분합니다. 그러한 점에서 "'안정적'이라는 말이 '완전함'을 의미하지는 않는다."고 하겠습니다. - -- :doc:`Built-in signals `. settings와 마찬가지로, 앞으로 새로운 시그널을 추가하게 될 수는 있지만, 기존에 사용되던 것들은 해치지 않을 것입니다. - -- :doc:`Unicode handling `. - -- :doc:`HOWTO guides `에서 다루는 것들. - -``django.utils`` ----------------- - -``django.utils``에 있는 대부분의 모듈은 내부적인 사용을 위하여 디자인하였습니다. :doc:`django.utils ` 중 다음에 대해서만 안정적이라고 볼 수 있습니다. - -- ``django.utils.cache`` -- ``django.utils.datastructures.SortedDict`` -- 단일 클래스에 한하며, 모듈 내의 나머지 것들은 내부적으로 쓰임. -- ``django.utils.encoding`` -- ``django.utils.feedgenerator`` -- ``django.utils.http`` -- ``django.utils.safestring`` -- ``django.utils.translation`` -- ``django.utils.tzinfo`` - -예외 -==== - -이러한 안정성과 하위 호환성을 약속함에 있어 몇 가지 예외가 있습니다. - -보안 픽스 ---------- - -:ref:`security reporting policy `에 따라 보안상의 문제점을 발견한 경우, 그것을 고치기 위해 필요한 모든 조치를 취할 것이며 이는 하위 호환성을 깨뜨릴 수도 있습니다. 호환성을 보장하는 것보다 보안이 더 중요하기 때문입니다. - -공헌받은 애플리케이션 (``django.contrib``) ------------------------------------------- - -이러한 API 안정성에 대하여 모든 노력을 다할 것이며, 어떠한 contrib 앱에 대하여도 깨뜨릴 계획이 없지만, 릴리스가 거듭되는 동안 외부의 상황이 달라질 수도 있습니다. 웹은 진화해가므로, Django도 그에 발맞추어야 하는 것입니다. - -그렇다 하더라도, contrib 앱에 대한 어떠한 변화가 일어나든 중요한 보장을 할 것입니다. 우리는 contrib 앱의 변화가 필요할 때에는 항상 그것의 이전 버전을 사용할 수 있음을 확실히 할 것입니다. 따라서, 만약 Django 1.5가 하위 호환성이 없는 ``django.contrib.flatpages``를 탑재한다면, Django 1.4 버전을 Django 1.5와 함께 사용할 수 있도록 할 것입니다. 이는 계속 업그레이드를 쉽게 할 수 있도록 해줄 것입니다. - -과거를 살펴볼 때, ``django.contrib``에 있는 앱이 core에 비하여 오히려 더 안정적이었기 때문에, 사실상 이러한 예외가 발생하지는 않을 것입니다. 그렇다 하더라도, ``django.contrib``에 의존적인 앱을 만들지 않는 것이 좋습니다. - -내부용으로 표시된 API ---------------------- - -어떤 API에 대해서는 두 가지 방법으로 "내부용"임을 명시합니다. - -- 어떤 문서는 내부용 API를 다루며, 그에 대하여 언급합니다. 만약 문서에 어떤 것이 내부용이라고 되어 있다면, 그것들은 변경할 수 있습니다. - -- 밑줄(``_``)로 시작하는 함수, 메소드 및 그외의 개체. 이는 비공개인 것들을 다루는 파이썬의 표준적인 방법이므로, ``_`` 한 개로 시작하는 것들은 내부 API입니다. - -.. _misc-api-stability-localflavor: - -Local flavors -------------- - -.. versionchanged:: 1.3 - -:mod:`django.contrib.localflavor`는 특정 국가 및 문화권에 대하여 유용한 다양한 코드를 담고 있습니다. 이 자료는 지역적인 것이며 Django의 릴리스 일정과는 별개로 변경이 일어납니다. 한 지방을 둘로 분할한다거나, 기존의 지명이 변경되는 것을 예로 들 수 있습니다. - -이러한 변경은 두 가지 상반된 호환성 문제를 가집니다. 이름이 바뀌어서 더 이상 쓰이지 않는 지명을 선택 위젯에 표시하는 것은 사용자 인터페이스 측면에서는 좋지 못합니다. 그렇지만 하위 호환성을 최대한 유지하려면 더 이상 유효하지 않은 것들까지 포함한 과거 기록을 데이터베이스 내에 남겨두어야 할 수도 있습니다. - -그리하여, Django는 지역적 특성을 갖는 API에 대해서는 다음과 같은 정책을 따릅니다. - -* Django를 릴리스할 때에는, :mod:`django.contrib.localflavor`에 포함된 자료와 알고리즘은, 힘이 닿는 한 최선을 다해서, 지역의 정부 부처에서 공식적으로 발표된 정책을 반영합니다. 지방이 추가, 변경, 삭제되는 경우에는 Django의 localflavor에 반영합니다. - -* 이러한 변경은 이전의 안정적인 릴리스에 백포팅하지 않습니다. 마이너 버전을 업그레이드하는 경우 자료의 마이그레이션이나 UI 변경을 위한 감사를 요구하지 않습니다. 그러므로, 최근의 지방 목록을 얻고자 한다면, Django를 업그레이드하거나, 지방 목록을 직접 백포트하셔야 합니다. - -* 하나의 릴리스에 대하여, 영향을 받는 localflavor 모듈이 임포트되면 ``RuntimeWarning``을 일으킵니다. - -* 하위 호환되지 않는 변경이 일어남으로써 주의를 요하는 사항은 릴리스 노트에서 발표할 것입니다. 또한 localflavor 모듈의 문서에도 표시합니다. - -* 마이그레이션 스크립트가 꼭 필요하고 구현이 가능한 경우에는 마이그레이션 절차를 도울 수 있도록 이를 제공할 것입니다. - -예를 들어, Django 1.2의 인도네시아 localflavor에는 "Nanggroe Aceh Darussalam (NAD)"가 포함됩니다. 인도네시아 정부에서 지명을 "Aceh (ACE)"로 변경함에 따라, Django 1.3에서는 지방 목록에 "Nanggroe Aceh Darussalam (NAD)"을 *포함하지 않고*, "Aceh (ACE)"를 *포함합니다*. +========== +API 안정성 +========== + +:doc:`Django 1.0 릴리스 `\ 는 API 안정성과 상위 호환성을 약속으로 내걸었습니다. 간단히 말해서, 이는 여러분이 Django 1.0에서 개발한 코드는 1.1에서도 수정 없이 동작하며, 다른 1.X 릴리스에서도 사소한 수정만 하면 된다는 것을 의미합니다. + +"안정성"이란 +============ + +여기서 안정성이란 다음과 같은 뜻을 가집니다. + +- 모든 공개된 API -- 아래에 링크된 문서에 있는 모든 것, 그리고 밑줄로 시작하지 않는 모든 메소드 -- 는 하위 호환성을 제공하는 별칭을 제공하지 않은 채로 삭제하거나 이름을 바꾸지 않습니다. + +- 이러한 API에 새로운 기능이 추가되는 경우 -- 충분히 있음직한 일입니다 -- 기존 메소드의 의미를 파괴하거나 변경하지 않습니다. 달리 말해서, "안정적"이라는 말이 (반드시) "완전함"을 의미하는 것은 아닙니다. + +- 만약, 어떠한 이유로 인해, 안정적이라고 선언한 API를 삭제하거나 변경해야할 일이 생긴다면, 사용을 금지하되 최소 두 번의 마이너 버전 릴리스가 일어나는 동안은 남겨둘 것입니다. 사용 금지된 메소드가 호출될 때에는 경고가 발생합니다. + + Django의 버전 번호 규칙 및 어떻게 해서 기능이 사용 금지되는지에 대하여 자세히 알고 싶다면 :ref:`official-releases`를 참고하십시오. + +- 이러한 API들의 하위 호환성을 깨뜨리는 것은 버그 또는 보안상의 헛점으로 인하여 불가피한 경우에 한합니다. + +안정적인 API +============ + +일반적인 경우에, -- :doc:`internals area `\ 에 있는 어떠한 예외도 포함하여 이 문서에서 다루는 모든 것은 1.0에서 안정적인 것으로 간주합니다. 여기에는 다음과 같은 API를 포함합니다. + +- :doc:`인증 ` + +- :doc:`캐싱 `. + +- :doc:`Model definition, managers, querying and transactions + ` + +- :doc:`Sending email `. + +- :doc:`File handling and storage ` + +- :doc:`Forms ` + +- :doc:`HTTP request/response handling `. including 파일 업로드, 미들웨어, 세션, URL resolution, 뷰 및 shortcut API를 포함. + +- :doc:`Generic views `. + +- :doc:`Internationalization `. + +- :doc:`Pagination ` + +- :doc:`Serialization ` + +- :doc:`Signals ` + +_- :doc:`Templates `, 언어 포함, 파이썬 수준의 :doc:`template APIs ` 및 :doc:`custom template tags and libraries `. 앞으로 새로운 템플릿 태그를 추가할 수 있으며 그 이름은 의도하지 않게 외부의 템플릿 태그와 충돌할 수 있습니다. 그러한 태그를 추가하기 전에, Django 중복되는 이름을 가진 태그를 로드하려고 할 때에는 오류를 일으키게끔 할 것입니다. + +- :doc:`Testing ` + +- :doc:`django-admin utility `. + +- :doc:`Built-in middleware ` + +- :doc:`Request/response objects `. + +- :doc:`설정 `. :doc:`list of built-in settings `\ 이 완전하다고 여기고는 있지만 새로운 설정이 미래에 추가될 가능성이 다분합니다. 그러한 점에서 "'안정적'이라는 말이 '완전함'을 의미하지는 않는다."고 하겠습니다. + +- :doc:`Built-in signals `. settings와 마찬가지로, 앞으로 새로운 시그널을 추가하게 될 수는 있지만, 기존에 사용되던 것들은 해치지 않을 것입니다. + +- :doc:`Unicode handling `. + +- :doc:`HOWTO guides `에서 다루는 것들. + +``django.utils`` +---------------- + +``django.utils``\ 에 있는 대부분의 모듈은 내부적인 사용을 위하여 디자인하였습니다. :doc:`django.utils ` 중 다음에 대해서만 안정적이라고 볼 수 있습니다. + +- ``django.utils.cache`` +- ``django.utils.datastructures.SortedDict`` -- 단일 클래스에 한하며, 모듈 내의 나머지 것들은 내부적으로 쓰임. +- ``django.utils.encoding`` +- ``django.utils.feedgenerator`` +- ``django.utils.http`` +- ``django.utils.safestring`` +- ``django.utils.translation`` +- ``django.utils.tzinfo`` + +예외 +==== + +이러한 안정성과 하위 호환성을 약속함에 있어 몇 가지 예외가 있습니다. + +보안 픽스 +--------- + +:ref:`security reporting policy `\ 에 따라 보안상의 문제점을 발견한 경우, 그것을 고치기 위해 필요한 모든 조치를 취할 것이며 이는 하위 호환성을 깨뜨릴 수도 있습니다. 호환성을 보장하는 것보다 보안이 더 중요하기 때문입니다. + +공헌받은 애플리케이션 (``django.contrib``) +------------------------------------------ + +이러한 API 안정성에 대하여 모든 노력을 다할 것이며, 어떠한 contrib 앱에 대하여도 깨뜨릴 계획이 없지만, 릴리스가 거듭되는 동안 외부의 상황이 달라질 수도 있습니다. 웹은 진화해가므로, Django도 그에 발맞추어야 하는 것입니다. + +그렇다 하더라도, contrib 앱에 대한 어떠한 변화가 일어나든 중요한 보장을 할 것입니다. 우리는 contrib 앱의 변화가 필요할 때에는 항상 그것의 이전 버전을 사용할 수 있음을 확실히 할 것입니다. 따라서, 만약 Django 1.5가 하위 호환성이 없는 ``django.contrib.flatpages``를 탑재한다면, Django 1.4 버전을 Django 1.5와 함께 사용할 수 있도록 할 것입니다. 이는 계속 업그레이드를 쉽게 할 수 있도록 해줄 것입니다. + +과거를 살펴볼 때, ``django.contrib``\ 에 있는 앱이 core에 비하여 오히려 더 안정적이었기 때문에, 사실상 이러한 예외가 발생하지는 않을 것입니다. 그렇다 하더라도, ``django.contrib``\ 에 의존적인 앱을 만들지 않는 것이 좋습니다. + +내부용으로 표시된 API +--------------------- + +어떤 API에 대해서는 두 가지 방법으로 "내부용"임을 명시합니다. + +- 어떤 문서는 내부용 API를 다루며, 그에 대하여 언급합니다. 만약 문서에 어떤 것이 내부용이라고 되어 있다면, 그것들은 변경할 수 있습니다. + +- 밑줄(``_``)로 시작하는 함수, 메소드 및 그외의 개체. 이는 비공개인 것들을 다루는 파이썬의 표준적인 방법이므로, ``_`` 한 개로 시작하는 것들은 내부 API입니다. + +.. _misc-api-stability-localflavor: + +Local flavors +------------- + +.. versionchanged:: 1.3 + +:mod:`django.contrib.localflavor`는 특정 국가 및 문화권에 대하여 유용한 다양한 코드를 담고 있습니다. 이 자료는 지역적인 것이며 Django의 릴리스 일정과는 별개로 변경이 일어납니다. 한 지방을 둘로 분할한다거나, 기존의 지명이 변경되는 것을 예로 들 수 있습니다. + +이러한 변경은 두 가지 상반된 호환성 문제를 가집니다. 이름이 바뀌어서 더 이상 쓰이지 않는 지명을 선택 위젯에 표시하는 것은 사용자 인터페이스 측면에서는 좋지 못합니다. 그렇지만 하위 호환성을 최대한 유지하려면 더 이상 유효하지 않은 것들까지 포함한 과거 기록을 데이터베이스 내에 남겨두어야 할 수도 있습니다. + +그리하여, Django는 지역적 특성을 갖는 API에 대해서는 다음과 같은 정책을 따릅니다. + +* Django를 릴리스할 때에는, :mod:`django.contrib.localflavor`\ 에 포함된 자료와 알고리즘은, 힘이 닿는 한 최선을 다해서, 지역의 정부 부처에서 공식적으로 발표된 정책을 반영합니다. 지방이 추가, 변경, 삭제되는 경우에는 Django의 localflavor에 반영합니다. + +* 이러한 변경은 이전의 안정적인 릴리스에 백포팅하지 않습니다. 마이너 버전을 업그레이드하는 경우 자료의 마이그레이션이나 UI 변경을 위한 감사를 요구하지 않습니다. 그러므로, 최근의 지방 목록을 얻고자 한다면, Django를 업그레이드하거나, 지방 목록을 직접 백포트하셔야 합니다. + +* 하나의 릴리스에 대하여, 영향을 받는 localflavor 모듈이 임포트되면 ``RuntimeWarning``\ 을 일으킵니다. + +* 하위 호환되지 않는 변경이 일어남으로써 주의를 요하는 사항은 릴리스 노트에서 발표할 것입니다. 또한 localflavor 모듈의 문서에도 표시합니다. + +* 마이그레이션 스크립트가 꼭 필요하고 구현이 가능한 경우에는 마이그레이션 절차를 도울 수 있도록 이를 제공할 것입니다. + +예를 들어, Django 1.2의 인도네시아 localflavor에는 "Nanggroe Aceh Darussalam (NAD)"가 포함됩니다. 인도네시아 정부에서 지명을 "Aceh (ACE)"로 변경함에 따라, Django 1.3에서는 지방 목록에 "Nanggroe Aceh Darussalam (NAD)"을 *포함하지 않고*, "Aceh (ACE)"를 *포함합니다*. From e308c9d734d62a35c5816ba1e3892b8a183a7440 Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Sun, 5 Aug 2012 10:32:48 +0900 Subject: [PATCH 009/128] fix and translate links on api-stability --- misc/api-stability.txt | 47 +++++++++++++++++++++--------------------- 1 file changed, 23 insertions(+), 24 deletions(-) diff --git a/misc/api-stability.txt b/misc/api-stability.txt index b1f7e80..b6f7b61 100644 --- a/misc/api-stability.txt +++ b/misc/api-stability.txt @@ -22,50 +22,49 @@ API 안정성 안정적인 API ============ -일반적인 경우에, -- :doc:`internals area `\ 에 있는 어떠한 예외도 포함하여 이 문서에서 다루는 모든 것은 1.0에서 안정적인 것으로 간주합니다. 여기에는 다음과 같은 API를 포함합니다. +일반적인 경우에, -- :doc:`내부 영역 `\ 에 있는 어떠한 예외도 포함하여 이 문서에서 다루는 모든 것은 1.0에서 안정적인 것으로 간주합니다. 여기에는 다음과 같은 API를 포함합니다. - :doc:`인증 ` - :doc:`캐싱 `. -- :doc:`Model definition, managers, querying and transactions - ` +- :doc:`모델 정의, 관리자, 질의 및 트랜잭션 ` -- :doc:`Sending email `. +- :doc:`이메일 보내기 `. -- :doc:`File handling and storage ` +- :doc:`파일 처리 및 스토리지 ` -- :doc:`Forms ` +- :doc:`폼 ` -- :doc:`HTTP request/response handling `. including 파일 업로드, 미들웨어, 세션, URL resolution, 뷰 및 shortcut API를 포함. +- :doc:`HTTP 요청/응답 처리 `. 파일 업로드, 미들웨어, 세션, URL resolution, 뷰 및 shortcut API를 포함. -- :doc:`Generic views `. +- :doc:`제너릭 뷰 `. -- :doc:`Internationalization `. +- :doc:`국제화 `. -- :doc:`Pagination ` +- :doc:`페이지네이션 ` -- :doc:`Serialization ` +- :doc:`직렬화 ` -- :doc:`Signals ` +- :doc:`시그널 ` -_- :doc:`Templates `, 언어 포함, 파이썬 수준의 :doc:`template APIs ` 및 :doc:`custom template tags and libraries `. 앞으로 새로운 템플릿 태그를 추가할 수 있으며 그 이름은 의도하지 않게 외부의 템플릿 태그와 충돌할 수 있습니다. 그러한 태그를 추가하기 전에, Django 중복되는 이름을 가진 태그를 로드하려고 할 때에는 오류를 일으키게끔 할 것입니다. +- :doc:`템플릿 `, 언어 포함, 파이썬 수준의 :doc:`template APIs ` 및 :doc:`custom template tags and libraries `. 앞으로 새로운 템플릿 태그를 추가할 수 있으며 그 이름은 의도하지 않게 외부의 템플릿 태그와 충돌할 수 있습니다. 그러한 태그를 추가하기 전에, Django 중복되는 이름을 가진 태그를 로드하려고 할 때에는 오류를 일으키게끔 할 것입니다. -- :doc:`Testing ` +- :doc:`테스팅 ` -- :doc:`django-admin utility `. +- :doc:`django-admin 유틸리티 `. -- :doc:`Built-in middleware ` +- :doc:`내장된 미들웨어 ` -- :doc:`Request/response objects `. +- :doc:`요청/응답 개체 `. -- :doc:`설정 `. :doc:`list of built-in settings `\ 이 완전하다고 여기고는 있지만 새로운 설정이 미래에 추가될 가능성이 다분합니다. 그러한 점에서 "'안정적'이라는 말이 '완전함'을 의미하지는 않는다."고 하겠습니다. +- :doc:`설정 `. :doc:`내장 settings 목록 `\ 이 완전하다고 여기고는 있지만 새로운 설정이 미래에 추가될 가능성이 다분합니다. 그러한 점에서 "'안정적'이라는 말이 '완전함'을 의미하지는 않는다."고 하겠습니다. -- :doc:`Built-in signals `. settings와 마찬가지로, 앞으로 새로운 시그널을 추가하게 될 수는 있지만, 기존에 사용되던 것들은 해치지 않을 것입니다. +- :doc:`내장된 시그널 `. 설정과 마찬가지로 앞으로 새로운 시그널을 추가하게 될 수는 있지만, 기존에 사용되던 것들은 해치지 않을 것입니다. -- :doc:`Unicode handling `. +- :doc:`유니코드 처리 `. -- :doc:`HOWTO guides `에서 다루는 것들. +- :doc:`하우투 안내서 `\ 에서 다루는 것들. ``django.utils`` ---------------- @@ -89,14 +88,14 @@ _- :doc:`Templates `, 언어 포함, 파이썬 수준의 :doc 보안 픽스 --------- -:ref:`security reporting policy `\ 에 따라 보안상의 문제점을 발견한 경우, 그것을 고치기 위해 필요한 모든 조치를 취할 것이며 이는 하위 호환성을 깨뜨릴 수도 있습니다. 호환성을 보장하는 것보다 보안이 더 중요하기 때문입니다. +:ref:`보안 보고 정책 `\ 에 따라 보안상의 문제점을 발견한 경우, 그것을 고치기 위해 필요한 모든 조치를 취할 것이며 이는 하위 호환성을 깨뜨릴 수도 있습니다. 호환성을 보장하는 것보다 보안이 더 중요하기 때문입니다. 공헌받은 애플리케이션 (``django.contrib``) ------------------------------------------ 이러한 API 안정성에 대하여 모든 노력을 다할 것이며, 어떠한 contrib 앱에 대하여도 깨뜨릴 계획이 없지만, 릴리스가 거듭되는 동안 외부의 상황이 달라질 수도 있습니다. 웹은 진화해가므로, Django도 그에 발맞추어야 하는 것입니다. -그렇다 하더라도, contrib 앱에 대한 어떠한 변화가 일어나든 중요한 보장을 할 것입니다. 우리는 contrib 앱의 변화가 필요할 때에는 항상 그것의 이전 버전을 사용할 수 있음을 확실히 할 것입니다. 따라서, 만약 Django 1.5가 하위 호환성이 없는 ``django.contrib.flatpages``를 탑재한다면, Django 1.4 버전을 Django 1.5와 함께 사용할 수 있도록 할 것입니다. 이는 계속 업그레이드를 쉽게 할 수 있도록 해줄 것입니다. +그렇다 하더라도, contrib 앱에 대한 어떠한 변화가 일어나든 중요한 보장을 할 것입니다. 우리는 contrib 앱의 변화가 필요할 때에는 항상 그것의 이전 버전을 사용할 수 있음을 확실히 할 것입니다. 따라서, 만약 Django 1.5가 하위 호환성이 없는 ``django.contrib.flatpages``\ 를 탑재한다면, Django 1.4 버전을 Django 1.5와 함께 사용할 수 있도록 할 것입니다. 이는 계속 업그레이드를 쉽게 할 수 있도록 해줄 것입니다. 과거를 살펴볼 때, ``django.contrib``\ 에 있는 앱이 core에 비하여 오히려 더 안정적이었기 때문에, 사실상 이러한 예외가 발생하지는 않을 것입니다. 그렇다 하더라도, ``django.contrib``\ 에 의존적인 앱을 만들지 않는 것이 좋습니다. @@ -116,7 +115,7 @@ Local flavors .. versionchanged:: 1.3 -:mod:`django.contrib.localflavor`는 특정 국가 및 문화권에 대하여 유용한 다양한 코드를 담고 있습니다. 이 자료는 지역적인 것이며 Django의 릴리스 일정과는 별개로 변경이 일어납니다. 한 지방을 둘로 분할한다거나, 기존의 지명이 변경되는 것을 예로 들 수 있습니다. +:mod:`django.contrib.localflavor`\ 는 특정 국가 및 문화권에 대하여 유용한 다양한 코드를 담고 있습니다. 이 자료는 지역적인 것이며 Django의 릴리스 일정과는 별개로 변경이 일어납니다. 한 지방을 둘로 분할한다거나, 기존의 지명이 변경되는 것을 예로 들 수 있습니다. 이러한 변경은 두 가지 상반된 호환성 문제를 가집니다. 이름이 바뀌어서 더 이상 쓰이지 않는 지명을 선택 위젯에 표시하는 것은 사용자 인터페이스 측면에서는 좋지 못합니다. 그렇지만 하위 호환성을 최대한 유지하려면 더 이상 유효하지 않은 것들까지 포함한 과거 기록을 데이터베이스 내에 남겨두어야 할 수도 있습니다. From 9353dd2140f7492ed256233d519751b063628b06 Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Sun, 5 Aug 2012 10:39:25 +0900 Subject: [PATCH 010/128] fix and translate links on api-stability again --- misc/api-stability.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/misc/api-stability.txt b/misc/api-stability.txt index b6f7b61..4209fe7 100644 --- a/misc/api-stability.txt +++ b/misc/api-stability.txt @@ -15,7 +15,7 @@ API 안정성 - 만약, 어떠한 이유로 인해, 안정적이라고 선언한 API를 삭제하거나 변경해야할 일이 생긴다면, 사용을 금지하되 최소 두 번의 마이너 버전 릴리스가 일어나는 동안은 남겨둘 것입니다. 사용 금지된 메소드가 호출될 때에는 경고가 발생합니다. - Django의 버전 번호 규칙 및 어떻게 해서 기능이 사용 금지되는지에 대하여 자세히 알고 싶다면 :ref:`official-releases`를 참고하십시오. + Django의 버전 번호 규칙 및 어떻게 해서 기능이 사용 금지되는지에 대하여 자세히 알고 싶다면 :ref:`official-releases`\ 를 참고하십시오. - 이러한 API들의 하위 호환성을 깨뜨리는 것은 버그 또는 보안상의 헛점으로 인하여 불가피한 경우에 한합니다. @@ -48,7 +48,7 @@ API 안정성 - :doc:`시그널 ` -- :doc:`템플릿 `, 언어 포함, 파이썬 수준의 :doc:`template APIs ` 및 :doc:`custom template tags and libraries `. 앞으로 새로운 템플릿 태그를 추가할 수 있으며 그 이름은 의도하지 않게 외부의 템플릿 태그와 충돌할 수 있습니다. 그러한 태그를 추가하기 전에, Django 중복되는 이름을 가진 태그를 로드하려고 할 때에는 오류를 일으키게끔 할 것입니다. +- :doc:`템플릿 `, 언어 포함, 파이썬 수준의 :doc:`template APIs ` 및 :doc:`맞춤 템플릿 태그 및 라이브러리 `. 앞으로 새로운 템플릿 태그를 추가할 수 있으며 그 이름은 의도하지 않게 외부의 템플릿 태그와 충돌할 수 있습니다. 그러한 태그를 추가하기 전에, Django 중복되는 이름을 가진 태그를 로드하려고 할 때에는 오류를 일으키게끔 할 것입니다. - :doc:`테스팅 ` From 9bba206774a12d4dc053120a35fca05e347d47cf Mon Sep 17 00:00:00 2001 From: "Sangho, Choi" Date: Sun, 5 Aug 2012 14:06:36 +0900 Subject: [PATCH 011/128] Update intro/tutorial02.txt Wrong words have been fixed. --- intro/tutorial02.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/intro/tutorial02.txt b/intro/tutorial02.txt index 69122f3..cf4e879 100644 --- a/intro/tutorial02.txt +++ b/intro/tutorial02.txt @@ -8,7 +8,7 @@ 관리자나 고객들이 컨텐츠를 추가, 변경, 삭제할 수 있는 관리자 사이트를 생성하는 것은 그다지 창조적이지 않은 지루한 작업 입니다. 이러한 작업을 - 위해서 장고는 모델을 위한 관리자 인터페이스 생성을 완전히 자동화 하였습니다니다. + 위해서 장고는 모델을 위한 관리자 인터페이스 생성을 완전히 자동화 하였습니다. 장고는 뉴스를 준비하는 환경을 위해 만들어졌으며, "컨텐츠 발행인"과 "공개" 사이트를 완벽히 분리하였습니. 사이트 관리자들은 From 80cf4e31ddc172106a87d94047e3cfd67843878d Mon Sep 17 00:00:00 2001 From: shchoi Date: Mon, 6 Aug 2012 01:38:54 +0900 Subject: [PATCH 012/128] Update intro/tutorial02.txt --- intro/tutorial02.txt | 74 ++++++++++++++++++++------------------------ 1 file changed, 34 insertions(+), 40 deletions(-) diff --git a/intro/tutorial02.txt b/intro/tutorial02.txt index 69122f3..75bc9f6 100644 --- a/intro/tutorial02.txt +++ b/intro/tutorial02.txt @@ -84,84 +84,78 @@ http://127.0.0.1:8000/admin/. 관리자 사이트의 로그인 화면을 볼 수 ... 여러분이 사용하시는 장고의 버젼이 본 자습서의 버젼과 - 맞지 않을 수 있습니다. 사용하시는 장고 버젼과 맞는 자습서를 참고 하거나, + 맞지 않을 수 있습니다. 사용하시는 장고 버젼에 맞는 자습서를 참고 하거나, 새로운 버젼의 장고를 사용하시기 바랍니다. 관리자 사이트 들어가기 ==================== -자, 이제 로그인 해 보세요. (첫번째 자습서에서 최고 관리자 계정을 생성한 것을 기억 하시나요?만약 생성하지 않았거나, 비밀번호가 기억나지 않는다면 :ref:`다른 계정을 생성 해 보세요 `.) 아마 장고 관리자 사이트의 초기 페이지를 확인할 수 있을 것 입니다: +자, 이제 로그인 해 보세요. (첫번째 자습서에서 최고 관리자 계정을 생성한 것을 기억 하시나요? 만약 생성하지 않았거나, 비밀번호가 기억나지 않는다면 :ref:`다른 계정을 생성` 해 보세요.) 장고 관리자 사이트의 초기 페이지를 확인할 수 있을 것 입니다: .. image:: _images/admin02t.png :alt: 장고 관리자 사이트 초기 페이지 -You should see a few types of editable content, including groups, users -and sites. These are core features Django ships with by default. +Groups, users, sites 등 몇 개의 수정 가능한 컨텐츠를 확인할 수 있는데, 이들은 장고에서 기본적으로 제공하는 핵심 기능 입니다. -Make the poll app modifiable in the admin +관리자 사이트에서 수정 가능한 설문조사 앱 만들기 ========================================= -But where's our poll app? It's not displayed on the admin index page. +그러데 우리의 설문조사 앱은 어디에 있나요?아직 관리자 사이트 초기 페이지에 보이지 않습니다. -Just one thing to do: We need to tell the admin that ``Poll`` -objects have an admin interface. To do this, create a file called -``admin.py`` in your ``polls`` directory, and edit it to look like this:: +단 한가지 할 일: 우선 관리자 사이트에게 ``Poll`` +오브젝트가 관리자 인터페이스가 필요하다고 알려줘야 합니다. 이를 위해 ``polls`` 디렉토리 안에 ``admin.py`` 파일을 생성하고 아래와 같이 수정합니다:: from polls.models import Poll from django.contrib import admin admin.site.register(Poll) -You'll need to restart the development server to see your changes. Normally, -the server auto-reloads code every time you modify a file, but the action of -creating a new file doesn't trigger the auto-reloading logic. +수정사항을 확인하기 위해 개발 서버를 재시작 해야 합니다. 일반적으로 파일이 수정되면 서버는 자동으로 수정된 코드를 다시 불러오지만 새로 생성된 파일은 자동으로 불러오지 않습니다. -Explore the free admin functionality +무료 관리 기능 탐험하기 ==================================== -Now that we've registered ``Poll``, Django knows that it should be displayed on -the admin index page: +자, 이제 ``Poll`` 이 등록되었고, 장고는 ``Poll`` 을 관리 사이트 초기 페이지에 보여줘야 함을 알고 있습니다: .. image:: _images/admin03t.png - :alt: Django admin index page, now with polls displayed + :alt: polls가 보여지는 장고 관리자 사이트 초기 페이지 -Click "Polls." Now you're at the "change list" page for polls. This page -displays all the polls in the database and lets you choose one to change it. -There's the "What's up?" poll we created in the first tutorial: +이제 "Polls."를 클릭하면 polls의 "change list" 를 볼 수 있습니다. 이 페이지에서는 데이터베이스의 모든 poll이 보여지게 되며 이중 한개를 선택하여 변경할 수 있습니다. +여기에 우리가 첫 번째 자습서에서 생성한 "What's up?" poll을 확인할 수 있습니다: .. image:: _images/admin04t.png - :alt: Polls change list page + :alt: Poll 변경 리스트 페이지 -Click the "What's up?" poll to edit it: +Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: .. image:: _images/admin05t.png - :alt: Editing form for poll object + :alt: Poll 객체 수정 폼 -Things to note here: +여기서 짚고 넘어가기: -* The form is automatically generated from the Poll model. +* 폼은 Poll 모델로 부터 자동적으로 생성되었습니다. -* The different model field types (:class:`~django.db.models.DateTimeField`, - :class:`~django.db.models.CharField`) correspond to the appropriate HTML - input widget. Each type of field knows how to display itself in the Django - admin. +* 서로 다른 모델의 필드 타입 (:class:`~django.db.models.DateTimeField`, + :class:`~django.db.models.CharField`) 에 따라 적절한 HTML 입력 위젯이 + 보여집니다. 각각의 필드는 장고의 관리자 싸이트에서 어떻게 보여질지 스스로 알고 + 있습니다. -* Each :class:`~django.db.models.DateTimeField` gets free JavaScript - shortcuts. Dates get a "Today" shortcut and calendar popup, and times get - a "Now" shortcut and a convenient popup that lists commonly entered times. +* 각각의 :class:`~django.db.models.DateTimeField` 에는 간편한 JavaScript + 기능이 제공됩니다. 날짜는 "Today" 바로입력과 달력 팝업이 제공되며, 시간에는 + "Now" 바로입력과 일반적으로 시간 입력에 사용되는 간편한 팝업이 제공됩니다. -The bottom part of the page gives you a couple of options: +페이지 하단에는 몇가지 옵션을 제공합니다: -* Save -- Saves changes and returns to the change-list page for this type of - object. +* Save -- 변경사항을 저장하고 현재 객체 타입의 변경된 목록 페이지를 + 보여줍니다. -* Save and continue editing -- Saves changes and reloads the admin page for - this object. +* Save and continue editing -- 변경사항을 저장하고 현 객체의 관리 페이지를 + 다시 보여줍니다. -* Save and add another -- Saves changes and loads a new, blank form for this - type of object. +* Save and add another -- 변경사항을 저장하고 현재 객체 타입의 신규 정보를 등록할 수 있는 + 비어있는 폼을 보여줍니다. -* Delete -- Displays a delete confirmation page. +* Delete -- 삭제 확인 페이지를 보여줍니다. If the value of "Date published" doesn't match the time when you created the poll in Tutorial 1, it probably means you forgot to set the correct value for @@ -325,7 +319,7 @@ Now that the Poll admin page is looking good, let's make some tweaks to the Here's what it looks like at this point: .. image:: _images/admin04t.png - :alt: Polls change list page + :alt: Poll 변경 리스트 페이지 By default, Django displays the ``str()`` of each object. But sometimes it'd be more helpful if we could display individual fields. To do that, use the From 6b53b5136a10e99fafcf1526332f12c328d5b935 Mon Sep 17 00:00:00 2001 From: shchoi Date: Mon, 6 Aug 2012 01:49:05 +0900 Subject: [PATCH 013/128] some modifications --- intro/tutorial02.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/intro/tutorial02.txt b/intro/tutorial02.txt index 5210f81..2f4941c 100644 --- a/intro/tutorial02.txt +++ b/intro/tutorial02.txt @@ -14,7 +14,7 @@ "컨텐츠 발행인"과 "공개" 사이트를 완벽히 분리하였습니. 사이트 관리자들은 새로운 스토리나 이벤트, 스포츠 점수 결과 등을 추가하기 위해 시스템을 이용하며, 이런 컨텐츠들은 공개 사이트에 노출됩니다. 장고는 사이트 관리자들이 컨텐츠를 수정할 수 있는 - 통합 인터페이스를 제공함으로서 문제를 해결합니다다. + 통합 인터페이스를 제공함으로서 문제를 해결합니다. 관리자 사이트는 사이트 방문자를 위한 것이 아닙니다. 이는 관리자들을 위한 것 입니다. @@ -144,7 +144,7 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: 기능이 제공됩니다. 날짜는 "Today" 바로입력과 달력 팝업이 제공되며, 시간에는 "Now" 바로입력과 일반적으로 시간 입력에 사용되는 간편한 팝업이 제공됩니다. -페이지 하단에는 몇가지 옵션을 제공합니다: +페이지 하단에는 몇가지 옵션이 제공됩니다: * Save -- 변경사항을 저장하고 현재 객체 타입의 변경된 목록 페이지를 보여줍니다. From 9c4c28018be2a0b8ce1aa9ad58ae599768b36f36 Mon Sep 17 00:00:00 2001 From: seok woojing Date: Tue, 7 Aug 2012 01:36:50 +0900 Subject: [PATCH 014/128] overview commit test and little translation. --- intro/overview.txt | 639 ++++++++++++++++++++++----------------------- 1 file changed, 315 insertions(+), 324 deletions(-) diff --git a/intro/overview.txt b/intro/overview.txt index 4f97fef..93ef758 100644 --- a/intro/overview.txt +++ b/intro/overview.txt @@ -1,324 +1,315 @@ -================== -Django at a glance -================== - -Because Django was developed in a fast-paced newsroom environment, it was -designed to make common Web-development tasks fast and easy. Here's an informal -overview of how to write a database-driven Web app with Django. - -The goal of this document is to give you enough technical specifics to -understand how Django works, but this isn't intended to be a tutorial or -reference -- but we've got both! When you're ready to start a project, you can -:doc:`start with the tutorial ` or :doc:`dive right into more -detailed documentation `. - -Design your model -================= - -Although you can use Django without a database, it comes with an -object-relational mapper in which you describe your database layout in Python -code. - -The :doc:`data-model syntax ` offers many rich ways of -representing your models -- so far, it's been solving two years' worth of -database-schema problems. Here's a quick example, which might be saved in -the file ``mysite/news/models.py``:: - - class Reporter(models.Model): - full_name = models.CharField(max_length=70) - - def __unicode__(self): - return self.full_name - - class Article(models.Model): - pub_date = models.DateTimeField() - headline = models.CharField(max_length=200) - content = models.TextField() - reporter = models.ForeignKey(Reporter) - - def __unicode__(self): - return self.headline - -Install it -========== - -Next, run the Django command-line utility to create the database tables -automatically: - -.. code-block:: bash - - manage.py syncdb - -The :djadmin:`syncdb` command looks at all your available models and creates -tables in your database for whichever tables don't already exist. - -Enjoy the free API -================== - -With that, you've got a free, and rich, :doc:`Python API ` to -access your data. The API is created on the fly, no code generation necessary:: - - # Import the models we created from our "news" app - >>> from news.models import Reporter, Article - - # No reporters are in the system yet. - >>> Reporter.objects.all() - [] - - # Create a new Reporter. - >>> r = Reporter(full_name='John Smith') - - # Save the object into the database. You have to call save() explicitly. - >>> r.save() - - # Now it has an ID. - >>> r.id - 1 - - # Now the new reporter is in the database. - >>> Reporter.objects.all() - [] - - # Fields are represented as attributes on the Python object. - >>> r.full_name - 'John Smith' - - # Django provides a rich database lookup API. - >>> Reporter.objects.get(id=1) - - >>> Reporter.objects.get(full_name__startswith='John') - - >>> Reporter.objects.get(full_name__contains='mith') - - >>> Reporter.objects.get(id=2) - Traceback (most recent call last): - ... - DoesNotExist: Reporter matching query does not exist. - - # Create an article. - >>> from datetime import datetime - >>> a = Article(pub_date=datetime.now(), headline='Django is cool', - ... content='Yeah.', reporter=r) - >>> a.save() - - # Now the article is in the database. - >>> Article.objects.all() - [] - - # Article objects get API access to related Reporter objects. - >>> r = a.reporter - >>> r.full_name - 'John Smith' - - # And vice versa: Reporter objects get API access to Article objects. - >>> r.article_set.all() - [] - - # The API follows relationships as far as you need, performing efficient - # JOINs for you behind the scenes. - # This finds all articles by a reporter whose name starts with "John". - >>> Article.objects.filter(reporter__full_name__startswith="John") - [] - - # Change an object by altering its attributes and calling save(). - >>> r.full_name = 'Billy Goat' - >>> r.save() - - # Delete an object with delete(). - >>> r.delete() - -A dynamic admin interface: it's not just scaffolding -- it's the whole house -============================================================================ - -Once your models are defined, Django can automatically create a professional, -production ready :doc:`administrative interface ` -- a Web -site that lets authenticated users add, change and delete objects. It's as easy -as registering your model in the admin site:: - - # In models.py... - - from django.db import models - - class Article(models.Model): - pub_date = models.DateTimeField() - headline = models.CharField(max_length=200) - content = models.TextField() - reporter = models.ForeignKey(Reporter) - - - # In admin.py in the same directory... - - import models - from django.contrib import admin - - admin.site.register(models.Article) - -The philosophy here is that your site is edited by a staff, or a client, or -maybe just you -- and you don't want to have to deal with creating backend -interfaces just to manage content. - -One typical workflow in creating Django apps is to create models and get the -admin sites up and running as fast as possible, so your staff (or clients) can -start populating data. Then, develop the way data is presented to the public. - -Design your URLs -================ - -A clean, elegant URL scheme is an important detail in a high-quality Web -application. Django encourages beautiful URL design and doesn't put any cruft -in URLs, like ``.php`` or ``.asp``. - -To design URLs for an app, you create a Python module called a :doc:`URLconf -`. A table of contents for your app, it contains a simple mapping -between URL patterns and Python callback functions. URLconfs also serve to -decouple URLs from Python code. - -Here's what a URLconf might look like for the ``Reporter``/``Article`` -example above:: - - from django.conf.urls import patterns, url, include - - urlpatterns = patterns('', - (r'^articles/(\d{4})/$', 'news.views.year_archive'), - (r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'), - (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'), - ) - -The code above maps URLs, as simple regular expressions, to the location of -Python callback functions ("views"). The regular expressions use parenthesis to -"capture" values from the URLs. When a user requests a page, Django runs -through each pattern, in order, and stops at the first one that matches the -requested URL. (If none of them matches, Django calls a special-case 404 view.) -This is blazingly fast, because the regular expressions are compiled at load -time. - -Once one of the regexes matches, Django imports and calls the given view, which -is a simple Python function. Each view gets passed a request object -- -which contains request metadata -- and the values captured in the regex. - -For example, if a user requested the URL "/articles/2005/05/39323/", Django -would call the function ``news.views.article_detail(request, -'2005', '05', '39323')``. - -Write your views -================ - -Each view is responsible for doing one of two things: Returning an -:class:`~django.http.HttpResponse` object containing the content for the -requested page, or raising an exception such as :class:`~django.http.Http404`. -The rest is up to you. - -Generally, a view retrieves data according to the parameters, loads a template -and renders the template with the retrieved data. Here's an example view for -``year_archive`` from above:: - - def year_archive(request, year): - a_list = Article.objects.filter(pub_date__year=year) - return render_to_response('news/year_archive.html', {'year': year, 'article_list': a_list}) - -This example uses Django's :doc:`template system `, which has -several powerful features but strives to stay simple enough for non-programmers -to use. - -Design your templates -===================== - -The code above loads the ``news/year_archive.html`` template. - -Django has a template search path, which allows you to minimize redundancy among -templates. In your Django settings, you specify a list of directories to check -for templates. If a template doesn't exist in the first directory, it checks the -second, and so on. - -Let's say the ``news/year_archive.html`` template was found. Here's what that -might look like: - -.. code-block:: html+django - - {% extends "base.html" %} - - {% block title %}Articles for {{ year }}{% endblock %} - - {% block content %} -

Articles for {{ year }}

- - {% for article in article_list %} -

{{ article.headline }}

-

By {{ article.reporter.full_name }}

-

Published {{ article.pub_date|date:"F j, Y" }}

- {% endfor %} - {% endblock %} - -Variables are surrounded by double-curly braces. ``{{ article.headline }}`` -means "Output the value of the article's headline attribute." But dots aren't -used only for attribute lookup: They also can do dictionary-key lookup, index -lookup and function calls. - -Note ``{{ article.pub_date|date:"F j, Y" }}`` uses a Unix-style "pipe" (the "|" -character). This is called a template filter, and it's a way to filter the value -of a variable. In this case, the date filter formats a Python datetime object in -the given format (as found in PHP's date function; yes, there is one good idea -in PHP). - -You can chain together as many filters as you'd like. You can write custom -filters. You can write custom template tags, which run custom Python code behind -the scenes. - -Finally, Django uses the concept of "template inheritance": That's what the -``{% extends "base.html" %}`` does. It means "First load the template called -'base', which has defined a bunch of blocks, and fill the blocks with the -following blocks." In short, that lets you dramatically cut down on redundancy -in templates: each template has to define only what's unique to that template. - -Here's what the "base.html" template might look like: - -.. code-block:: html+django - - - - {% block title %}{% endblock %} - - - Logo - {% block content %}{% endblock %} - - - -Simplistically, it defines the look-and-feel of the site (with the site's logo), -and provides "holes" for child templates to fill. This makes a site redesign as -easy as changing a single file -- the base template. - -It also lets you create multiple versions of a site, with different base -templates, while reusing child templates. Django's creators have used this -technique to create strikingly different cell-phone editions of sites -- simply -by creating a new base template. - -Note that you don't have to use Django's template system if you prefer another -system. While Django's template system is particularly well-integrated with -Django's model layer, nothing forces you to use it. For that matter, you don't -have to use Django's database API, either. You can use another database -abstraction layer, you can read XML files, you can read files off disk, or -anything you want. Each piece of Django -- models, views, templates -- is -decoupled from the next. - -This is just the surface -======================== - -This has been only a quick overview of Django's functionality. Some more useful -features: - -* A :doc:`caching framework ` that integrates with memcached - or other backends. - -* A :doc:`syndication framework ` that makes - creating RSS and Atom feeds as easy as writing a small Python class. - -* More sexy automatically-generated admin features -- this overview barely - scratched the surface. - -The next obvious steps are for you to `download Django`_, read :doc:`the -tutorial ` and join `the community`_. Thanks for your -interest! - -.. _download Django: https://www.djangoproject.com/download/ -.. _the community: https://www.djangoproject.com/community/ +================= +장고 한눈에 살펴보기 +================= + +장고는 빠른 페이스의 뉴스룸 환경에서 개발되었기 때문에 일반적인 웹개발 작업을 빠르고 쉽게 하도록 디자인 되었습니다. 이것은 장고로 데이터베이스 기반의 웹 어플리케이션을 작성하는 것 에 대한 간략한 개요입니다. + +이 문서의 목표는 장고가 어떻게 동작하는지 이해하는데 충분한 기술적 세부 사항을 전달하는 것 입니다. 이것은 튜터리얼이나 레퍼런스를 대신할수는 없습니다. 하지만 우린 그 두가지를 다 가지고 있지요! 프로젝트를 시작할 준비가 되었으면 :doc:`튜터리얼로 시작 ` 하거나 :doc:`좀더 세부적인 문서 `\ 로 곧장 뛰어들수 있습니다. + +모델 설계 +======== + +장고를 데이터베이스 없이 사용할수는 있어도 어쨋든 파이썬 코드로 데이터베이스 레이아웃을 설명하는 객체 관계 매퍼(ORM)이 제공됩니다. + +:doc:`데이터-모델 문법 `\ 은 모델을 표현할수 있는 풍부한 방법을 +제공합니다. -- so far, it's been solving two years' worth of +database-schema problems. ``mysite/news/models.py`` 정도로 저장할만한 간단한 예제 입니다. :: + + class Reporter(models.Model): + full_name = models.CharField(max_length=70) + + def __unicode__(self): + return self.full_name + + class Article(models.Model): + pub_date = models.DateTimeField() + headline = models.CharField(max_length=200) + content = models.TextField() + reporter = models.ForeignKey(Reporter) + + def __unicode__(self): + return self.headline + +설치하기 +========== + +Next, run the Django command-line utility to create the database tables +automatically: + +.. code-block:: bash + + manage.py syncdb + +The :djadmin:`syncdb` command looks at all your available models and creates +tables in your database for whichever tables don't already exist. + +Enjoy the free API +================== + +With that, you've got a free, and rich, :doc:`Python API ` to +access your data. The API is created on the fly, no code generation necessary:: + + # Import the models we created from our "news" app + >>> from news.models import Reporter, Article + + # No reporters are in the system yet. + >>> Reporter.objects.all() + [] + + # Create a new Reporter. + >>> r = Reporter(full_name='John Smith') + + # Save the object into the database. You have to call save() explicitly. + >>> r.save() + + # Now it has an ID. + >>> r.id + 1 + + # Now the new reporter is in the database. + >>> Reporter.objects.all() + [] + + # Fields are represented as attributes on the Python object. + >>> r.full_name + 'John Smith' + + # Django provides a rich database lookup API. + >>> Reporter.objects.get(id=1) + + >>> Reporter.objects.get(full_name__startswith='John') + + >>> Reporter.objects.get(full_name__contains='mith') + + >>> Reporter.objects.get(id=2) + Traceback (most recent call last): + ... + DoesNotExist: Reporter matching query does not exist. + + # Create an article. + >>> from datetime import datetime + >>> a = Article(pub_date=datetime.now(), headline='Django is cool', + ... content='Yeah.', reporter=r) + >>> a.save() + + # Now the article is in the database. + >>> Article.objects.all() + [] + + # Article objects get API access to related Reporter objects. + >>> r = a.reporter + >>> r.full_name + 'John Smith' + + # And vice versa: Reporter objects get API access to Article objects. + >>> r.article_set.all() + [] + + # The API follows relationships as far as you need, performing efficient + # JOINs for you behind the scenes. + # This finds all articles by a reporter whose name starts with "John". + >>> Article.objects.filter(reporter__full_name__startswith="John") + [] + + # Change an object by altering its attributes and calling save(). + >>> r.full_name = 'Billy Goat' + >>> r.save() + + # Delete an object with delete(). + >>> r.delete() + +A dynamic admin interface: it's not just scaffolding -- it's the whole house +============================================================================ + +Once your models are defined, Django can automatically create a professional, +production ready :doc:`administrative interface ` -- a Web +site that lets authenticated users add, change and delete objects. It's as easy +as registering your model in the admin site:: + + # In models.py... + + from django.db import models + + class Article(models.Model): + pub_date = models.DateTimeField() + headline = models.CharField(max_length=200) + content = models.TextField() + reporter = models.ForeignKey(Reporter) + + + # In admin.py in the same directory... + + import models + from django.contrib import admin + + admin.site.register(models.Article) + +The philosophy here is that your site is edited by a staff, or a client, or +maybe just you -- and you don't want to have to deal with creating backend +interfaces just to manage content. + +One typical workflow in creating Django apps is to create models and get the +admin sites up and running as fast as possible, so your staff (or clients) can +start populating data. Then, develop the way data is presented to the public. + +Design your URLs +================ + +A clean, elegant URL scheme is an important detail in a high-quality Web +application. Django encourages beautiful URL design and doesn't put any cruft +in URLs, like ``.php`` or ``.asp``. + +To design URLs for an app, you create a Python module called a :doc:`URLconf +`. A table of contents for your app, it contains a simple mapping +between URL patterns and Python callback functions. URLconfs also serve to +decouple URLs from Python code. + +Here's what a URLconf might look like for the ``Reporter``/``Article`` +example above:: + + from django.conf.urls import patterns, url, include + + urlpatterns = patterns('', + (r'^articles/(\d{4})/$', 'news.views.year_archive'), + (r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'), + (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'), + ) + +The code above maps URLs, as simple regular expressions, to the location of +Python callback functions ("views"). The regular expressions use parenthesis to +"capture" values from the URLs. When a user requests a page, Django runs +through each pattern, in order, and stops at the first one that matches the +requested URL. (If none of them matches, Django calls a special-case 404 view.) +This is blazingly fast, because the regular expressions are compiled at load +time. + +Once one of the regexes matches, Django imports and calls the given view, which +is a simple Python function. Each view gets passed a request object -- +which contains request metadata -- and the values captured in the regex. + +For example, if a user requested the URL "/articles/2005/05/39323/", Django +would call the function ``news.views.article_detail(request, +'2005', '05', '39323')``. + +Write your views +================ + +Each view is responsible for doing one of two things: Returning an +:class:`~django.http.HttpResponse` object containing the content for the +requested page, or raising an exception such as :class:`~django.http.Http404`. +The rest is up to you. + +Generally, a view retrieves data according to the parameters, loads a template +and renders the template with the retrieved data. Here's an example view for +``year_archive`` from above:: + + def year_archive(request, year): + a_list = Article.objects.filter(pub_date__year=year) + return render_to_response('news/year_archive.html', {'year': year, 'article_list': a_list}) + +This example uses Django's :doc:`template system `, which has +several powerful features but strives to stay simple enough for non-programmers +to use. + +Design your templates +===================== + +The code above loads the ``news/year_archive.html`` template. + +Django has a template search path, which allows you to minimize redundancy among +templates. In your Django settings, you specify a list of directories to check +for templates. If a template doesn't exist in the first directory, it checks the +second, and so on. + +Let's say the ``news/year_archive.html`` template was found. Here's what that +might look like: + +.. code-block:: html+django + + {% extends "base.html" %} + + {% block title %}Articles for {{ year }}{% endblock %} + + {% block content %} +

Articles for {{ year }}

+ + {% for article in article_list %} +

{{ article.headline }}

+

By {{ article.reporter.full_name }}

+

Published {{ article.pub_date|date:"F j, Y" }}

+ {% endfor %} + {% endblock %} + +Variables are surrounded by double-curly braces. ``{{ article.headline }}`` +means "Output the value of the article's headline attribute." But dots aren't +used only for attribute lookup: They also can do dictionary-key lookup, index +lookup and function calls. + +Note ``{{ article.pub_date|date:"F j, Y" }}`` uses a Unix-style "pipe" (the "|" +character). This is called a template filter, and it's a way to filter the value +of a variable. In this case, the date filter formats a Python datetime object in +the given format (as found in PHP's date function; yes, there is one good idea +in PHP). + +You can chain together as many filters as you'd like. You can write custom +filters. You can write custom template tags, which run custom Python code behind +the scenes. + +Finally, Django uses the concept of "template inheritance": That's what the +``{% extends "base.html" %}`` does. It means "First load the template called +'base', which has defined a bunch of blocks, and fill the blocks with the +following blocks." In short, that lets you dramatically cut down on redundancy +in templates: each template has to define only what's unique to that template. + +Here's what the "base.html" template might look like: + +.. code-block:: html+django + + + + {% block title %}{% endblock %} + + + Logo + {% block content %}{% endblock %} + + + +Simplistically, it defines the look-and-feel of the site (with the site's logo), +and provides "holes" for child templates to fill. This makes a site redesign as +easy as changing a single file -- the base template. + +It also lets you create multiple versions of a site, with different base +templates, while reusing child templates. Django's creators have used this +technique to create strikingly different cell-phone editions of sites -- simply +by creating a new base template. + +Note that you don't have to use Django's template system if you prefer another +system. While Django's template system is particularly well-integrated with +Django's model layer, nothing forces you to use it. For that matter, you don't +have to use Django's database API, either. You can use another database +abstraction layer, you can read XML files, you can read files off disk, or +anything you want. Each piece of Django -- models, views, templates -- is +decoupled from the next. + +This is just the surface +======================== + +This has been only a quick overview of Django's functionality. Some more useful +features: + +* A :doc:`caching framework ` that integrates with memcached + or other backends. + +* A :doc:`syndication framework ` that makes + creating RSS and Atom feeds as easy as writing a small Python class. + +* More sexy automatically-generated admin features -- this overview barely + scratched the surface. + +The next obvious steps are for you to `download Django`_, read :doc:`the +tutorial ` and join `the community`_. Thanks for your +interest! + +.. _download Django: https://www.djangoproject.com/download/ +.. _the community: https://www.djangoproject.com/community/ From 9c8f704d8eeb4be0a1c16b0988b4b7f1c729f8ec Mon Sep 17 00:00:00 2001 From: shchoi Date: Wed, 8 Aug 2012 01:44:14 +0900 Subject: [PATCH 015/128] Update intro/tutorial02.txt --- intro/tutorial02.txt | 77 ++++++++++++++++++-------------------------- 1 file changed, 32 insertions(+), 45 deletions(-) diff --git a/intro/tutorial02.txt b/intro/tutorial02.txt index 2f4941c..9ffd502 100644 --- a/intro/tutorial02.txt +++ b/intro/tutorial02.txt @@ -1,19 +1,19 @@ ===================================== -첫번째 장고 앱 만들기! part 2 +첫번째 Django 앱 만들기! part 2 ===================================== -본 자습서는 :doc:`Tutorial 1 ` 에 이어 계속됩니다. 앞서 개발한 설문조사 애플리케이션과 함께 장고에서 자동으로 생성되는 관리자 사이트에 대해 알아보도록 하겠습니다. +본 자습서는 :doc:`Tutorial 1 ` 에 이어 계속됩니다. 앞서 개발한 설문조사 애플리케이션과 함께 Django 에서 자동으로 생성되는 관리자 사이트에 대해 알아보도록 하겠습니다. .. admonition:: 철학 관리자나 고객들이 컨텐츠를 추가, 변경, 삭제할 수 있는 관리자 사이트를 생성하는 것은 그다지 창조적이지 않은 지루한 작업 입니다. 이러한 작업을 - 위해서 장고는 모델을 위한 관리자 인터페이스 생성을 완전히 자동화 하였습니다. + 위해서 Django 는 모델을 위한 관리자 인터페이스 생성을 완전히 자동화 하였습니다. - 장고는 뉴스를 준비하는 환경을 위해 만들어졌으며, + Django 는 뉴스를 준비하는 환경을 위해 만들어졌으며, "컨텐츠 발행인"과 "공개" 사이트를 완벽히 분리하였습니. 사이트 관리자들은 새로운 스토리나 이벤트, 스포츠 점수 결과 등을 추가하기 위해 시스템을 이용하며, - 이런 컨텐츠들은 공개 사이트에 노출됩니다. 장고는 사이트 관리자들이 컨텐츠를 수정할 수 있는 + 이런 컨텐츠들은 공개 사이트에 노출됩니다. Django 는 사이트 관리자들이 컨텐츠를 수정할 수 있는 통합 인터페이스를 제공함으로서 문제를 해결합니다. 관리자 사이트는 사이트 방문자를 위한 것이 아닙니다. 이는 @@ -72,7 +72,7 @@ http://127.0.0.1:8000/admin/. 관리자 사이트의 로그인 화면을 볼 수 있을 것 입니다: .. image:: _images/admin01.png - :alt: 장고 관리자 사이트 로그인 화면 + :alt: Django 관리자 사이트 로그인 화면 .. admonition:: 여러분에게 보이는 페이지와 다른가요? @@ -83,9 +83,9 @@ http://127.0.0.1:8000/admin/. 관리자 사이트의 로그인 화면을 볼 수 cannot import name patterns ... - 여러분이 사용하시는 장고의 버젼이 본 자습서의 버젼과 - 맞지 않을 수 있습니다. 사용하시는 장고 버젼에 맞는 자습서를 참고 하거나, - 새로운 버젼의 장고를 사용하시기 바랍니다. + 여러분이 사용하시는 Django 의 버젼이 본 자습서의 버젼과 + 맞지 않을 수 있습니다. 사용하시는 Django 버젼에 맞는 자습서를 참고 하거나, + 새로운 버젼의 Django 를 사용하시기 바랍니다. 관리자 사이트 들어가기 ==================== @@ -93,9 +93,9 @@ http://127.0.0.1:8000/admin/. 관리자 사이트의 로그인 화면을 볼 수 자, 이제 로그인 해 보세요. (첫번째 자습서에서 최고 관리자 계정을 생성한 것을 기억 하시나요? 만약 생성하지 않았거나, 비밀번호가 기억나지 않는다면 :ref:`다른 계정을 생성` 해 보세요.) 장고 관리자 사이트의 초기 페이지를 확인할 수 있을 것 입니다: .. image:: _images/admin02t.png - :alt: 장고 관리자 사이트 초기 페이지 + :alt: Django 관리자 사이트 초기 페이지 -Groups, users, sites 등 몇 개의 수정 가능한 컨텐츠를 확인할 수 있는데, 이들은 장고에서 기본적으로 제공하는 핵심 기능 입니다. +Groups, users, sites 등 몇 개의 수정 가능한 컨텐츠를 확인할 수 있는데, 이들은 Django 에서 기본적으로 제공하는 핵심 기능 입니다. 관리자 사이트에서 수정 가능한 설문조사 앱 만들기 ========================================= @@ -103,7 +103,7 @@ Groups, users, sites 등 몇 개의 수정 가능한 컨텐츠를 확인할 수 그러데 우리의 설문조사 앱은 어디에 있나요?아직 관리자 사이트 초기 페이지에 보이지 않습니다. 단 한가지 할 일: 우선 관리자 사이트에게 ``Poll`` -오브젝트가 관리자 인터페이스가 필요하다고 알려줘야 합니다. 이를 위해 ``polls`` 디렉토리 안에 ``admin.py`` 파일을 생성하고 아래와 같이 수정합니다:: +개체가 관리자 인터페이스가 필요하다고 알려줘야 합니다. 이를 위해 ``polls`` 디렉토리 안에 ``admin.py`` 파일을 생성하고 아래와 같이 수정합니다:: from polls.models import Poll from django.contrib import admin @@ -115,10 +115,10 @@ Groups, users, sites 등 몇 개의 수정 가능한 컨텐츠를 확인할 수 무료 관리 기능 탐험하기 ==================================== -자, 이제 ``Poll`` 이 등록되었고, 장고는 ``Poll`` 을 관리 사이트 초기 페이지에 보여줘야 함을 알고 있습니다: +자, 이제 ``Poll`` 이 등록되었고, Django 는 ``Poll`` 을 관리 사이트 초기 페이지에 보여줘야 함을 알고 있습니다: .. image:: _images/admin03t.png - :alt: polls가 보여지는 장고 관리자 사이트 초기 페이지 + :alt: polls가 보여지는 Django 관리자 사이트 초기 페이지 이제 "Polls."를 클릭하면 polls의 "change list" 를 볼 수 있습니다. 이 페이지에서는 데이터베이스의 모든 poll이 보여지게 되며 이중 한개를 선택하여 변경할 수 있습니다. 여기에 우리가 첫 번째 자습서에서 생성한 "What's up?" poll을 확인할 수 있습니다: @@ -129,7 +129,7 @@ Groups, users, sites 등 몇 개의 수정 가능한 컨텐츠를 확인할 수 Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: .. image:: _images/admin05t.png - :alt: Poll 객체 수정 폼 + :alt: Poll 개체 수정 폼 여기서 짚고 넘어가기: @@ -146,62 +146,49 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: 페이지 하단에는 몇가지 옵션이 제공됩니다: -* Save -- 변경사항을 저장하고 현재 객체 타입의 변경된 목록 페이지를 +* Save -- 변경사항을 저장하고 현재 개체 타입의 변경된 목록 페이지를 보여줍니다. -* Save and continue editing -- 변경사항을 저장하고 현 객체의 관리 페이지를 +* Save and continue editing -- 변경사항을 저장하고 현 개체의 관리 페이지를 다시 보여줍니다. -* Save and add another -- 변경사항을 저장하고 현재 객체 타입의 신규 정보를 등록할 수 있는 +* Save and add another -- 변경사항을 저장하고 현재 개체 타입의 신규 정보를 등록할 수 있는 비어있는 폼을 보여줍니다. * Delete -- 삭제 확인 페이지를 보여줍니다. -If the value of "Date published" doesn't match the time when you created the -poll in Tutorial 1, it probably means you forgot to set the correct value for -the :setting:`TIME_ZONE` setting. Change it, reload the page and check that -the correct value appears. +만약 "Date published" 의 시간이 여러분이 자습서 1에서 poll을 생성한 시간과 맞지 않는다면 +정확한 :setting:`TIME_ZONE` 설정하지 않았기 때문 일 수 있습니다. 값을 정확히 입력하고 페이지를 다시 읽어들이면 +정확한 값이 보여지는 것을 확인할 수 있을 것입니다. -Change the "Date published" by clicking the "Today" and "Now" shortcuts. Then -click "Save and continue editing." Then click "History" in the upper right. -You'll see a page listing all changes made to this object via the Django admin, -with the timestamp and username of the person who made the change: +"Today" 와 "Now" 바로입력 버튼을 누르면 "Date published"의 정보를 바꿀 수 있습니다. 그리고 "Save and continue editing." 를 클릭한 후 오른쪽 위의 "History" 를 클릭 해 보세요. +이 페이지 에서는 Django 관리 사이트에서 이루어진 현 개체의 모든 변경 사항의 목록을 확인할 수 있으며, 수정 시간과 수정을 한 사용자 이름도 확인할 수 있습니다.: .. image:: _images/admin06t.png - :alt: History page for poll object + :alt: Poll 개체의 History 페이지 -Customize the admin form +관리자 싸이트 폼 커스터마이즈 하기 ======================== -Take a few minutes to marvel at all the code you didn't have to write. By -registering the Poll model with ``admin.site.register(Poll)``, Django was able -to construct a default form representation. Often, you'll want to customize how -the admin form looks and works. You'll do this by telling Django the options -you want when you register the object. +단지 몇분동안 코드를 살펴보며 감탄한 것 처럼 여러분은 코드를 작성 할 필요가 없습니다. 단지 Poll 모델과 ``admin.site.register(Poll)`` 을 등록 하는 것 만으로, Django는 기본적인 폼의 외형을 생성할 수 있었습니다. 때때로 여러분은 관리자 싸이트 폼의 외형과 작업을 커스터마이즈 해야 할 필요가 있을 것 입니다. 이는 여러분이 개채를 등록할 때 필요한 옵션을 Django 에게 알려주면 됩니다.. -Let's see how this works by re-ordering the fields on the edit form. Replace -the ``admin.site.register(Poll)`` line with:: +수정 폼의 필드를 재 정렬 하는 예제를 통해서 어떻게 커스터마이즈 할 수 있는지 알아봅시다. ``admin.site.register(Poll)`` 라인을 아래와 같이 수정 해 봅시다.:: class PollAdmin(admin.ModelAdmin): fields = ['pub_date', 'question'] admin.site.register(Poll, PollAdmin) -You'll follow this pattern -- create a model admin object, then pass it as the -second argument to ``admin.site.register()`` -- any time you need to change the -admin options for an object. +여러분은 위와 같은 패턴 -- Model admin 개체 생성, ``admin.site.register()`` 의 두번째 인자로 전달 -- 을 통해 언제든 개체의 관리 싸이트 옵션을 변경할 수 있습니다. -This particular change above makes the "Publication date" come before the -"Question" field: +이번 예제는 "Publication date" 필드가 "Question" 필드의 앞에 오도록 수정하였습니다.: .. image:: _images/admin07.png - :alt: Fields have been reordered + :alt: 재 정렬된 필드들 -This isn't impressive with only two fields, but for admin forms with dozens -of fields, choosing an intuitive order is an important usability detail. +단지 두 개의 필드에서는 크게 인상적이지 않을 지 모르지만 수십개의 필드가 있는 폼 에서는 직관적인 순서를 선택하는 것이 보다 세세한 사용성 측면에서 중요합니다. -And speaking of forms with dozens of fields, you might want to split the form -up into fieldsets:: +또한 수십개의 필드를 포함한 폼을 다룰 때에는 이들을 폼의 필드셋 으로의 분리가 필요할 수 있습니다.:: class PollAdmin(admin.ModelAdmin): fieldsets = [ From 853a56797b4d47a81494e06bc5aa5044434a799f Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Wed, 8 Aug 2012 22:24:37 +0900 Subject: [PATCH 016/128] translate faq/general --- faq/general.txt | 321 ++++++++++++++++++++---------------------------- 1 file changed, 130 insertions(+), 191 deletions(-) diff --git a/faq/general.txt b/faq/general.txt index cfd0a3e..3e7a6ed 100644 --- a/faq/general.txt +++ b/faq/general.txt @@ -1,191 +1,130 @@ -FAQ: General -============ - -Why does this project exist? ----------------------------- - -Django grew from a very practical need: World Online, a newspaper Web -operation, is responsible for building intensive Web applications on journalism -deadlines. In the fast-paced newsroom, World Online often has only a matter of -hours to take a complicated Web application from concept to public launch. - -At the same time, the World Online Web developers have consistently been -perfectionists when it comes to following best practices of Web development. - -In fall 2003, the World Online developers (Adrian Holovaty and Simon Willison) -ditched PHP and began using Python to develop its Web sites. As they built -intensive, richly interactive sites such as Lawrence.com, they began to extract -a generic Web development framework that let them build Web applications more -and more quickly. They tweaked this framework constantly, adding improvements -over two years. - -In summer 2005, World Online decided to open-source the resulting software, -Django. Django would not be possible without a whole host of open-source -projects -- `Apache`_, `Python`_, and `PostgreSQL`_ to name a few -- and we're -thrilled to be able to give something back to the open-source community. - -.. _Apache: http://httpd.apache.org/ -.. _Python: http://www.python.org/ -.. _PostgreSQL: http://www.postgresql.org/ - -What does "Django" mean, and how do you pronounce it? ------------------------------------------------------ - -Django is named after `Django Reinhardt`_, a gypsy jazz guitarist from the 1930s -to early 1950s. To this day, he's considered one of the best guitarists of all time. - -Listen to his music. You'll like it. - -Django is pronounced **JANG**-oh. Rhymes with FANG-oh. The "D" is silent. - -We've also recorded an `audio clip of the pronunciation`_. - -.. _Django Reinhardt: http://en.wikipedia.org/wiki/Django_Reinhardt -.. _audio clip of the pronunciation: http://red-bean.com/~adrian/django_pronunciation.mp3 - -Is Django stable? ------------------ - -Yes. World Online has been using Django for more than three years. Sites built -on Django have weathered traffic spikes of over one million hits an hour and a -number of Slashdottings. Yes, it's quite stable. - -Does Django scale? ------------------- - -Yes. Compared to development time, hardware is cheap, and so Django is -designed to take advantage of as much hardware as you can throw at it. - -Django uses a "shared-nothing" architecture, which means you can add hardware -at any level -- database servers, caching servers or Web/application servers. - -The framework cleanly separates components such as its database layer and -application layer. And it ships with a simple-yet-powerful -:doc:`cache framework `. - -Who's behind this? ------------------- - -Django was originally developed at World Online, the Web department of a -newspaper in Lawrence, Kansas, USA. Django's now run by an international team of -volunteers; you can read all about them over at the :doc:`list of committers -` - -Which sites use Django? ------------------------ - -`DjangoSites.org`_ features a constantly growing list of Django-powered sites. - -.. _DjangoSites.org: http://djangosites.org - -.. _faq-mtv: - -Django appears to be a MVC framework, but you call the Controller the "view", and the View the "template". How come you don't use the standard names? ------------------------------------------------------------------------------------------------------------------------------------------------------ - -Well, the standard names are debatable. - -In our interpretation of MVC, the "view" describes the data that gets presented -to the user. It's not necessarily *how* the data *looks*, but *which* data is -presented. The view describes *which data you see*, not *how you see it.* It's -a subtle distinction. - -So, in our case, a "view" is the Python callback function for a particular URL, -because that callback function describes which data is presented. - -Furthermore, it's sensible to separate content from presentation -- which is -where templates come in. In Django, a "view" describes which data is presented, -but a view normally delegates to a template, which describes *how* the data is -presented. - -Where does the "controller" fit in, then? In Django's case, it's probably the -framework itself: the machinery that sends a request to the appropriate view, -according to the Django URL configuration. - -If you're hungry for acronyms, you might say that Django is a "MTV" framework --- that is, "model", "template", and "view." That breakdown makes much more -sense. - -At the end of the day, of course, it comes down to getting stuff done. And, -regardless of how things are named, Django gets stuff done in a way that's most -logical to us. - - does -- why doesn't Django? ------------------------------------------------------ - -We're well aware that there are other awesome Web frameworks out there, and -we're not averse to borrowing ideas where appropriate. However, Django was -developed precisely because we were unhappy with the status quo, so please be -aware that "because does it" is not going to be sufficient reason -to add a given feature to Django. - -Why did you write all of Django from scratch, instead of using other Python libraries? --------------------------------------------------------------------------------------- - -When Django was originally written a couple of years ago, Adrian and Simon -spent quite a bit of time exploring the various Python Web frameworks -available. - -In our opinion, none of them were completely up to snuff. - -We're picky. You might even call us perfectionists. (With deadlines.) - -Over time, we stumbled across open-source libraries that did things we'd -already implemented. It was reassuring to see other people solving similar -problems in similar ways, but it was too late to integrate outside code: We'd -already written, tested and implemented our own framework bits in several -production settings -- and our own code met our needs delightfully. - -In most cases, however, we found that existing frameworks/tools inevitably had -some sort of fundamental, fatal flaw that made us squeamish. No tool fit our -philosophies 100%. - -Like we said: We're picky. - -We've documented our philosophies on the -:doc:`design philosophies page `. - -Is Django a content-management-system (CMS)? --------------------------------------------- - -No, Django is not a CMS, or any sort of "turnkey product" in and of itself. -It's a Web framework; it's a programming tool that lets you build Web sites. - -For example, it doesn't make much sense to compare Django to something like -Drupal_, because Django is something you use to *create* things like Drupal. - -Of course, Django's automatic admin site is fantastic and timesaving -- but -the admin site is one module of Django the framework. Furthermore, although -Django has special conveniences for building "CMS-y" apps, that doesn't mean -it's not just as appropriate for building "non-CMS-y" apps (whatever that -means!). - -.. _Drupal: http://drupal.org/ - -How can I download the Django documentation to read it offline? ---------------------------------------------------------------- - -The Django docs are available in the ``docs`` directory of each Django tarball -release. These docs are in reST (reStructuredText) format, and each text file -corresponds to a Web page on the official Django site. - -Because the documentation is `stored in revision control`_, you can browse -documentation changes just like you can browse code changes. - -Technically, the docs on Django's site are generated from the latest development -versions of those reST documents, so the docs on the Django site may offer more -information than the docs that come with the latest Django release. - -.. _stored in revision control: https://code.djangoproject.com/browser/django/trunk/docs - -Where can I find Django developers for hire? --------------------------------------------- - -Consult our `developers for hire page`_ for a list of Django developers who -would be happy to help you. - -You might also be interested in posting a job to http://djangogigs.com/ . -If you want to find Django-capable people in your local area, try -http://djangopeople.net/ . - -.. _developers for hire page: https://code.djangoproject.com/wiki/DevelopersForHire +FAQ: 일반 +========= + +왜 이 프로젝트가 존재하나요? +---------------------------- + +Django는 매우 실용적인 필요에 의해 만들어졌습니다. 신문사 웹 오퍼레이션인 World Online은 저널리즘 데드라인에 맞추어 집약적인 웹 애플리케이션을 구축하는 책임을 지고 있습니다. 숨가쁘게 돌아가는 뉴스룸에서, World Online은 복잡한 웹 애플리케이션의 구상에서 대외적인 배포까지에 몇 시간이 채 걸리지 않는 경우가 종종 있습니다. + +한편, World Online의 웹 개발자들은 웹 개발의 모범 사례를 지속적이고도 철저하게 따르고 있습니다. + +2003년 가을에 들어, World Online의 개발자(Adrian Holovaty와 Simon Willison)들은 PHP를 버리고 파이썬을 웹 사이트 개발에 사용하기 시작했습니다. 그들은 Lawrence.com과 같이 집약적이고 두터운 상호작용을 하는 사이트를 구축하면서 웹 개발의 일반적인 틀(framework)을 만들어내기 시작했고, 점점 더 빨리 개발을 해나갔습니다. 이 프레임워크를 2년 이상 지속적으로 고치고, 개선하였습니다. + +2005년 여름에 들어, World Online은 그 결과물인 Django를 오픈 소스로 내놓기로 결정했습니다. Django는 `Apache`_, `Python`_, 그리고 `PostgreSQL`_\ 과 같은 오픈 소스 프로젝트 없이는 만들어지지 못했을 것인데, 이것을 다시 오픈 소스 커뮤니티에 환원할 수 있게 되어 기쁩니다. + +.. _Apache: http://httpd.apache.org/ +.. _Python: http://www.python.org/ +.. _PostgreSQL: http://www.postgresql.org/ + +"Django"는 어떤 의미이며, 어떻게 발음하나요? +-------------------------------------------- + +Django는 `Django Reinhardt`_\ 라는 1930년대에서 1950년대 초반에 활동한 집시 재즈 기타리스트의 이름을 딴 것입니다. 오늘날, 그는 최고의 기타리스트 중 한 명으로 불리고 있습니다. + +그의 음악을 들어보신다면 좋아하게 될 겁니다. + +장고는 **JANG**-oh로 발음합니다. FANG-oh와 각운을 이룹니다. "D"는 묵음입니다. + +`발음 듣기`_\ 도 가능합니다. + +.. _Django Reinhardt: http://en.wikipedia.org/wiki/Django_Reinhardt +.. _발음 듣기: http://red-bean.com/~adrian/django_pronunciation.mp3 + +Django는 안정적인가요? +---------------------- + +그렇습니다. World Online는 Django를 삼 년 이상 사용해오고 있습니다. Django로 구축한 사이트는 시간 당 백만 건 이상의 히트와 일시적인 방문자 급증을 견뎌왔습니다. 네, 상당히 안정적입니다. + +Django는 규모변경이 용이한가요? +------------------------------- + +예. 개발 기간에 따른 비용보다는 하드웨어가 값이 싸기 때문에, Django는 하드웨어를 많이 쓸수록 성능이 더 좋아지도록 디자인되었습니다. + +Django는 "shared-nothing" 아키텍처를 채택했는데, 이는 데이터베이스 서버, 캐시 서버 및 웹/애플리케이션 서버 등 어떠한 수준에서도 하드웨어를 추가할 수 있음을 의미합니다. + +프레임워크는 데이터베이스 계층 및 애플리케이션 계층과 같은 구성요소를 깔끔하게 분리하였으며, 간단하면서도 강력한 :doc:`캐시 프레임워크 `\ 를 탑재하였습니다. + +배후에는 누가 있나요? +--------------------- + +Django는 미국 캔사스 주 로렌스의 World Online에서 처음 만들었습니다. 지금은 국제적인 자원봉사 팀에 의해 진행되며 :doc:`커미터 목록 +`\ 에서 그 구성원을 확인하실 수 있습니다. + +어떤 사이트에서 Django를 사용하나요? +------------------------------------ + +`DjangoSites.org`_\ 에 장고로 만들어진 사이트의 목록이 있는데, 계속 길어지고 있습니다. + +.. _DjangoSites.org: http://djangosites.org + +.. _faq-mtv: + +Django는 MVC 프레임워크이면서도, 컨트롤러를 "뷰"라고 부르고, 뷰를 "템플릿"이라고 부릅니다. 왜 표준적인 이름을 사용하지 않는 건가요? +------------------------------------------------------------------------------------------------------------------------------------ + +사실, 표준적인 이름에 대해서는 이론이 있습니다. + +MVC에 대한 우리의 견해에 따르면, "뷰"는 사용자에게 표출되는 자료를 기술합니다. 자료가 *어떻게 보이느냐*\ 가 아니라, *어떤* 자료를 보여줄 것인지가 필수적인 부분입니다. 뷰는 *어느 데이터를 볼 것인지*\ 를 기술하는 것이지, 그것을 *어떻게 볼 것인지*\ 를 기술하는 것이 아닙니다. 이것은 미묘한 차이입니다. + +즉, 우리의 경우에는 "뷰"는 특정 URL에 대한 파이썬 콜백 함수인데, 이는 그러한 콜백 함수가 바로 어느 자료를 보여줄 것인지에 대하여 기술하기 때문입니다. + +더 나아가, 내용과 형식을 분리하는 것은 민감한 부분이며 여기에서 템플릿이 유래합니다. 장고에서는, "뷰"는 어떠한 자료를 보여줄 것인지를 기술하지만, 자료가 *어떻게* 보일 것인가에 대해서는 템플릿에 위임하는 것이 보통입니다. + +그렇다면 "컨트롤러"는 어디에 들어맞는 것일까요? Django에서는 프레임워크 자체, 즉 Django URL 구성에 따라서 적절한 뷰에 대한 요청을 보내는 기계적인 부분이 될 것입니다. + +두문자어를 굳이 만들어내자면, Django는 "MTV" 프레임워크라 하겠습니다. 각각의 대문자는 "model", "template" 그리고 "view"를 나타냅니다. 이러한 얼개가 보다 타당합니다. + +이름이야 어찌됐건 결국 일을 제대로 처리하느냐가 중요한 것이고, Django는 우리에게 있어 가장 논리적인 방법으로 일을 처리해주고 있습니다. + +<프레임워크 X>에는 이 있는데, Django에는 왜 없나요? +----------------------------------------------------------- + +대단한 프레임워크들이 많이 있는 것도 알고 있고, 아이디어를 빌려오는 것을 꺼리지도 않습니다. 하지만 Django는 현 상태에 불만이 있어서 개발을 하는 것이지, "에 좋은 기능이 있기 때문에" Django에도 그러한 기능을 추가해야한다는 것이 기능을 추가해야 할 만한 이유가 되지는 못함을 알아주시기 바랍니다. + +좋은 파이썬 라이브러리를 두고, 굳이 바닥에서부터 Django를 만든 이유가 무엇인가요? +--------------------------------------------------------------------------------- + +몇 년 전에 Django를 처음 만들 때만 해도, Adrian과 Simon은 파이썬에서 사용할 수 있는 다양한 웹 프레임워크를 조사하는 데에 시간을 들였습니다. + +우리가 보기에는, 그 중에 완전히 마음에 드는 것이 없었습니다. + +우리는 까다롭습니다. 혹자는 완벽주의자라고 할 지도 모르겠습니다. + +오픈 소스 라이브러리 가운데는, 우리가 이미 구현한 것들과 같은 것들이 여럿 있었습니다. 이를 통해 다른 사람들도 비슷한 문제를 비슷한 방법으로 해결하려한다는 것을 재확인하였지만, 외부 코드를 통합하기에는 너무 늦어버렸습니다. 우리는 이미 구현과 테스트를 마치고 여러 프로덕션 환경에 구성을 했고, 우리의 코드가 우리가 필요하는 것을 잘 충족시켰습니다. + +하지만 대부분의 경우에, 기존의 프레임워크 및 도구들은 역시나 초보적이고, 견디기 힘든 치명적인 결함을 안고 있었습니다. 우리의 철학에 100% 들어맞는 도구는 없었습니다. + +우리는 까다롭거든요. + +:doc:`디자인 철학 페이지 `\ 에 우리의 철학을 문서로 남겨두었습니다. + +Django는 컨텐트 관리 시스템(CMS)인가요? +--------------------------------------- + +아니오, Django는 CMS가 아닐 뿐더러, 어떠한 종류의 "턴키 제품"도 아닙니다. 웹 프레임워크로서 웹 사이트를 구축할 수 있게 해주는 프로그래밍 도구입니다. + +예컨대, Django를 Drupal_ 등과 비교하는 것은 적절치 못한데, 이는 Django가 Drupal 같은 것을 *만들어내기 위해* 쓰이는 것이기 때문입니다. + +물론 Django에서 자동으로 만들어내는 admin 사이트는 멋지고 시간도 아껴주기는 하지만, admin 사이트는 Django 프레임워크의 일개 모듈에 불과합니다. 게다가, Django가 "CMS-y" 앱 같은 것을 만들어내기에 특별히 편리하다고 해서, 그것이 "비 CMS-y" 앱(그게 뭐가 되었든!)을 만들기에 부적당함을 의미하지는 않습니다. + +.. _Drupal: http://drupal.org/ + +Django 문서를 오프라인으로 읽고 싶은데, 어떻게 다운로드하나요? +-------------------------------------------------------------- + +Django 문서는 Django의 tarball 릴리스의 ``docs`` 디렉토리에 있습니다. 이 문서는 reST(reStructuredText) 형식으로 되어 있으며, 각각의 텍스트 파일은 공식 Django 사이트의 각 페이지에 해당합니다. + +문서는 `리비전 컨트롤에 저장되어 있으므로`_, 코드의 변경사항을 살펴보듯이 문서의 변경사항을 확인할 수 있습니다. + +기술적으로는, Django에 대한 문서는 이러한 reST 문서의 최신 개발 버전으로부터 만들어지므로, Django 사이트에 있는 문서가 최종 Django 릴리스에 있는 것보다 더 많은 정보를 제공할 수도 있습니다. + +.. _리비전 컨트롤에 저장되어 있으므로: https://code.djangoproject.com/browser/django/trunk/docs + +Django 개발자를 고용하고 싶은데 어디에서 찾을 수 있나요? +-------------------------------------------------------- + +`개발자 구직 페이지`_\ 의 Django 개발자 목록을 참고하시기 바랍니다. + +http://djangogigs.com/\ 에 구인 광고를 낼 수도 있습니다. Django를 다룰 수 있는 사람을 지역 내에서 찾고자 한다면, http://djangopeople.net/\ 을 살펴보세요. + +.. _개발자 구직 페이지: https://code.djangoproject.com/wiki/DevelopersForHire From 8bcc24bf45f14aac4d25f8c9c08144d76000340f Mon Sep 17 00:00:00 2001 From: shchoi Date: Sat, 11 Aug 2012 05:09:43 +0900 Subject: [PATCH 017/128] nslation have been finished --- intro/tutorial02.txt | 243 +++++++++++++++---------------------------- 1 file changed, 83 insertions(+), 160 deletions(-) diff --git a/intro/tutorial02.txt b/intro/tutorial02.txt index 9ffd502..d02ad85 100644 --- a/intro/tutorial02.txt +++ b/intro/tutorial02.txt @@ -90,17 +90,17 @@ http://127.0.0.1:8000/admin/. 관리자 사이트의 로그인 화면을 볼 수 관리자 사이트 들어가기 ==================== -자, 이제 로그인 해 보세요. (첫번째 자습서에서 최고 관리자 계정을 생성한 것을 기억 하시나요? 만약 생성하지 않았거나, 비밀번호가 기억나지 않는다면 :ref:`다른 계정을 생성` 해 보세요.) 장고 관리자 사이트의 초기 페이지를 확인할 수 있을 것 입니다: +자, 이제 로그인 해 보세요. (첫번째 자습서에서 최고 관리자 계정을 생성한 것을 기억 하시나요? 만약 생성하지 않았거나, 비밀번호가 기억나지 않는다면 :ref:`다른 계정을 생성` 해 보세요.) 장고 관리자 사이트의 첫 페이지를 확인할 수 있을 것 입니다: .. image:: _images/admin02t.png - :alt: Django 관리자 사이트 초기 페이지 + :alt: Django 관리자 사이트 첫 페이지 Groups, users, sites 등 몇 개의 수정 가능한 컨텐츠를 확인할 수 있는데, 이들은 Django 에서 기본적으로 제공하는 핵심 기능 입니다. 관리자 사이트에서 수정 가능한 설문조사 앱 만들기 ========================================= -그러데 우리의 설문조사 앱은 어디에 있나요?아직 관리자 사이트 초기 페이지에 보이지 않습니다. +그러데 우리의 설문조사 앱은 어디에 있나요?아직 관리자 사이트 첫 페이지에 보이지 않습니다. 단 한가지 할 일: 우선 관리자 사이트에게 ``Poll`` 개체가 관리자 인터페이스가 필요하다고 알려줘야 합니다. 이를 위해 ``polls`` 디렉토리 안에 ``admin.py`` 파일을 생성하고 아래와 같이 수정합니다:: @@ -115,10 +115,10 @@ Groups, users, sites 등 몇 개의 수정 가능한 컨텐츠를 확인할 수 무료 관리 기능 탐험하기 ==================================== -자, 이제 ``Poll`` 이 등록되었고, Django 는 ``Poll`` 을 관리 사이트 초기 페이지에 보여줘야 함을 알고 있습니다: +자, 이제 ``Poll`` 이 등록되었고, Django 는 ``Poll`` 을 관리 사이트 첫 페이지에 보여줘야 함을 알고 있습니다: .. image:: _images/admin03t.png - :alt: polls가 보여지는 Django 관리자 사이트 초기 페이지 + :alt: polls가 보여지는 Django 관리자 사이트 첫 페이지 이제 "Polls."를 클릭하면 polls의 "change list" 를 볼 수 있습니다. 이 페이지에서는 데이터베이스의 모든 poll이 보여지게 되며 이중 한개를 선택하여 변경할 수 있습니다. 여기에 우리가 첫 번째 자습서에서 생성한 "What's up?" poll을 확인할 수 있습니다: @@ -137,7 +137,7 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: * 서로 다른 모델의 필드 타입 (:class:`~django.db.models.DateTimeField`, :class:`~django.db.models.CharField`) 에 따라 적절한 HTML 입력 위젯이 - 보여집니다. 각각의 필드는 장고의 관리자 싸이트에서 어떻게 보여질지 스스로 알고 + 보여집니다. 각각의 필드는 장고의 관리자 사이트에서 어떻게 보여질지 스스로 알고 있습니다. * 각각의 :class:`~django.db.models.DateTimeField` 에는 간편한 JavaScript @@ -167,10 +167,10 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: .. image:: _images/admin06t.png :alt: Poll 개체의 History 페이지 -관리자 싸이트 폼 커스터마이즈 하기 +관리자 사이트 폼 커스터마이즈 하기 ======================== -단지 몇분동안 코드를 살펴보며 감탄한 것 처럼 여러분은 코드를 작성 할 필요가 없습니다. 단지 Poll 모델과 ``admin.site.register(Poll)`` 을 등록 하는 것 만으로, Django는 기본적인 폼의 외형을 생성할 수 있었습니다. 때때로 여러분은 관리자 싸이트 폼의 외형과 작업을 커스터마이즈 해야 할 필요가 있을 것 입니다. 이는 여러분이 개채를 등록할 때 필요한 옵션을 Django 에게 알려주면 됩니다.. +몇분 동안 간단히 코드를 살펴보며 감탄한 것 처럼 여러분은 코드를 작성 할 필요가 없습니다. 단지 Poll 모델과 ``admin.site.register(Poll)`` 을 등록 하는 것 만으로, Django는 기본적인 폼의 외형을 생성할 수 있었습니다. 때때로 여러분은 관리자 사이트 폼의 외형과 작업을 커스터마이즈 해야 할 필요가 있을 것 입니다. 이는 여러분이 개채를 등록할 때 필요한 옵션을 Django 에게 알려주면 됩니다.. 수정 폼의 필드를 재 정렬 하는 예제를 통해서 어떻게 커스터마이즈 할 수 있는지 알아봅시다. ``admin.site.register(Poll)`` 라인을 아래와 같이 수정 해 봅시다.:: @@ -179,7 +179,7 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: admin.site.register(Poll, PollAdmin) -여러분은 위와 같은 패턴 -- Model admin 개체 생성, ``admin.site.register()`` 의 두번째 인자로 전달 -- 을 통해 언제든 개체의 관리 싸이트 옵션을 변경할 수 있습니다. +여러분은 위와 같은 패턴 -- Model admin 개체 생성, ``admin.site.register()`` 의 두번째 인자로 전달 -- 을 통해 언제든 개체의 관리 사이트 옵션을 변경할 수 있습니다. 이번 예제는 "Publication date" 필드가 "Question" 필드의 앞에 오도록 수정하였습니다.: @@ -188,7 +188,7 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: 단지 두 개의 필드에서는 크게 인상적이지 않을 지 모르지만 수십개의 필드가 있는 폼 에서는 직관적인 순서를 선택하는 것이 보다 세세한 사용성 측면에서 중요합니다. -또한 수십개의 필드를 포함한 폼을 다룰 때에는 이들을 폼의 필드셋 으로의 분리가 필요할 수 있습니다.:: +또한 수십개의 필드를 포함한 폼을 다룰 때에는 이들을 폼의 필드셋(fieldsets)으로 분리할 수도 있습니다.:: class PollAdmin(admin.ModelAdmin): fieldsets = [ @@ -198,16 +198,14 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: admin.site.register(Poll, PollAdmin) -The first element of each tuple in ``fieldsets`` is the title of the fieldset. -Here's what our form looks like now: +필드셋의 튜플(tuple)에 있는 각각의 첫 번째 요소는 필드셋의 제목을 의미합니다. +아래에서 우리가 만든 폼이 어떻게 보이는지 확인할 수 있습니다.: .. image:: _images/admin08t.png - :alt: Form has fieldsets now + :alt: 필드셋을 보여주는 폼 -You can assign arbitrary HTML classes to each fieldset. Django provides a -``"collapse"`` class that displays a particular fieldset initially collapsed. -This is useful when you have a long form that contains a number of fields that -aren't commonly used:: +각각의 필드셋에는 여러분이 원하는 HTML 클래스를 할당할 수 있습니다. Django 는 특정 필드셋이 처음에 접혀 있는 모습으로 보여질 수 있도록``"collapse"`` 클래스를 제공합니다. +이는 잘 사용하지 않지만 많은 필드를 가지고 있는 길이가 긴 폼이 있을 때 유용 할 것입니다.:: class PollAdmin(admin.ModelAdmin): fieldsets = [ @@ -216,47 +214,34 @@ aren't commonly used:: ] .. image:: _images/admin09.png - :alt: Fieldset is initially collapsed + :alt: 처음에 접혀있는 필드셋 -Adding related objects +관계가 있는 개체 추가 ====================== -OK, we have our Poll admin page. But a ``Poll`` has multiple ``Choices``, and -the admin page doesn't display choices. +자 이제 우리는 Poll 관리자 페이지를 가지게 됐습니다. 그런데 ``Poll`` 은 여러개의 ``Choices`` 를 포함하고 있는데 관리자 페이지는 Choices를 보여주지 않습니다. -Yet. +아직까지는요. -There are two ways to solve this problem. The first is to register ``Choice`` -with the admin just as we did with ``Poll``. That's easy:: +두 가지 방법을 통해 이 문제를 해결할 수 있습니다. 첫 번째 방법은 관리자 페이지에 ``Poll`` 과 함께 ``Choice`` 를 등록하는 것 입니다. 참 쉽죠?:: from polls.models import Choice admin.site.register(Choice) -Now "Choices" is an available option in the Django admin. The "Add choice" form -looks like this: +자, 이제 Django 관리자 페이지에서 "Choices" 옵션을 사용가능한것을 볼 수 있습니다. 자 이제 아래와 같은 "Add choice" 을 확인할 수 있습니다.: .. image:: _images/admin10.png - :alt: Choice admin page + :alt: Choice 의 관리 페이지 -In that form, the "Poll" field is a select box containing every poll in the -database. Django knows that a :class:`~django.db.models.ForeignKey` should be -represented in the admin as a ```` 박스로 보여져야 한다는 것을 알고 있습니다. 현재 예제 에서는 한개의 Poll만 존재하는 상태 입니다. -Also note the "Add Another" link next to "Poll." Every object with a -``ForeignKey`` relationship to another gets this for free. When you click "Add -Another," you'll get a popup window with the "Add poll" form. If you add a poll -in that window and click "Save," Django will save the poll to the database and -dynamically add it as the selected choice on the "Add choice" form you're -looking at. +"Poll" 다음에 있는 "Add Another" 링크에 주목하세요. 다른 개체에 대한 ``ForeignKey`` 관계를 가지고 있는 모든 개체는 손쉽게 이용할 수 있습니다. "Add Another" 를 클릭하면 "Add poll" 폼이 있는 팝업 윈도우를 볼 수 있습니다. 팝업 윈도우에서 Poll을 추가 하고 "Save" 버튼을 누르면 Django 는 Poll을 데이터베이스에 저장하고 여러분이 보고있는 "Add choice"의 선택된 Choice에 동적으로 추가합니다. -But, really, this is an inefficient way of adding Choice objects to the system. -It'd be better if you could add a bunch of Choices directly when you create the -Poll object. Let's make that happen. +그러나 시스템에 Choice 개체를 추가하는 작업은 비효율적인 작업입니다 . +만약 여러분이 Poll 개체를 만들 때 여러개의 Choice를 추가할 수 있다면 더 좋을 것 입니다. 자, 그럼 어떻게 하는지 알아봅시다. -Remove the ``register()`` call for the Choice model. Then, edit the ``Poll`` -registration code to read:: +Choice 모델을 호출하는 ``register()`` 를 제거하세요. 그런 다음 ``Poll`` 을 불러오기 위해 등록 코드를 수정하세요.:: class ChoiceInline(admin.StackedInline): model = Choice @@ -271,73 +256,55 @@ registration code to read:: admin.site.register(Poll, PollAdmin) -This tells Django: "Choice objects are edited on the Poll admin page. By -default, provide enough fields for 3 choices." +이런 작업은 Django에게 "Choice 개체들이 Poll 관리자 페이지에서 수정됨" 을 알려줍니다. 기본적으로 3개의 충분한 Choice 필드를 제공합니다." -Load the "Add poll" page to see how that looks, you may need to restart your development server: +"Add poll" 페이지를 열어 어떻게 보이는지 확인 해 봅시다. 그 전에 개발 서버를 재 시작 해 주세요.: .. image:: _images/admin11t.png - :alt: Add poll page now has choices on it + :alt: Choice 가 포함된 Poll 페이지 -It works like this: There are three slots for related Choices -- as specified -by ``extra`` -- and each time you come back to the "Change" page for an -already-created object, you get another three extra slots. +이렇게 작동합니다.: 관련된 세개의 슬롯 -- ``extra`` 에 의해 선택된 -- 이 있고 언제든지 생성된 개체의 "수정" 페이지로 되돌아올 수 있으며, 또다른 세개의 추가 슬롯을 사용할 수도 있다. -One small problem, though. It takes a lot of screen space to display all the -fields for entering related Choice objects. For that reason, Django offers a -tabular way of displaying inline related objects; you just need to change -the ``ChoiceInline`` declaration to read:: +한 가자 작은 문제에 대해 생각 해 봅시다. 관련된 Choice 개체를 입력하기 위해 모든 필드가 넓은 공간에 보여지고 있습니다. 이러한 이유로 Django 는 표를 이용하여 연관된 개체를 한 줄로 보여줍니다.; 다른과 같이 ``ChoiceInline`` 를 변경하세요.:: class ChoiceInline(admin.TabularInline): #... -With that ``TabularInline`` (instead of ``StackedInline``), the -related objects are displayed in a more compact, table-based format: +``StackedInline`` 대신에 ``TabularInline`` 을 사용하면 연관된 개체는 보다 간소화 된 표 기반 형식으로 표현됩니다.: .. image:: _images/admin12.png - :alt: Add poll page now has more compact choices + :alt: 보다 간소화된 Choice를 포함한 Poll 추가 페이지 -Customize the admin change list +관리자 페이지의 수정 목록 커스터마이즈 =============================== -Now that the Poll admin page is looking good, let's make some tweaks to the -"change list" page -- the one that displays all the polls in the system. +이제 Poll 관리 페이지가 보기 좋아졌습니다. 다음으로 시스템의 모든 Poll을 보여주는 "변깅 리스트(change list)" 페이지를 수정 해 봅시다. -Here's what it looks like at this point: +현재는 아래와 같이 보입니다.: .. image:: _images/admin04t.png :alt: Poll 변경 리스트 페이지 -By default, Django displays the ``str()`` of each object. But sometimes it'd be -more helpful if we could display individual fields. To do that, use the -``list_display`` admin option, which is a tuple of field names to display, as -columns, on the change list page for the object:: +기본적으로 Django 는 각 개체를 ``str()`` 로 보여줍니다. 그러나 각 필드를 직접 보여주는게 더 효과적일 수도 있습니다. 이를 위해 ``list_display`` 관리 옵션을 사용합니다. ``list_display`` 옵션은 개체의 변경 리스트에서 컬럼 이름으로 사용되는 필드 이름의 튜플로 구성됩니다.:: class PollAdmin(admin.ModelAdmin): # ... list_display = ('question', 'pub_date') -Just for good measure, let's also include the ``was_published_recently`` custom -method from Tutorial 1:: +좋은 지표로 삼기 위해 첫번째 자습서에서 만든 커스텀 메소드인 ``was_published_recently`` 을 포함시켜 봅시다.:: class PollAdmin(admin.ModelAdmin): # ... list_display = ('question', 'pub_date', 'was_published_recently') -Now the poll change list page looks like this: +이제 아래와 같은 Poll 변경 리스트를 확인하실 수 있습니다.: .. image:: _images/admin13t.png - :alt: Polls change list page, updated + :alt: 업데이트 된 Poll 변경 리스트 페이지 -You can click on the column headers to sort by those values -- except in the -case of the ``was_published_recently`` header, because sorting by the output -of an arbitrary method is not supported. Also note that the column header for -``was_published_recently`` is, by default, the name of the method (with -underscores replaced with spaces), and that each line contains the string -representation of the output. +컬럼 값에 따라 정렬하기 위해 컬럼 헤더를 클릭 해 보세요. -- 커스텀 메소드인 ``was_published_recently`` 는 정렬을 지원하지 않습니다. ``was_published_recently`` 의 컬럼 해더는 기본적으로 메소드의 이름으로 포현되며(공백은 밑줄로 대체) 각 컬럼은 문자열로 표현되게 됩니다. -You can improve that by giving that method (in ``models.py``) a few -attributes, as follows:: +여러분은 아래와 같이 ``models.py`` 에 있는 몇 개의 어트리뷰트를 변경하여 보다 보기 좋게 만들 수 있습니다.:: class Poll(models.Model): # ... @@ -347,116 +314,72 @@ attributes, as follows:: was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' -Edit your admin.py file again and add an improvement to the Poll change list page: Filters. Add the -following line to ``PollAdmin``:: +admin.py 파일을 수정하여 Poll 수정 리스트를 향상시킬 수 있습니다.: 필터. ``PollAdmin`` 에 아래 코드를 추가하세요.:: list_filter = ['pub_date'] -That adds a "Filter" sidebar that lets people filter the change list by the -``pub_date`` field: +사이드 바에 추가된 "Filter" 되어 사용자 들이 수정 목록을 ``pub_date`` 필드로 필터링 할 수 있습니다.: .. image:: _images/admin14t.png - :alt: Polls change list page, updated + :alt: 업데이트 된 Poll 변경 리스트 페이지 -The type of filter displayed depends on the type of field you're filtering on. -Because ``pub_date`` is a :class:`~django.db.models.fields.DateTimeField`, -Django knows to give appropriate filter options: "Any date," "Today," "Past 7 +여러분이 필터링 하는 필드의 타입에 따라 필터의 타입이 보여지게 됩니다. +``pub_date`` 은 :class:`~django.db.models.fields.DateTimeField` 이기 때문에 Django 는 적절한 옵션을 제공합니다.: "Any date," "Today," "Past 7 days," "This month," "This year." -This is shaping up well. Let's add some search capability:: +꽤 사용하기 편하게 구성되죠?이제 검색 기능을 추가 해 봅시다.:: search_fields = ['question'] -That adds a search box at the top of the change list. When somebody enters -search terms, Django will search the ``question`` field. You can use as many -fields as you'd like -- although because it uses a ``LIKE`` query behind the -scenes, keep it reasonable, to keep your database happy. +위의 옵션은 수정 목록 상단에 검색창(Search Box)를 추가합니다. 사용자가 검색어를 입력하면 Django 는 ``question`` 필드를 검색합니다. 여러분은 여러분이 원하는 만큼 필드를 추가할 수 있으며 내부에서 ``LIKE`` 질의를 하기 때문에 데이터베이스의 효율을 높일 수 있습니다. -Finally, because Poll objects have dates, it'd be convenient to be able to -drill down by date. Add this line:: +마지막으로 Poll 개체는 날짜를 포함하므로 손쉽게 날짜 순으로 보여줄 수 있습니다. 아래 코드를 추가하세요.:: date_hierarchy = 'pub_date' -That adds hierarchical navigation, by date, to the top of the change list page. -At top level, it displays all available years. Then it drills down to months -and, ultimately, days. +이는 수정 목록 페이지의 상단에서 날짜 순의 계층적 탐색을 추가합니다. +최상위 수준에서 선택 가능한 모든 연도가 표시됩니다. 또한 월 에서 일까지 순차적으로 선택할 수 있습니다. -Now's also a good time to note that change lists give you free pagination. The -default is to display 100 items per page. Change-list pagination, search boxes, -filters, date-hierarchies and column-header-ordering all work together like you -think they should. +이제 수정 리스트의 페이지네이션에 대하여 알아봅시다. 기본적으로 한 페이지에 100개의 아이템이 보여집니다. 이제 수정 목록 페이지네이션(Change-list pagination), 검색창(search boxes), +필터(filters), 날짜 구조화(date-hierarchies) and 컬럼 헤더 정렬(column-header-ordering) 모두 여러분이 생각하는 데로 작동합니다. -Customize the admin look and feel +관리자 사이트 룩앤필(Look and feel) 커스터마이즈 하기 ================================= -Clearly, having "Django administration" at the top of each admin page is -ridiculous. It's just placeholder text. +모든 관리자 페이지의 최상단에 존재하는 "Django administration" 가 조금은 이상하게 느껴집니다. 이는 임시적인 문구 입니다. -That's easy to change, though, using Django's template system. The Django admin -is powered by Django itself, and its interfaces use Django's own template -system. +Django 의 템플릿 시스템을 이용하면 쉽게 변경할 수 있습니다. Django 관리자 사이트는 Django 기반으로 개발되었기 때문에 Django의 자체 템플릿 시스템을 사용하여 인터페이스를 제공하고 있습니다. -Open your settings file (``mysite/settings.py``, remember) and look at the -:setting:`TEMPLATE_DIRS` setting. :setting:`TEMPLATE_DIRS` is a tuple of -filesystem directories to check when loading Django templates. It's a search -path. +설정 파일(``mysite/settings.py``, 기억하나요?)을 열어 :setting:`TEMPLATE_DIRS` 설정을 봅시다. :setting:`TEMPLATE_DIRS` 은 Django 템플릿을 불러올 때 확인하는 파일 시스템 디렉토리로 구성된 튜플로 구성됩니다. 이는 검색을 위한 패스 입니다. -By default, :setting:`TEMPLATE_DIRS` is empty. So, let's add a line to it, to -tell Django where our templates live:: +기본적으로 :setting:`TEMPLATE_DIRS` 는 비어있습니다. 이제 Django에게 어디에 우리의 템플릿이 있는지 알려주기 위해 한 줄 추가 해 봅시다.:: TEMPLATE_DIRS = ( '/home/my_username/mytemplates', # Change this to your own directory. ) -Now copy the template ``admin/base_site.html`` from within the default Django -admin template directory in the source code of Django itself -(``django/contrib/admin/templates``) into an ``admin`` subdirectory of -whichever directory you're using in :setting:`TEMPLATE_DIRS`. For example, if -your :setting:`TEMPLATE_DIRS` includes ``'/home/my_username/mytemplates'``, as -above, then copy ``django/contrib/admin/templates/admin/base_site.html`` to -``/home/my_username/mytemplates/admin/base_site.html``. Don't forget that -``admin`` subdirectory. - -Then, just edit the file and replace the generic Django text with your own -site's name as you see fit. - -This template file contains lots of text like ``{% block branding %}`` -and ``{{ title }}``. The ``{%`` and ``{{`` tags are part of Django's -template language. When Django renders ``admin/base_site.html``, this -template language will be evaluated to produce the final HTML page. -Don't worry if you can't make any sense of the template right now -- -we'll delve into Django's templating language in Tutorial 3. - -Note that any of Django's default admin templates can be overridden. To -override a template, just do the same thing you did with ``base_site.html`` -- -copy it from the default directory into your custom directory, and make -changes. - -Astute readers will ask: But if :setting:`TEMPLATE_DIRS` was empty by default, -how was Django finding the default admin templates? The answer is that, by -default, Django automatically looks for a ``templates/`` subdirectory within -each app package, for use as a fallback. See the :ref:`template loader -documentation ` for full information. - -Customize the admin index page +이제 Django 소스코드의 기본 Django 관리자 템플릿 디렉토리 (``django/contrib/admin/templates``) 에 있는 ``admin/base_site.html``를 여러분이 :setting:`TEMPLATE_DIRS`에 지정한 디렉토리의 ``admin`` 하위 디렉토리로 복사합니다. 예를 들어, 만약 여러분의 :setting:`TEMPLATE_DIRS` 에 위와 같이 ``'/home/my_username/mytemplates'`` 가 포함되어 있다면, ``django/contrib/admin/templates/admin/base_site.html`` 를 +``/home/my_username/mytemplates/admin/base_site.html`` 로 복사하세요. ``admin`` 의 하위 디렉토리를 잊지 마세요. + +다음으로, 파일을 수정하여 이미 입력 되 있는 Django 텍스트를 적절한 여러분의 사이트 이름으로 교체 해 주세요. + +이 템플릿 파일은 여러개의 ``{% block branding %}`` 과 ``{{ title }}`` 을 포함하고 있습니다. ``{%`` 와 ``{{`` 는 Django 템플릿 언어 중 일부입니다. Django 가 ``admin/base_site.html`` 를 출력할 때 HTML 페이지를 완성하기 위하여 이 텀플릿 언어는 평가됩니다. +여러분이 지금 템플릿에 대해 잘 알지 못해도 걱정하지 마세요. 세번째 자습서에서 Django의 탐플릿 언어에 대해 자세히 알아볼 것 입니다. + +Django의 기본 관리자 사이트 템플릿은 재정의(Override) 될 수 있다는 것만 알아두세요. 템플릿을 재정의 하기 위해, 위에서 한 작업들을 ``base_site.html`` 에 해 주세요. -- +파일을 기본 디렉토리에서 여러분의 커스텀 디렉토리에 복사 한 후 수정하세요. + +여기서 날카로운 여러분은 의문이 생길겁니다.: 만약 기본적으로 :setting:`TEMPLATE_DIRS` 가 비어있다면, +Django 는 어떻게 기본 관리자 사이트 템플릿을 찾나요?정답은, Django는 기본적으로 각 앱 패키지의 하위디렉토리에 있는 ``templates/`` 의 템플릿을 자동으로 대체하여 사용합니다. 보다 자세한 정보를 위해 :ref:`template loader documentation ` 을 참조하세요. + +관리자 사이트 첫 페이지 커스터마이즈 하기 ============================== -On a similar note, you might want to customize the look and feel of the Django -admin index page. - -By default, it displays all the apps in :setting:`INSTALLED_APPS` that have been -registered with the admin application, in alphabetical order. You may want to -make significant changes to the layout. After all, the index is probably the -most important page of the admin, and it should be easy to use. - -The template to customize is ``admin/index.html``. (Do the same as with -``admin/base_site.html`` in the previous section -- copy it from the default -directory to your custom template directory.) Edit the file, and you'll see it -uses a template variable called ``app_list``. That variable contains every -installed Django app. Instead of using that, you can hard-code links to -object-specific admin pages in whatever way you think is best. Again, -don't worry if you can't understand the template language -- we'll cover that -in more detail in Tutorial 3. - -When you're comfortable with the admin site, read :doc:`part 3 of this tutorial -` to start working on public poll views. +여러분은 이제 Django 관리 사이트의 첫 페이지 룩앤필도 커스터마이즈 하고 싶을 것 입니다. + +기본적으로 첫 페이지는 :setting:`INSTALLED_APPS` 에 등록된 모든 앱을 알파벳 순서로 보여줍니다. 여러분은 아마 레이아웃을 여러분이 원하는데로 변경하고 싶을 것 입니다. 초기 페이지는 관리자 사이트에서 가장 중요한 페이지 이며 쉽게 사용할 수 있어야 합니다. + +초기 페이지의 커스터마이즈 템플릿은 ``admin/index.html`` 파일 입니다. (이 전 섹션에서 ``admin/base_site.html`` 에서 한 작업들을 그대로 해 주세요. -- 파일을 기본 디렉토리에서 여러분의 커스텀 디렉토리에 복사 한 후 수정하세요.) 파일을 수정 할 때 ``app_list`` 변수를 확인할 수 있을 것 입니다. 변수는 여러분이 설치한 모든 Django 앱이 포함되어 있을 것 입니다. 이 링크를 그대로 사용해도 되지만, 어려분이 생각하는 데로 관리자 페이지의 개체에 링크를 직접 연결할 수도 있습니다. 다시 한번 얘기 드리지만, 템플릿 언어를 모른다고 걱정하지 마세요. -- 세 번째 자습서에서 보다 자세히 알아볼 것 입니다. + +이제 관리자 사이트에 익숙 해 졌다면, :doc:`세 번째 자습서 +` 를 통해 공개된 poll 뷰에 대해 알아봅시다. From 2fb0010b1e0f6229cdea17f90a40273989756945 Mon Sep 17 00:00:00 2001 From: shchoi Date: Sat, 11 Aug 2012 05:51:19 +0900 Subject: [PATCH 018/128] Some modification have been applied --- intro/tutorial02.txt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/intro/tutorial02.txt b/intro/tutorial02.txt index d02ad85..bd0d2bd 100644 --- a/intro/tutorial02.txt +++ b/intro/tutorial02.txt @@ -39,19 +39,19 @@ from django.conf.urls import patterns, include, url - # Uncomment the next two lines to enable the admin: + # 관리자 사이트를 활성화 시키기 위해 다음 두 줄의 주석을 제거 해 주세요.: **from django.contrib import admin** **admin.autodiscover()** urlpatterns = patterns('', - # Examples: + # 예제: # url(r'^$', '{{ project_name }}.views.home', name='home'), # url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), - # Uncomment the admin/doc line below to enable admin documentation: + # 관리자 싸이트 문서를 활성화 시키기 위해 admin/doc 의 주석을 제거 해 주세요.: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), - # Uncomment the next line to enable the admin: + # 관리자 사이트를 활성화 시키기 위해 다음 줄의 주석을 제거 해 주세요.: **url(r'^admin/', include(admin.site.urls)),** ) @@ -355,7 +355,7 @@ Django 의 템플릿 시스템을 이용하면 쉽게 변경할 수 있습니다 기본적으로 :setting:`TEMPLATE_DIRS` 는 비어있습니다. 이제 Django에게 어디에 우리의 템플릿이 있는지 알려주기 위해 한 줄 추가 해 봅시다.:: TEMPLATE_DIRS = ( - '/home/my_username/mytemplates', # Change this to your own directory. + '/home/my_username/mytemplates', # 여러분의 디렉토리로 변경 해 주세요. ) 이제 Django 소스코드의 기본 Django 관리자 템플릿 디렉토리 (``django/contrib/admin/templates``) 에 있는 ``admin/base_site.html``를 여러분이 :setting:`TEMPLATE_DIRS`에 지정한 디렉토리의 ``admin`` 하위 디렉토리로 복사합니다. 예를 들어, 만약 여러분의 :setting:`TEMPLATE_DIRS` 에 위와 같이 ``'/home/my_username/mytemplates'`` 가 포함되어 있다면, ``django/contrib/admin/templates/admin/base_site.html`` 를 From 2395db5fdae93e0d498cceee119fd935301690bc Mon Sep 17 00:00:00 2001 From: Jeong Date: Tue, 14 Aug 2012 22:00:36 +0900 Subject: [PATCH 019/128] tutorial04 first commit --- intro/tutorial04.txt | 171 ++++++++++++++++++------------------------- 1 file changed, 73 insertions(+), 98 deletions(-) diff --git a/intro/tutorial04.txt b/intro/tutorial04.txt index 85d54c3..bc5fd29 100644 --- a/intro/tutorial04.txt +++ b/intro/tutorial04.txt @@ -1,16 +1,13 @@ ===================================== -Writing your first Django app, part 4 -===================================== +첫번째 장고 앱 만들기! part 4 +==================================== -This tutorial begins where :doc:`Tutorial 3 ` left off. We're -continuing the Web-poll application and will focus on simple form processing and -cutting down our code. +본 자습서는 :doc:`Tutorial 3 `\ 에 이어서 계속 됩니다. 우리는 웹 설문조사 어플리케이션을 만들고 있고, 우리 코드의 양을 줄이고, 간단한 폼처리를 하는데 초점을 맞출 것 입니다. -Write a simple form +간단한 폼 사용하기. =================== -Let's update our poll detail template ("polls/detail.html") from the last -tutorial, so that the template contains an HTML ``
`` element: +HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조사 세부 템플릿을 수정하자: .. code-block:: html+django @@ -27,13 +24,13 @@ tutorial, so that the template contains an HTML ```` element:
-A quick rundown: +간략하게 설명하면: -* The above template displays a radio button for each poll choice. The +* 위의 템플릿은 각 설문 선택지의 라디오버튼을 표시한다. The ``value`` of each radio button is the associated poll choice's ID. The ``name`` of each radio button is ``"choice"``. That means, when somebody selects one of the radio buttons and submits the form, it'll send the - POST data ``choice=3``. This is HTML Forms 101. + POST data ``choice=3``. 이것이 HTML Forms 101 이다. * We set the form's ``action`` to ``/polls/{{ poll.id }}/vote/``, and we set ``method="post"``. Using ``method="post"`` (as opposed to @@ -64,17 +61,13 @@ view, so that it looks like the following:: return render_to_response('polls/detail.html', {'poll': p}, context_instance=RequestContext(request)) -The details of how this works are explained in the documentation for -:ref:`RequestContext `. +이것이 작동하는 것에 대한 자세한 내용은 :ref:`RequestContext ` 부분의 문서를 참고하라. -Now, let's create a Django view that handles the submitted data and does -something with it. Remember, in :doc:`Tutorial 3 `, we -created a URLconf for the polls application that includes this line:: +이제 전송된 자료를 다룰 장고 뷰를 만들고, 그것을 가지고 무엇인가를 해보자. :doc:`자습서 3 `\ 에서 이 라인을 포함하는 설물조사 어플리케이션을 위해 URLconf를 만들것을 기억하라:: (r'^(?P\d+)/vote/$', 'vote'), -We also created a dummy implementation of the ``vote()`` function. Let's -create a real version. Add the following to ``polls/views.py``:: +또, 우리는 ``vote()``\ 더미의 실행 함수를 만들었다. 실제 버전을 만들어보자. ``polls/views.py``\ 에 다음을 추가하자:: from django.shortcuts import get_object_or_404, render_to_response from django.http import HttpResponseRedirect, HttpResponse @@ -87,7 +80,7 @@ create a real version. Add the following to ``polls/views.py``:: try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): - # Redisplay the poll voting form. + # 설문조사 폼을 다시 보여주기. return render_to_response('polls/detail.html', { 'poll': p, 'error_message': "You didn't select a choice.", @@ -95,12 +88,12 @@ create a real version. Add the following to ``polls/views.py``:: else: selected_choice.votes += 1 selected_choice.save() - # Always return an HttpResponseRedirect after successfully dealing + # 전송된 POST 자료를 성공적으로 처리한 뒤에는 항상 HttpResponseRedirect를 반환하라. # with POST data. This prevents data from being posted twice if a - # user hits the Back button. + # 자료가 두 번 전송되는 경우를 막아준다. return HttpResponseRedirect(reverse('polls.views.results', args=(p.id,))) -This code includes a few things we haven't covered yet in this tutorial: +위 코드는 이 자습서에서 아직 다루지 않은 몇 가지를 포함하고 있다: * :attr:`request.POST ` is a dictionary-like object that lets you access submitted data by key name. In this case, @@ -114,53 +107,47 @@ This code includes a few things we haven't covered yet in this tutorial: ` in our code, to ensure that data is only altered via a POST call. -* ``request.POST['choice']`` will raise :exc:`KeyError` if ``choice`` wasn't - provided in POST data. The above code checks for :exc:`KeyError` and - redisplays the poll form with an error message if ``choice`` isn't given. +* 만약 POST 자료에 ``choice``\ 가 없으면, ``request.POST['choice']``\ + 는 :exc:`KeyError`\ 를 일으킨다. 위의 코드는 :exc:`KeyError`\ 를 체크하고, ``choice``\ 가 주어지지 않은 경우에는 + 설문조사 양식을 다시보여준다. -* After incrementing the choice count, the code returns an - :class:`~django.http.HttpResponseRedirect` rather than a normal - :class:`~django.http.HttpResponse`. - :class:`~django.http.HttpResponseRedirect` takes a single argument: the - URL to which the user will be redirected (see the following point for how - we construct the URL in this case). +* 설문지의 수가 증가한 이후에, 코드는 평범한 + :class:`~django.http.HttpResponse` 보다는 + :class:`~django.http.HttpResponseRedirect`\ 를 반환한다 :class:`~django.http.HttpResponseRedirect`\ 는 하나의 인수를 받는다: + 사용자가 재전송할 URL. (이 경우에 우리가 URL을 + 어떻게 구성하는지 다음 항목을 보라). - As the Python comment above points out, you should always return an + 위 소스안의 파이썬 주석내용대로, POST 자료를 성공적으로 처리한 후에는 항상 :class:`~django.http.HttpResponseRedirect` after successfully dealing with - POST data. This tip isn't specific to Django; it's just good Web - development practice. - -* We are using the :func:`~django.core.urlresolvers.reverse` function in the - :class:`~django.http.HttpResponseRedirect` constructor in this example. - This function helps avoid having to hardcode a URL in the view function. - It is given the name of the view that we want to pass control to and the - variable portion of the URL pattern that points to that view. In this + POST data. 이것은 장고에만 특정한 팁이 아니다, + 좋은 웹 개발관례일 뿐이다. + +* 우리는 이 예제에서 :class:`~django.http.HttpResponseRedirect` 생성자 안의 + :func:`~django.core.urlresolvers.reverse` 함수를 사용하고 있다. + 이 함수는 함수에서 URL을 하드코딩하는 행위를 안하게 도와준다. + 제어를 전달하기 원하는 view의 이름을 제공하고, URL패턴의 변수부분이 그 뷰를 가리킨다. + 이 경우에, URLconf를 사용하여 우리는 자습서 3에서 설정하였다. In this case, using the URLconf we set up in Tutorial 3, this - :func:`~django.core.urlresolvers.reverse` call will return a string like + 아래와 같은 문자열을 반환할 것이다. :: '/polls/3/results/' - ... where the ``3`` is the value of ``p.id``. This redirected URL will - then call the ``'results'`` view to display the final page. Note that you - need to use the full name of the view here (including the prefix). + ... ``3``\ 은 ``p.id``\ 의 값이다. 이 리다이렉트된 URL은 + 마지막 페이지를 보여주기위해 ``'results'`` 뷰를 호출한다. 뷰 이름(풀네임)을 + 사용해야한다는 것을 주의하라(접두사를 포함하여). -As mentioned in Tutorial 3, ``request`` is a :class:`~django.http.HttpRequest` -object. For more on :class:`~django.http.HttpRequest` objects, see the -:doc:`request and response documentation `. +자습서 3에서 언급했듯이, ``request``\ 은 :class:`~django.http.HttpRequest`\ 개체이다. :class:`~django.http.HttpRequest` 개체에 대해 더 알고 싶다면 :doc:`request and response documentation `\ 을 보라. -After somebody votes in a poll, the ``vote()`` view redirects to the results -page for the poll. Let's write that view:: +어떤 이가 설문조사에 설문을 하고난 뒤에는, ``vote()`` 뷰는 설문조사 결과 페이지로 리다이렉트한다. 그 뷰를 작성해보자:: def results(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/results.html', {'poll': p}) -This is almost exactly the same as the ``detail()`` view from :doc:`Tutorial 3 -`. The only difference is the template name. We'll fix this -redundancy later. +이것은 :doc:`Tutorial 3`\ 의 ``detail()`` view와 거의 동일하다. 다른점은 템플릿 이름밖에 없다. 우리는 후에 이 쓸데없는 것들을 수정할 것이다. -Now, create a ``results.html`` template: +이제, ``results.html`` 템플릿을 만들자: .. code-block:: html+django @@ -174,49 +161,39 @@ Now, create a ``results.html`` template: Vote again? -Now, go to ``/polls/1/`` in your browser and vote in the poll. You should see a -results page that gets updated each time you vote. If you submit the form -without having chosen a choice, you should see the error message. +이제, 웹브라주여에서 ``/polls/1/`` 페이지로 가자, 그리고 설문조사를 해보자. 당신이 설문조사를 할 때마다 값이 반영된 결과페이지를 볼것이다. 만약 당신이 설문지를 선택하지 않고 폼을 전송했다면, 에러메시지를 보게될 것이다. -Use generic views: Less code is better +제네릭 뷰 사용하기 : 적은 코드가 더 좋음 ====================================== -The ``detail()`` (from :doc:`Tutorial 3 `) and ``results()`` -views are stupidly simple -- and, as mentioned above, redundant. The ``index()`` -view (also from Tutorial 3), which displays a list of polls, is similar. +``detail()`` ( :doc:`자습 3 `\ 에서의) 과 ``results()`` +뷰는 매우 비슷하다. -- 그리고, 위에서 언급한 것 처럼 장황하다. 설문 목록들을 보여주는 ``index()`` 뷰(이것도 자습서 3에서), 는 비슷하다. -These views represent a common case of basic Web development: getting data from -the database according to a parameter passed in the URL, loading a template and -returning the rendered template. Because this is so common, Django provides a -shortcut, called the "generic views" system. +이 뷰들은 기본적인 웹 개발의 일반적인 케이스들:(URL로 전달된 매개변수로부터 데이터베이스에서 자료를 얻고, 템플릿을 불러오며, 처리된 템플릿을 반환하는)을 제공한다. 매우 일반적인 것들이기 때문에, 장고는 "제네릭 뷰" 시스템이라 불리는 지름길을 제공한다. -Generic views abstract common patterns to the point where you don't even need -to write Python code to write an app. +앱을 쓰기위해 파이썬 코드를 쓸 필요가 없을 정도로 제네릭 뷰는 일반적인(역자주-중복되고, 장황한) 패턴들을 제거한다. -Let's convert our poll app to use the generic views system, so we can delete a -bunch of our own code. We'll just have to take a few steps to make the -conversion. We will: +제네릭 뷰 시스템을 사용해서 우리의 설문자 앱을 바꿔보자. 그리고 우리의 코드를 삭제할 수도 있다. 변환하기에는 몇 단계를 거쳐야 한다. 우리는: -1. Convert the URLconf. +1. URLconf를 변환한다. -2. Delete some of the old, unneeded views. +2. 오래되고 불필요한 뷰들 일부를 삭제한다. -3. Fix up URL handling for the new views. +3. 새로운 뷰들을 위해 URL 다루기를 수정한다. -Read on for details. +자세한 내용을 읽어보라. -.. admonition:: Why the code-shuffle? +.. admonition:: 왜 코드 섞기(code-shuffle)(역자주:코드를 이렇게 저렇게 수정하는 것)인가? - Generally, when writing a Django app, you'll evaluate whether generic views - are a good fit for your problem, and you'll use them from the beginning, - rather than refactoring your code halfway through. But this tutorial - intentionally has focused on writing the views "the hard way" until now, to - focus on core concepts. + 일반적으로, 장고 앱을 작성할 때, 당신은 제네릭 뷰가 당신의 문제에 + 잘 맞는지 평가할 것이고, 절반정도 작성된 당신의 코드를 + 리펙토링 하기보다는 처음부터 제네릭 뷰를 사용할 것이다. 그러나 이 자습서는 + 지금까지 핵심개념들을 배우기위해 의도적으로 "힘든 방법으로", + 뷰 작성하기에 초점을 맞춰왔다. - You should know basic math before you start using a calculator. + 계산기를 사용하기전에 기본적인 산수를 알아야하지 않겠는가. -First, open the ``polls/urls.py`` URLconf. It looks like this, according to the -tutorial so far:: +먼저, ``polls/urls.py``\ 의 URLconf를 보라. 지금까지의 자습서 내용대로라면 아래와 같은 내용이 보일것이다. from django.conf.urls import patterns, include, url @@ -227,7 +204,7 @@ tutorial so far:: url(r'^(?P\d+)/vote/$', 'vote'), ) -Change it like so:: +아래와 같이 변경하라:: from django.conf.urls import patterns, include, url from django.views.generic import DetailView, ListView @@ -251,24 +228,22 @@ Change it like so:: url(r'^(?P\d+)/vote/$', 'polls.views.vote'), ) -We're using two generic views here: -:class:`~django.views.generic.list.ListView` and -:class:`~django.views.generic.detail.DetailView`. Respectively, those -two views abstract the concepts of "display a list of objects" and -"display a detail page for a particular type of object." +여기에서 제네릭 뷰 두 개를 사용하고 있다: +:class:`~django.views.generic.list.ListView` 와 +:class:`~django.views.generic.detail.DetailView`.. 이 두 개의 뷰들은 각각, "개체들의 목록을 보여주기" 와 "개체의 특정한 형식에 맞춘 세부 페이지 보여주기" 란 개념을 가지고 있다. -* Each generic view needs to know what model it will be acting - upon. This is provided using the ``model`` parameter. +* 각 제네릭 뷰는 제네릭 뷰가 어떤 모델에 작용할지 알아야한다 + .. 그것은 ``model`` 파라미터를 사용하여 제공된다. -* The :class:`~django.views.generic.list.DetailView` generic view - expects the primary key value captured from the URL to be called - ``"pk"``, so we've changed ``poll_id`` to ``pk`` for the generic - views. +* :class:`~django.views.generic.list.DetailView` 제네릭 뷰는 + ``"pk"``라 불리는 URL에서 가져온 기본 키 값을 받을 준비를 하고 있다 + , 그래서 우리는 ``poll_id``\ 를 ``pk``\ 로 변경했다 + . -* We've added a name, ``poll_results``, to the results view so - that we have a way to refer to its URL later on (see the - documentation about :ref:`naming URL patterns - ` for information). We're also using the +* 우리는 results 뷰에 ``poll_results``\ 란 이름을 추가했다, + 그렇게 하면 URL 이후에 오는 변수를 참조할 수 있게 된다.( + 이것에 관한 정보는 :ref:`naming URL patterns + ` 문서를 보라). We're also using the :func:`~django.conf.urls.url` function from :mod:`django.conf.urls` here. It's a good habit to use :func:`~django.conf.urls.url` when you are providing a From 605faa647d4bf0591977e8471a8e2c1e4089b357 Mon Sep 17 00:00:00 2001 From: Jeong Date: Tue, 14 Aug 2012 23:28:49 +0900 Subject: [PATCH 020/128] second commit.not yet perfect.. --- intro/tutorial04.txt | 127 +++++++++++++++---------------------------- 1 file changed, 44 insertions(+), 83 deletions(-) diff --git a/intro/tutorial04.txt b/intro/tutorial04.txt index bc5fd29..60b6aad 100644 --- a/intro/tutorial04.txt +++ b/intro/tutorial04.txt @@ -26,33 +26,27 @@ HTML ``
`` 요소를 포함하고 있는 앞 장에서 사용한 설문조 간략하게 설명하면: -* 위의 템플릿은 각 설문 선택지의 라디오버튼을 표시한다. The - ``value`` of each radio button is the associated poll choice's ID. The - ``name`` of each radio button is ``"choice"``. That means, when somebody - selects one of the radio buttons and submits the form, it'll send the - POST data ``choice=3``. 이것이 HTML Forms 101 이다. - -* We set the form's ``action`` to ``/polls/{{ poll.id }}/vote/``, and we - set ``method="post"``. Using ``method="post"`` (as opposed to - ``method="get"``) is very important, because the act of submitting this - form will alter data server-side. Whenever you create a form that alters - data server-side, use ``method="post"``. This tip isn't specific to - Django; it's just good Web development practice. - -* ``forloop.counter`` indicates how many times the :ttag:`for` tag has gone - through its loop - -* Since we're creating a POST form (which can have the effect of modifying - data), we need to worry about Cross Site Request Forgeries. - Thankfully, you don't have to worry too hard, because Django comes with - a very easy-to-use system for protecting against it. In short, all POST - forms that are targeted at internal URLs should use the - :ttag:`{% csrf_token %}` template tag. - -The :ttag:`{% csrf_token %}` tag requires information from the -request object, which is not normally accessible from within the template -context. To fix this, a small adjustment needs to be made to the ``detail`` -view, so that it looks like the following:: +* 위의 템플릿은 각 설문 선택지의 라디오버튼을 표시한다. 각 라디오 버튼의 + ``value``\ 는 연결된 설문조사 선택지의 ID이다. 각 라디오 버튼의 ``name`` + 은 ``"choice"``\ 이다. 이것은, 누군가 라디오버튼중 하나를 선택하고, + 폼을 제출하면, 폼은 POST 자료 ``choice=3``\ 를 전송한다는 것을 의미한다. + 이것이 HTML Forms 101(역자주: HTML FORMS의 기본)이다. + +* 우리는 폼의 ``action``\ 을 ``/polls/{{ poll.id }}/vote/``\ 로 지정하고, + ``method="post"``\ 로 지정했다. 이 폼을 제출하는 행위가 서버측 자료를 변경할 + 수 있기 때문에 ``method="post"``\ 를 사용하는 것은 (혹은 반대로 ``method="get"``) + 매우 중요하다. 서버측 자료를 변경할 폼을 만들때는, 항상 ``method="post"``\ 을 + 사용하라. 이 정보는 장고에 특정한 정보가 아니다; 단지 좋은 웹 개발 관례일 뿐이다. + +* ``forloop.counter``\ 는 :ttag:`for` 태그가 반복을 한 횟 수를 나타낸다. + +* 우리는 POST 폼(자료를 수정하는 효과를 가진)을 만들고 있으므로, 사이트 간 요청 위조 + (Cross Site Request Forgeries)에 대해 고민해야한다.고맙게도, 장고는 + 사이트 간 요청 위조(CSRF)에 대해 보호하기위한 사용하기 쉬운 시스템을 가지고 있기 때문에, + 너무 심각하게 고민할 필요가 없다. 간단히 말하면, 내부 URL들을 향하는 모든 POST 폼은 + 템플릿 태그 :ttag:`{% csrf_token %}`/ 을 사용해야한다. + +:ttag:`{% csrf_token %}`\ 태그는 템플릿 문접에서 평범하게 접근이 불가능한 요청(request) 개체로부터의 정보를 필요로 한다. 이부분을 적용하기 위해, 다음과 같은 작은 조정이 ``detail`` 뷰에 필요하다 :: from django.template import RequestContext # ... @@ -63,7 +57,7 @@ view, so that it looks like the following:: 이것이 작동하는 것에 대한 자세한 내용은 :ref:`RequestContext ` 부분의 문서를 참고하라. -이제 전송된 자료를 다룰 장고 뷰를 만들고, 그것을 가지고 무엇인가를 해보자. :doc:`자습서 3 `\ 에서 이 라인을 포함하는 설물조사 어플리케이션을 위해 URLconf를 만들것을 기억하라:: +이제 전송된 자료를 다룰 장고 뷰를 만들고, 그것을 가지고 무엇인가를 해보자. :doc:`자습서 3 `\ 에서 아 라인을 포함하는 설물조사 어플리케이션을 위해 URLconf를 만들것을 기억하라:: (r'^(?P\d+)/vote/$', 'vote'), @@ -139,7 +133,7 @@ view, so that it looks like the following:: 자습서 3에서 언급했듯이, ``request``\ 은 :class:`~django.http.HttpRequest`\ 개체이다. :class:`~django.http.HttpRequest` 개체에 대해 더 알고 싶다면 :doc:`request and response documentation `\ 을 보라. -어떤 이가 설문조사에 설문을 하고난 뒤에는, ``vote()`` 뷰는 설문조사 결과 페이지로 리다이렉트한다. 그 뷰를 작성해보자:: +어떤 이가 설문조사에 설문을 하고난 뒤에는, ``vote()`` 뷰는 설문조사 결과 페이지로 리다이렉트한다. 그 뷰를 작성해보자 :: def results(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) @@ -249,66 +243,33 @@ view, so that it looks like the following:: :func:`~django.conf.urls.url` when you are providing a pattern name like this. -By default, the :class:`~django.views.generic.list.DetailView` generic -view uses a template called ``/_detail.html``. -In our case, it'll use the template ``"polls/poll_detail.html"``. The -``template_name`` argument is used to tell Django to use a specific -template name instead of the autogenerated default template name. We -also specify the ``template_name`` for the ``results`` list view -- -this ensures that the results view and the detail view have a -different appearance when rendered, even though they're both a -:class:`~django.views.generic.list.DetailView` behind the scenes. - -Similarly, the :class:`~django.views.generic.list.ListView` generic -view uses a default template called ``/_list.html``; we use ``template_name`` to tell -:class:`~django.views.generic.list.ListView` to use our existing -``"polls/index.html"`` template. - -In previous parts of the tutorial, the templates have been provided -with a context that contains the ``poll`` and ``latest_poll_list`` -context variables. For DetailView the ``poll`` variable is provided -automatically -- since we're using a Django model (``Poll``), Django -is able to determine an appropriate name for the context variable. -However, for ListView, the automatically generated context variable is -``poll_list``. To override this we provide the ``context_object_name`` -option, specifying that we want to use ``latest_poll_list`` instead. -As an alternative approach, you could change your templates to match -the new default context variables -- but it's a lot easier to just -tell Django to use the variable you want. - -You can now delete the ``index()``, ``detail()`` and ``results()`` -views from ``polls/views.py``. We don't need them anymore -- they have -been replaced by generic views. - -The last thing to do is fix the URL handling to account for the use of -generic views. In the vote view above, we used the -:func:`~django.core.urlresolvers.reverse` function to avoid -hard-coding our URLs. Now that we've switched to a generic view, we'll -need to change the :func:`~django.core.urlresolvers.reverse` call to -point back to our new generic view. We can't simply use the view -function anymore -- generic views can be (and are) used multiple times --- but we can use the name we've given:: +기본적으로 :class:`~django.views.generic.list.DetailView` 제네릭 뷰는 ``/_detail.html``\ 이라 불리는 템플릿을 사용한다. +우리는 ``"polls/poll_detail.html"`` 템플릿을 사용할 것이다. 자동생성되는 기본 템플릿 이름 대신에 특정한 템릿 이름을 사용하여 장고에게 전달하기 위해 ``template_name`` 를 사용한다. 또한 우리는 ``results`` 리스트 뷰를 위해 ``template_name``\ 를 지정해야한다 -- 비록 둘 다 같은 :class:`~django.views.generic.list.DetailView`\ 이긴 하지만. 이것은 results 뷰와 detail 뷰가 달리 표현되는 것을 보장한다. + +비슷하게, 기존 ``"polls/index.html"`` 테플릿을 사용하기위해 ``template_name``\ 을 사용해서 :class:`~django.views.generic.list.ListView`\ 에 전달한다. + +이전 자습서에서, 탬플릿은 ``poll`` 과 ``latest_poll_list``\의 컨텍스트 변수를 포함한 컨텍스트가 제공되었다. DetailView를 위해 ``poll`` 변수는 자동으로 제공되었다 -- 장고 모델(``Poll``)을 사용했기때문에, 장고는 컨텍스트 변수를 위한 적당한 이름을 정할 수 있다. 그러나, ListView를 위해 , 자동적으로 생성되는 컨텍스트 변수는 ``poll_list``\ 이다. ``latest_poll_list``\ 를 대신 지정해서 사용하기 위해 ``context_object_name``\ 을 재정의하라.다른 방법으로, 새로운 기본 컨텍스트 변수들과 매치되는 당신만으로 템프릿으로 바꿀 수 있다. -- 그러나 단지 Django에게 당신이 원하는 변수를 전달하는 것이 훨씬 쉽다. + +이제 ``polls/views.py``\ 파일에서 ``index()``, ``detail()`` 그리고 ``results()`` 뷰들을 지울 수 있다.그 뷰들은 더이상 필요지 않다-- 그 뷰들은 제대릭 뷰로 대체된다. + +마지막으로 해야 할 것은 제네릭 뷰들의 사용을 처리하는 URL 다루기를 수정하는 것이다. 위의 vote 뷰에서, 우리의 URL들을 하드코딩하는 것을 피하기 위해 :func:`~django.core.urlresolvers.reverse` 함수를 사용했다. 이제 우린 generic view로 전환을 했으니. :func:`~django.core.urlresolvers.reverse` 함수가 새로운 generic view를 호출하도록 바꿀 필요가 있다. 우리는 더이상 view 함수를 쉽게 사용할 수 없다 -- 제네릭 뷰들은여러번 사용하거나, 사용되어질 수 있다 --그러나 우리는 우리에게 주어진 이름을 사용할 수 있다 :: return HttpResponseRedirect(reverse('poll_results', args=(p.id,))) -Run the server, and use your new polling app based on generic views. +서버를 실행하고, 제레릭 뷰를 기반으로하는 새로운 설문조사 앱을 사용해보자. -For full details on generic views, see the :doc:`generic views documentation -`. +제네릭 뷰에 대한 자세한 내용은, :doc:`generic views documentation ` 문서를 보라. -Coming soon +곧 올것들 =========== -The tutorial ends here for the time being. Future installments of the tutorial -will cover: +당분간 이 자습서는 여기에서 끝난다. 이 자습서가 앞으로 다룰 내용들이다 : -* Advanced form processing -* Using the RSS framework -* Using the cache framework -* Using the comments framework -* Advanced admin features: Permissions -* Advanced admin features: Custom JavaScript +* 진보된 폼 처리 +* RSS 프레임워크 사용하기 +* 캐시 프레임워크 사용하기 +* 댓글 프레임워크 사용하기 +* 진보된 관리자 기능: 권한 +* 진보된 관리자 기능: 사용자 정의 자바스크립트 -In the meantime, you might want to check out some pointers on :doc:`where to go -from here ` +그 동안, :doc:`where to go from here `\ 에서 몇몇 부분들을 살펴볼 수 있다. From 006f102bd4499b4df3d3ee5a761f7242bbcdbb4e Mon Sep 17 00:00:00 2001 From: HyunJin Moon Date: Wed, 15 Aug 2012 11:36:11 +0900 Subject: [PATCH 021/128] Tutorial3 complete. Done to translate tutorial3. --- .DS_Store | Bin 0 -> 12292 bytes intro/.DS_Store | Bin 0 -> 6148 bytes intro/tutorial03.txt | 371 ++++++++++++++----------------------------- 3 files changed, 121 insertions(+), 250 deletions(-) create mode 100644 .DS_Store create mode 100644 intro/.DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..3026df9029561a92927094e1ec64e0bd71920e96 GIT binary patch literal 12292 zcmeHM&2G~`5T0$))DcC>1?bV@#G$HE6;uu!LewHSAfcvG4-^%zuEov^Y~{HB2wMsXq9M*h&&wHwyvSNpy+XZ z%#=CXa}!p+25Kjc^qHN-!e1?{kc7K>L(YN(Zz;M|4_6t1Sn;Xwe1cPO(M~uVR*w`tJDEFn>UAs9VFK0gMq4zt4X8?YAbq&1> z<&}0Z&ubLGJ8U#>zWu4QGwgtzR|&547+10r$;|mT)|_#9{-1}sG(>?bQJ`j4UDEmg z=He{*D5wzR}z0Vy#~H1VnrP!OXe=q9qL$9;y6@&W!vt9vG7f!%O3 zM!QLO&CYbqq-)5|4gl%T$3376phZ_~v>7T)$JN)Y5qp#;Hpe~gFuRy$x1;G=ws-tS z1$6JWag7NcF+^$qvJpr0Z*fjP_%dS)XfyW-WA5}D4v{nFVaFGYj}=D87&GP$G3Bq4 zC6_C#9b|anD$k4);%g1>bA`9Zb>{Sp%!#ddgkCk*YI`r$R>eK8;cAtexF^+It929i zw1%tombtrB=7DwQm~mfpSMqA6Rx7PiwVcS!6>tUqsRBH+)moi^9$f)fz!g|1pznu- zu9!wF0@|yC!L9(rCcDkp){jQzBoWhyML>?wBv6TgD)EXTfzJLU=A{vffPoH)mk)_6 zOT3|otrxcLp;A+rkN%3r5D^Aba sgnmO;)4U?!g2IL!#mv>Cc%N>@{zMzZG-45uJv9FiFd00!0zaz2H=6X5>i_@% literal 0 HcmV?d00001 diff --git a/intro/tutorial03.txt b/intro/tutorial03.txt index 5ed927a..ad526b3 100644 --- a/intro/tutorial03.txt +++ b/intro/tutorial03.txt @@ -2,81 +2,61 @@ Writing your first Django app, part 3 ===================================== -This tutorial begins where :doc:`Tutorial 2 ` left off. We're -continuing the Web-poll application and will focus on creating the public -interface -- "views." + ڽ :doc:`Tutorial 2 ` ̾ մϴ. , 츮 ؼ "" ϴ ۺ ̽ ۼϴµ ΰ -ǥ ø̼ մϴ. -Philosophy +ö ========== -A view is a "type" of Web page in your Django application that generally serves -a specific function and has a specific template. For example, in a Weblog -application, you might have the following views: + Django ø̼ǿ Ư ϰų, Ư ø "Ÿ" Դϴ. α ø̼ǿ Ʒ ֽϴ. -* Blog homepage -- displays the latest few entries. +* α Ȩ -- ֽ Ʈ  display մϴ. -* Entry "detail" page -- permalink page for a single entry. +* Ʈ "" -- Ʈ ۸Ӹũ Դϴ. -* Year-based archive page -- displays all months with entries in the +* ī̺ -- ־ ִ Ʈ Բ Ÿϴ. given year. -* Month-based archive page -- displays all days with entries in the +* ī̺ -- ־ ޿ ִ Ʈ Բ Ÿϴ. given month. -* Day-based archive page -- displays all entries in the given day. +* Ϻ ī̺ -- ־ ִ Ʈ Ÿϴ. -* Comment action -- handles posting comments to a given entry. +* ڸƮ ޱ -- ־ Ʈ ڸƮ մϴ. -In our poll application, we'll have the following four views: +츮 ǥ ø̼ǿ Ʒ 䰡 ֽϴ. -* Poll "index" page -- displays the latest few polls. +* ǥ "ε" -- ֱ ǥ Ÿϴ. -* Poll "detail" page -- displays a poll question, with no results but +* ǥ "" -- ǥ ǥ ִ Բ Ÿϴ. ʽϴ. with a form to vote. -* Poll "results" page -- displays results for a particular poll. +* ǥ "" -- Ư ǥ Ÿϴ. -* Vote action -- handles voting for a particular choice in a particular +* ǥ ϱ -- Ư ǥ Ư ǥմϴ. poll. -In Django, each view is represented by a simple Python function. +Django ̽ Լ Ÿ ֽϴ. -Design your URLs +URL ϱ ================ -The first step of writing views is to design your URL structure. You do this by -creating a Python module, called a URLconf. URLconfs are how Django associates -a given URL with given Python code. +URL ϴ 並 ۼϴ ù ° ܰԴϴ. URLconf ̽ μ, URL ֽϴ. URLconfs DJango ־ URL ־ ̽ ڵ ϴ Դϴ. -When a user requests a Django-powered page, the system looks at the -:setting:`ROOT_URLCONF` setting, which contains a string in Python dotted -syntax. Django loads that module and looks for a module-level variable called -``urlpatterns``, which is a sequence of tuples in the following format:: +ڰ Django-powerd û , ý Python dotted syntax ִ ڿ ϴ :setting:'ROOT_URLCONF' մϴ. Django URLconf ε մϴ. ׸, Ʒ Ʃ - ``urlpatterns`` ˻ մϴ. (regular expression, Python callback function [, optional dictionary]) -Django starts at the first regular expression and makes its way down the list, -comparing the requested URL against each regular expression until it finds one -that matches. +DJango ù ° ǥĿ ؼ, ġϴ ã û URL ǥİ ϸ鼭 Ʈ Ʒ ϴ. -When it finds a match, Django calls the Python callback function, with an -:class:`~django.http.HttpRequest` object as the first argument, any "captured" -values from the regular expression as keyword arguments, and, optionally, -arbitrary keyword arguments from the dictionary (an optional third item in the -tuple). + ġϴ ã, Django ̽ ݹ Լ ȣ մϴ. , :class:`~django.http.HttpRequest` ü ù ° ڷ ϰ, ǥĿ ã ƹ keyword ڷ մϴ. ɼ the dictionaryκ ƹ keyword մϴ.(Ʃ ° ). -For more on :class:`~django.http.HttpRequest` objects, see the -:doc:`/ref/request-response`. For more details on URLconfs, see the -:doc:`/topics/http/urls`. +:class:`~django.http.HttpRequest` ü ؼ ڼ ˰ ʹٸ, :doc:`/ref/request-response` ϼ. URLconfs ؼ ڼ ˰ ʹٸ, :doc:`/topics/http/urls` ϼ. -When you ran ``django-admin.py startproject mysite`` at the beginning of -Tutorial 1, it created a default URLconf in ``mysite/urls.py``. It also -automatically set your :setting:`ROOT_URLCONF` setting (in ``settings.py``) to -point at that file:: +ڽ 1 ó ``django-admin.py startproject mysite`` , ⺻ URLconf ``mysite/urls.py`` ߽ϴ. Դٰ ڵ :setting:`ROOT_URLCONF` (``settings.py`` ȿ ִ) ``mysite/urls.py`` Ű ߽ϴ.:: ROOT_URLCONF = 'mysite.urls' -Time for an example. Edit ``mysite/urls.py`` so it looks like this:: + Դϴ. ``mysite/urls.py`` Ʒ մϴ.:: from django.conf.urls import patterns, include, url @@ -91,85 +71,58 @@ Time for an example. Edit ``mysite/urls.py`` so it looks like this:: url(r'^admin/', include(admin.site.urls)), ) -This is worth a review. When somebody requests a page from your Web site -- say, -"/polls/23/", Django will load this Python module, because it's pointed to by -the :setting:`ROOT_URLCONF` setting. It finds the variable named ``urlpatterns`` -and traverses the regular expressions in order. When it finds a regular -expression that matches -- ``r'^polls/(?P\d+)/$'`` -- it loads the -function ``detail()`` from ``polls/views.py``. Finally, it calls that -``detail()`` function like so:: + ϵ մϴ. Ʈ "/polls/23/"̶ û ϸ, Django :setting:`ROOT_URLCONF` Ű ֱ ̽ ε Դϴ. ̽ ``urlpatterns`` ̸ ãϴ. ׸, ǥĵ traverses մϴ. ̽ ġϴ ǥ ã -- ``r'^polls/(?P\d+)/$'`` -- ̽ ``polls/views.py`` ִ ``detail()`` Լ ε մϴ. ħ, ̽ Ʒ ``detail()`` Լ ȣ մϴ. detail(request=, poll_id='23') -The ``poll_id='23'`` part comes from ``(?P\d+)``. Using parentheses -around a pattern "captures" the text matched by that pattern and sends it as an -argument to the view function; the ``?P`` defines the name that will be -used to identify the matched pattern; and ``\d+`` is a regular expression to -match a sequence of digits (i.e., a number). +``poll_id='23'`` ``(?P\d+)`` Դϴ. ȣ() ؼ ϰ ġϴ ؽƮ "captures"ϰ, Լ ڷ ϴ; ``?P`` ġϴ νϱ ̸ մϴ. ׸ ``\d+`` ڰ ; ǥԴϴ.( : ǥĿ \d 0~9 ڸ ǹϰ + ڰ 1 ̻ Ÿ ȴٴ ǹ մϴ. , 1 ̻ ڰ ȴٴ Դϴ. ) -Because the URL patterns are regular expressions, there really is no limit on -what you can do with them. And there's no need to add URL cruft such as ``.php`` --- unless you have a sick sense of humor, in which case you can do something -like this:: + URL ϵ ǥ̱ , ǥ ϵ ϴ. ׸, Ʒ ϴ ̰ ʴ ``.php`` URL ν ʿ䰡 ϴ :: (r'^polls/latest\.php$', 'polls.views.index'), -But, don't do that. It's silly. +׷, . ٺ ϱ. -Note that these regular expressions do not search GET and POST parameters, or -the domain name. For example, in a request to ``http://www.example.com/myapp/``, -the URLconf will look for ``myapp/``. In a request to -``http://www.example.com/myapp/?page=3``, the URLconf will look for ``myapp/``. +̷ ǥĵ GET, POST Ķ͵ Ǵ ̸ ˻ ʴ ٴ Ͻʽÿ. ``http://www.example.com/myapp/`` û, URLconf ``myapp/`` ã Դϴ. ``http://www.example.com/myapp/?page=3`` û, URLconf ``myapp/`` ã Դϴ. -If you need help with regular expressions, see `Wikipedia's entry`_ and the -documentation of the :mod:`re` module. Also, the O'Reilly book "Mastering -Regular Expressions" by Jeffrey Friedl is fantastic. +, ǥĿ ʿϸ, `Wikipedia's entry`_ ׸ :mod:`re` Ͻʽÿ. , Jeffrey Friedl ϸ å "Mastering Regular Expressions" ݴϴ. -Finally, a performance note: these regular expressions are compiled the first -time the URLconf module is loaded. They're super fast. +Finally, a performance note : ó URLconf ε Ǿ , ǥĵ ˴ϴ. URLconf û ϴ. .. _Wikipedia's entry: http://en.wikipedia.org/wiki/Regular_expression -Write your first view +ù ° ۼ ϱ ===================== -Well, we haven't created any views yet -- we just have the URLconf. But let's -make sure Django is following the URLconf properly. +츮 URLconf ϴ. ƹ 䵵 ʾҽϴ. ׷, Django Ʒ URLconf ö ִ Ȯ Ͻʽÿ. -Fire up the Django development Web server: +Django ⵿ ŵϴ. .. code-block:: bash python manage.py runserver -Now go to "http://localhost:8000/polls/" on your domain in your Web browser. -You should get a pleasantly-colored error page with the following message:: + "http://localhost:8000/polls/" ̵ Ͻʽÿ. + ϰ ÷ Ʒ ޼ Դϴ.:: ViewDoesNotExist at /polls/ Could not import polls.views.index. View does not exist in module polls.views. -This error happened because you haven't written a function ``index()`` in the -module ``polls/views.py``. + ``polls/views.py`` ⿡ ``index()`` Լ ۼ ϴ. -Try "/polls/23/", "/polls/23/results/" and "/polls/23/vote/". The error -messages tell you which view Django tried (and failed to find, because you -haven't written any views yet). +"/polls/23/", "/polls/23/results/" ׸ "/polls/23/vote/" õ ʽÿ. ޼ Django  信 Ϸ ߴ ˷ݴϴ(׸, ۼ ʾұ ã⿡ մϴ). -Time to write the first view. Open the file ``polls/views.py`` -and put the following Python code in it:: +ù ° 並 ۼ ð Դϴ. ``polls/views.py``  Ʒ ̽ ڵ带 Է մϴ.:: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the poll index.") -This is the simplest view possible. Go to "/polls/" in your browser, and you -should see your text. + Դϴ. "/polls/" ̵ϸ, ۼ ؽƮ ־ մϴ. -Now lets add a few more views. These views are slightly different, because -they take an argument (which, remember, is passed in from whatever was -captured by the regular expression in the URLconf):: +並 ߰ ϴ. ڸ ݾ ٸϴ. (ϼ, URLconf ǥ 'captured'Ǿ ڷ ɴϴ.) def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id) @@ -180,30 +133,19 @@ captured by the regular expression in the URLconf):: def vote(request, poll_id): return HttpResponse("You're voting on poll %s." % poll_id) -Take a look in your browser, at "/polls/34/". It'll run the `detail()` method -and display whatever ID you provide in the URL. Try "/polls/34/results/" and -"/polls/34/vote/" too -- these will display the placeholder results and voting -pages. + "/polls/34/" ѷ. `detail()` ޼ҵ带 ϰ, URL Է ID Ÿϴ. "/polls/34/results/" "/polls/34/vote/" õ . -- URL placeholder results ǥ ݴϴ. -Write views that actually do something + ϴ ۼ ϱ ====================================== -Each view is responsible for doing one of two things: Returning an -:class:`~django.http.HttpResponse` object containing the content for the -requested page, or raising an exception such as :exc:`~django.http.Http404`. The -rest is up to you. + ߿ ϳ մϴ. û ִ :class:`~django.http.HttpResponse` ü ȯ ϰų :exc:`~django.http.Http404` ܸ ߻մϴ. ſ ޷Ƚϴ. -Your view can read records from a database, or not. It can use a template -system such as Django's -- or a third-party Python template system -- or not. -It can generate a PDF file, output XML, create a ZIP file on the fly, anything -you want, using whatever Python libraries you want. + 並 ͺ̽ records , ƴҼ ֽϴ. Django ִ° ø ý ֽϴ. Ǵ Ƽ ̽ ø ý Ҽ, Ҽ ֽϴ. +PDF ϰų, XML ϰų, ZIP ϰų, ϵ ̵ ϴ ̽ ̺귯 Ͻʽÿ. -All Django wants is that :class:`~django.http.HttpResponse`. Or an exception. + Django ʿ :class:`~django.http.HttpResponse` Դϴ. Ǵ Դϴ. -Because it's convenient, let's use Django's own database API, which we covered -in :doc:`Tutorial 1 `. Here's one stab at the ``index()`` -view, which displays the latest 5 poll questions in the system, separated by -commas, according to publication date:: +ϱ ?, 츮 :doc:`Tutorial 1 ` ٷ Django ͺ̽ API ô. ¥ ϰ, ޸ , ýۿ ִ ֱ 5 ǥ ִ``index()`` 並 õ ô. from polls.models import Poll from django.http import HttpResponse @@ -213,9 +155,9 @@ commas, according to publication date:: output = ', '.join([p.question for p in latest_poll_list]) return HttpResponse(output) -There's a problem here, though: The page's design is hard-coded in the view. If + ڵ忡 ֽϴ. 信 ϵ ڵ ߽ϴ. , ̴ ¸ Ϸ Ѵٸ, ̽ ڵ带 ϰ ɰ Դϴ. you want to change the way the page looks, you'll have to edit this Python code. -So let's use Django's template system to separate the design from Python:: +׷Ƿ ̽κ иϱ ؼ Django ø ý ̿ غ մϴ. from django.template import Context, loader from polls.models import Poll @@ -229,28 +171,22 @@ So let's use Django's template system to separate the design from Python:: }) return HttpResponse(t.render(c)) -That code loads the template called "polls/index.html" and passes it a context. -The context is a dictionary mapping template variable names to Python objects. + ڵ "polls/index.html" ø ε ؼ ؽƮ մϴ. +ؽƮ ̽ ü ̸ ø Դϴ. -Reload the page. Now you'll see an error:: + ΰħ Ͻʽÿ. ɰ Դϴ:: TemplateDoesNotExist at /polls/ polls/index.html -Ah. There's no template yet. First, create a directory, somewhere on your -filesystem, whose contents Django can access. (Django runs as whatever user your -server runs.) Don't put them under your document root, though. You probably -shouldn't make them public, just for security's sake. -Then edit :setting:`TEMPLATE_DIRS` in your ``settings.py`` to tell Django where -it can find templates -- just as you did in the "Customize the admin look and -feel" section of Tutorial 2. +. ø . ù °, Ͻý ƹ Django ִ 丮 Ͻʽÿ. (Django runs as whatever user your +server runs.) , ϵ root . Ȼ , 丮 ۺ ʾƾ մϴ. +׸, ``settings.py`` :setting:`TEMPLATE_DIRS` ؼ, Django ø ã ִ ˷ ֽʽÿ. -- Turorial 2 "Customize the admin look and feel" ǿ Ѱ ó ϸ ˴ϴ. -When you've done that, create a directory ``polls`` in your template directory. -Within that, create a file called ``index.html``. Note that our -``loader.get_template('polls/index.html')`` code from above maps to -"[template_directory]/polls/index.html" on the filesystem. + Ϸ ߴٸ, ``polls`` 丮 ø 丮 ϼ. + ȿ ``index.html`` ϼ. 츮 ``loader.get_template('polls/index.html')`` ڵ ýۿ ִ "[template_directory]/polls/index.html" Ǵ Ͻʽÿ. -Put the following code in that template: +Ʒ ڵ带 ø Էϼ. .. code-block:: html+django @@ -264,17 +200,12 @@ Put the following code in that template:

No polls are available.

{% endif %} -Load the page in your Web browser, and you should see a bulleted-list -containing the "What's up" poll from Tutorial 1. The link points to the poll's -detail page. + εϸ, Turorial 1 "What's up" ǥ ϴ bulleted-list ־ մϴ. ũ ǥ ŵϴ. -A shortcut: render_to_response() + ڳ: render_to_response() -------------------------------- -It's a very common idiom to load a template, fill a context and return an -:class:`~django.http.HttpResponse` object with the result of the rendered -template. Django provides a shortcut. Here's the full ``index()`` view, -rewritten:: +render_to_response() ø εϰ, ؽƮ ä, :class:`~django.http.HttpResponse` ü ø Բ ȯϱ οϴ Դϴ. Django մϴ. ü ``index()`` 並 ۼ߽ϴ. from django.shortcuts import render_to_response from polls.models import Poll @@ -283,20 +214,15 @@ rewritten:: latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list}) -Note that once we've done this in all these views, we no longer need to import -:mod:`~django.template.loader`, :class:`~django.template.Context` and -:class:`~django.http.HttpResponse`. +츮 信 ؼ ѹ ϸ, ̻ :mod:`~django.template.loader`, :class:`~django.template.Context` and +:class:`~django.http.HttpResponse` ҷ ʿ䰡 ٴ ϼ. -The :func:`~django.shortcuts.render_to_response` function takes a template name -as its first argument and a dictionary as its optional second argument. It -returns an :class:`~django.http.HttpResponse` object of the given template -rendered with the given context. +:func:`~django.shortcuts.render_to_response` Լ ø ̸ ù ° ڷ, ° ڷ ϴ. Լ ־ ؽƮ Բ ø ü :class:`~django.http.HttpResponse` ȯ մϴ. -Raising 404 +404 =========== -Now, let's tackle the poll detail view -- the page that displays the question -for a given poll. Here's the view:: +, ǥ 並 ô. -- ־ ǥ ǥմϴ. 䰡 ֽϴ:: from django.http import Http404 # ... @@ -307,22 +233,18 @@ for a given poll. Here's the view:: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) -The new concept here: The view raises the :exc:`~django.http.Http404` exception -if a poll with the requested ID doesn't exist. + ֽϴ. ǥ Բ û ID 䰡 :exc:`~django.http.Http404`ܸ ϴ. -We'll discuss what you could put in that ``polls/detail.html`` template a bit -later, but if you'd like to quickly get the above example working, just:: +츮 ߿ `polls/detail.html`` Դϴ. ׷, ϰ ʹٸ, :: {{ poll }} -will get you started for now. +ڵ尡 ݺ ֵ մϴ. -A shortcut: get_object_or_404() + ڳ: get_object_or_404() ------------------------------- -It's a very common idiom to use :meth:`~django.db.models.query.QuerySet.get` -and raise :exc:`~django.http.Http404` if the object doesn't exist. Django -provides a shortcut. Here's the ``detail()`` view, rewritten:: +get_object_or404() :meth:`~django.db.models.query.QuerySet.get` ϰ, ü :exc:`~django.http.Http404` ϴ Դϴ. Django մϴ. ``detail()`` 並 ۼ ߽ϴ.:: from django.shortcuts import render_to_response, get_object_or_404 # ... @@ -330,69 +252,48 @@ provides a shortcut. Here's the ``detail()`` view, rewritten:: p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p}) -The :func:`~django.shortcuts.get_object_or_404` function takes a Django model -as its first argument and an arbitrary number of keyword arguments, which it -passes to the module's :meth:`~django.db.models.query.QuerySet.get` function. -It raises :exc:`~django.http.Http404` if the object doesn't exist. +:func:`~django.shortcuts.get_object_or_404`Լ DJango ù ° ڷ ް, :meth:`~django.db.models.query.QuerySet.get` Լ ڸ Ű ڷ ޽ϴ. , ü , :exc:`~django.http.Http404` ϴ. -.. admonition:: Philosophy +.. :: ö - Why do we use a helper function :func:`~django.shortcuts.get_object_or_404` + 츮 :exc:`~django.core.exceptions.ObjectDoesNotExist` ؼ ڵ ܸ óϴ Լ :func:`~django.shortcuts.get_object_or_404` ? instead of automatically catching the :exc:`~django.core.exceptions.ObjectDoesNotExist` exceptions at a higher - level, or having the model API raise :exc:`~django.http.Http404` instead of + Ǵ :exc:`~django.core.exceptions.ObjectDoesNotExist` ϴ :exc:`~django.http.Http404` API ? :exc:`~django.core.exceptions.ObjectDoesNotExist`? - Because that would couple the model layer to the view layer. One of the - foremost design goals of Django is to maintain loose coupling. + ϱ ̴. One of the + Django 䰡 ǥ ϳ ϴ ̴. -There's also a :func:`~django.shortcuts.get_list_or_404` function, which works -just as :func:`~django.shortcuts.get_object_or_404` -- except using -:meth:`~django.db.models.query.QuerySet.filter` instead of -:meth:`~django.db.models.query.QuerySet.get`. It raises -:exc:`~django.http.Http404` if the list is empty. + :func:`~django.shortcuts.get_object_or_404` Ȱ ϴ :func:`~django.shortcuts.get_list_or_404` Լ ִ. -- :meth:`~django.db.models.query.QuerySet.get` :meth:`~django.db.models.query.QuerySet.filter` ϴ Ѵ. :func:`~django.shortcuts.get_list_or_404` Ʈ 쿡 :exc:`~django.http.Http404` . -Write a 404 (page not found) view +404 (page not found) ۼϱ ================================= -When you raise :exc:`~django.http.Http404` from within a view, Django -will load a special view devoted to handling 404 errors. It finds it -by looking for the variable ``handler404`` in your root URLconf (and -only in your root URLconf; setting ``handler404`` anywhere else will -have no effect), which is a string in Python dotted syntax -- the same -format the normal URLconf callbacks use. A 404 view itself has nothing -special: It's just a normal view. - -You normally won't have to bother with writing 404 views. If you don't set -``handler404``, the built-in view :func:`django.views.defaults.page_not_found` -is used by default. In this case, you still have one obligation: create a -``404.html`` template in the root of your template directory. The default 404 -view will use that template for all 404 errors. If :setting:`DEBUG` is set to -``False`` (in your settings module) and if you didn't create a ``404.html`` -file, an ``Http500`` is raised instead. So remember to create a ``404.html``. - -A couple more things to note about 404 views: - -* If :setting:`DEBUG` is set to ``True`` (in your settings module) then your + 信 :exc:`~django.http.Http404` Ű, Django 404 ٷ Ư 並 ε ̴. Djnago Ʈ URLconf(׸ Ʈ URLconf ``handler404`` ؾ Ѵ. ̿ ġ õȴ.) ``handler404`` string in python dotted syntax ãμ 404 ٷ Ư 並 ã ̴. -- · Ϲ URLconf ݹ Ѵ. 404 üδ ƯѰ ƹ͵ . Ϲ ̴. + +Ϲ 404 µ Ű澵 ʿ䰡 . ``handler404`` , :func:`django.views.defaults.page_not_found` + ⺻ Ѵ. 쿡 ִ. ``404.html`` ø rootø 丮 ؾ Ѵ. ⺻ 404 ø 404 ̴. :setting:`DEBUG` ``False`` (in your settings module) ϰų, ``404.html`` + , ``Http500`` . ׷Ƿ ``404.html`` ϴ . + +404 鿡 ؼ ˾Ƶξ Ұ ִ. + +* :setting:`DEBUG` ``True`` ߴٸ( ȿ) 404 ̴.(׸ ``404.html`` ø ʴ´). ֳϸ traceback ǥϱ ̴. 404 view will never be used (and thus the ``404.html`` template will never be rendered) because the traceback will be displayed instead. -* The 404 view is also called if Django doesn't find a match after checking +* 404 Django URLconf ǥ ˻ϰ, ġϴ ǥ ã ȣѴ. every regular expression in the URLconf. -Write a 500 (server error) view +500 (server error) ۼϱ =============================== -Similarly, your root URLconf may define a ``handler500``, which points -to a view to call in case of server errors. Server errors happen when -you have runtime errors in view code. +ϰ, Ʈ URLconf Ƹ 쿡 ȣϱ 並 Ű ``handler500`` ϰ ִ. ڵ忡 Ÿ ߻Ѵ. -Use the template system +ø ý ϱ ======================= -Back to the ``detail()`` view for our poll application. Given the context -variable ``poll``, here's what the "polls/detail.html" template might look -like: +츮 ǥ ø̼ ``detail()`` ư . ``poll`` ؽƮ ־, "polls/detail.html" ø  Ǵ : .. code-block:: html+django @@ -403,24 +304,17 @@ like: {% endfor %} -The template system uses dot-lookup syntax to access variable attributes. In -the example of ``{{ poll.question }}``, first Django does a dictionary lookup -on the object ``poll``. Failing that, it tries an attribute lookup -- which -works, in this case. If attribute lookup had failed, it would've tried a -list-index lookup. +ø ý Ӽ鿡 ϱ ؼ dot-lookup Ѵ. ``{{ poll.question }}`` , Django ó ``poll`` ü ã´. ã⿡ ϸ, ƮƮ ȸ Ѵ. -- which works, in this case. , ƮƮ ȸ ϸ, list-index ȸ õ Ѵ. -Method-calling happens in the :ttag:`{% for %}` loop: -``poll.choice_set.all`` is interpreted as the Python code -``poll.choice_set.all()``, which returns an iterable of Choice objects and is -suitable for use in the :ttag:`{% for %}` tag. +:ttag:`{% for %}` ޼ҵ ȣ ߻Ѵ: +``poll.choice_set.all`` ̽ ڵ ``poll.choice_set.all()`` ȯ Ѵ. ̽ ڵ ``poll.choice_set.all()`` ü an iterable ȯϰ, :ttag:`{% for %}` ±׿ ϱ ˸´. -See the :doc:`template guide ` for more about templates. +ø ڼ :doc:`template guide ` . -Simplifying the URLconfs +URLconfs ܼȭ ϱ ======================== -Take some time to play around with the views and template system. As you edit -the URLconf, you may notice there's a fair bit of redundancy in it:: + ø ýۻ̸ Ⱦ ϱ⿡ ð ɸϴ. URLconf ó, ȿ ʿ ߺ ִٴ ˾ Դϴ. urlpatterns = patterns('', url(r'^polls/$', 'polls.views.index'), @@ -429,11 +323,9 @@ the URLconf, you may notice there's a fair bit of redundancy in it:: url(r'^polls/(?P\d+)/vote/$', 'polls.views.vote'), ) -Namely, ``polls.views`` is in every callback. +ٽø ``polls.views`` ݹ鿡 ġ մϴ. -Because this is a common case, the URLconf framework provides a shortcut for -common prefixes. You can factor out the common prefixes and add them as the -first argument to :func:`~django.conf.urls.patterns`, like so:: +ֳϸ common case, URLconf ӿũ prefixs鿡 մϴ. prefixes ̾ ֽϴ. ׸, ̾Ƴ prefixes :func:`~django.conf.urls.patterns` Ʒ ù ° ڷ ߰ ֽϴ. :: urlpatterns = patterns('polls.views', url(r'^polls/$', 'index'), @@ -442,13 +334,10 @@ first argument to :func:`~django.conf.urls.patterns`, like so:: url(r'^polls/(?P\d+)/vote/$', 'vote'), ) -This is functionally identical to the previous formatting. It's just a bit -tidier. + ð ġ մϴ. մϴ. -Since you generally don't want the prefix for one app to be applied to every -callback in your URLconf, you can concatenate multiple -:func:`~django.conf.urls.patterns`. Your full ``mysite/urls.py`` might -now look like this:: +Ϲ URLconf ݹ鿡 ϳ ø̼ prefix ϰ ʴٸ, :func:`~django.conf.urls.patterns` ֽϴ. +. ``mysite/urls.py`` ü Ʒ ϴ. :: from django.conf.urls import patterns, include, url @@ -466,25 +355,16 @@ now look like this:: url(r'^admin/', include(admin.site.urls)), ) -Decoupling the URLconfs +URLconf յ ߱ ======================= -While we're at it, we should take the time to decouple our poll-app URLs from -our Django project configuration. Django apps are meant to be pluggable -- that -is, each particular app should be transferable to another Django installation -with minimal fuss. +while we're at it, 츮 Django Ʈ 츮 ǥ- URL иϴ ð մϴ. Django ۵ pluggable ϵ Ǿ ֽϴ. -- Ư ּ ٸ Django installation ؾ մϴ. -Our poll app is pretty decoupled at this point, thanks to the strict directory -structure that ``python manage.py startapp`` created, but one part of it is -coupled to the Django settings: The URLconf. +츮 ǥ иǾ ֽϴ. ``python manage.py startapp`` 丮 Ͻʽÿ. ׷, URLconf ϳ Django յǾ ֽϴ. -We've been editing the URLs in ``mysite/urls.py``, but the URL design of an -app is specific to the app, not to the Django installation -- so let's move the -URLs within the app directory. + 츮 ``mysite/urls.py`` ִ URL ߽ϴ. ׷, URL Django installation ƴ϶, Ư Դϴ. -- ׷ URL 丮 ̵ մϴ. -Copy the file ``mysite/urls.py`` to ``polls/urls.py``. Then, change -``mysite/urls.py`` to remove the poll-specific URLs and insert an -:func:`~django.conf.urls.include`, leaving you with:: +``mysite/urls.py`` ``polls/urls.py`` Ͻʽÿ. ׸, ``mysite/urls.py`` ǥ- URL ϰ, :func:`~django.conf.urls.include` ڸ ߰ ϵ մϴ:: from django.conf.urls import patterns, include, url @@ -496,25 +376,19 @@ Copy the file ``mysite/urls.py`` to ``polls/urls.py``. Then, change url(r'^admin/', include(admin.site.urls)), ) -:func:`~django.conf.urls.include` simply references another URLconf. -Note that the regular expression doesn't have a ``$`` (end-of-string match -character) but has the trailing slash. Whenever Django encounters -:func:`~django.conf.urls.include`, it chops off whatever part of the -URL matched up to that point and sends the remaining string to the included -URLconf for further processing. +:func:`~django.conf.urls.include` ϰ ٸ URLconf մϴ. +ǥ ``$``(ڿ ġϴ ) ʰ, trailling slash ϼ. Django :func:`~django.conf.urls.include` Լ , it chops off whatever part of the +URL matched up to that point ׸ ߰ ó ؼ URLconf ڿ մϴ. -Here's what happens if a user goes to "/polls/34/" in this system: +ڰ ýۿ "/polls/34/" ̵ϴ 쿡 ߻ϴ ô: -* Django will find the match at ``'^polls/'`` +* Django ``'^polls/'`` ġϴ ãԴϴ. -* Then, Django will strip off the matching text (``"polls/"``) and send the - remaining text -- ``"34/"`` -- to the 'polls.urls' URLconf for +* ׸, Django ġϴ (``"polls/"``) Դϴ. ׸ + -- ``"34/"`` -- 'polls.urls' URLconf ߰ ó ؼ ϴ. further processing. -Now that we've decoupled that, we need to decouple the ``polls.urls`` -URLconf by removing the leading "polls/" from each line, and removing the -lines registering the admin site. Your ``polls/urls.py`` file should now look like -this:: +, URLconf Django յ ߾ϴ. 츮 տ ִ "polls/" ϰ, Ʈ ε ν ``polls.urls`` URLconf յ ߾ϴ. ``polls/urls.py`` Ʒ ƾ մϴ. :: from django.conf.urls import patterns, include, url @@ -525,12 +399,9 @@ this:: url(r'^(?P\d+)/vote/$', 'vote'), ) -The idea behind :func:`~django.conf.urls.include` and URLconf -decoupling is to make it easy to plug-and-play URLs. Now that polls are in their -own URLconf, they can be placed under "/polls/", or under "/fun_polls/", or -under "/content/polls/", or any other path root, and the app will still work. +:func:`~django.conf.urls.include` URLconf յ ߴ ̵ URL plug-and-play ݴϴ. , ǥ URLconf ֽϴ. ǥ "/polls/" ؿ ְ, "/fun_polls/" ؿ, "/content/polls/" ؿ, ׸ ٸ  root ֽϴ. ׸ Դϴ. -All the poll app cares about is its relative path, not its absolute path. + ǥ ۵ ΰ ƴ϶, θ մϴ. -When you're comfortable with writing views, read :doc:`part 4 of this tutorial -` to learn about simple form processing and generic views. + 並 ۼ ϴ Ϳ ͼ ܼ ó ʸ 並 ؼ :doc:`part 4 of this tutorial +` оʽÿ. From d8fa0acea16d17df9d2f84112cca07ab6fdc5f9e Mon Sep 17 00:00:00 2001 From: HyunJin Moon Date: Wed, 15 Aug 2012 13:51:39 +0900 Subject: [PATCH 022/128] Update intro/tutorial03.txt --- intro/tutorial03.txt | 236 +++++++++++++++++++++---------------------- 1 file changed, 118 insertions(+), 118 deletions(-) diff --git a/intro/tutorial03.txt b/intro/tutorial03.txt index ad526b3..c16e6d2 100644 --- a/intro/tutorial03.txt +++ b/intro/tutorial03.txt @@ -2,61 +2,61 @@ Writing your first Django app, part 3 ===================================== - ڽ :doc:`Tutorial 2 ` ̾ մϴ. , 츮 ؼ "" ϴ ۺ ̽ ۼϴµ ΰ -ǥ ø̼ մϴ. +이 자습서는 :doc:`Tutorial 2 `의 마지막에 이어서 시작 합니다. 자, 우리는 계속해서 "뷰"라고 하는 퍼블릭 인터페이스를 작성하는데 중점을 두고 웹-투표 어플리케이션을 진행 합니다. -ö +철학 ========== - Django ø̼ǿ Ư ϰų, Ư ø "Ÿ" Դϴ. α ø̼ǿ Ʒ ֽϴ. +뷰는 Django 어플리케이션에서 특정한 기능을 수행하거나, 특정한 템플릿을 가지는 웹 페이지의 "타입" 입니다. 예를 들어 웹블로그 어플리케이션에는 아래와 같은 뷰들을 가질 수 있습니다. -* α Ȩ -- ֽ Ʈ  display մϴ. +* 블로그 홈페이지 -- 최신 엔트리를 몇개 display 합니다. -* Ʈ "" -- Ʈ ۸Ӹũ Դϴ. +* 엔트리 "세부" 페이지 -- 한 개의 엔트리를 위한 퍼머링크 입니다. -* ī̺ -- ־ ִ Ʈ Բ Ÿϴ. +* 연도별 아카이브 페이지 -- 주어진 연도에 있는 모든 달을 엔트리와 함께 나타냅니다. given year. -* ī̺ -- ־ ޿ ִ Ʈ Բ Ÿϴ. +* 월별 아카이브 페이지 -- 주어진 달에 있는 모든 날을 엔트리와 함께 나타냅니다. given month. -* Ϻ ī̺ -- ־ ִ Ʈ Ÿϴ. +* 일별 아카이브 페이지 -- 주어진 날에 있는 모든 엔트리를 나타냅니다. -* ڸƮ ޱ -- ־ Ʈ ڸƮ մϴ. +* 코멘트 달기 -- 주어진 엔트리에 코멘트를 포스팅 합니다. -츮 ǥ ø̼ǿ Ʒ 䰡 ֽϴ. +우리 투표 어플리케이션에는 아래와 같이 네 개의 뷰가 있습니다. -* ǥ "ε" -- ֱ ǥ Ÿϴ. +* 투표 "인덱스" 페이지 -- 최근 몇 개의 투표를 나타냅니다. -* ǥ "" -- ǥ ǥ ִ Բ Ÿϴ. ʽϴ. +* 투표 "세부" 페이지 -- 투표의 질문을 투표 할 수 있는 폼과 함께 나타냅니다. 질문은 보여주지 않습니다. with a form to vote. -* ǥ "" -- Ư ǥ Ÿϴ. +* 투표 "결과" 페이지 -- 특정 투표의 결과를 나타냅니다. -* ǥ ϱ -- Ư ǥ Ư ǥմϴ. +* 투표 하기 -- 특정 투표에서 특정 선택지에 투표합니다. poll. -Django ̽ Լ Ÿ ֽϴ. +Django 에서 개별 뷰는 간단한 파이썬 함수로 나타낼수 있습니다. -URL ϱ +URL 디자인 하기 ================ -URL ϴ 並 ۼϴ ù ° ܰԴϴ. URLconf ̽ μ, URL ֽϴ. URLconfs DJango ־ URL ־ ̽ ڵ ϴ Դϴ. +URL 구조를 디자인 하는 것은 뷰를 작성하는 첫 번째 단계입니다. 당신은 URLconf라는 파이썬 모듈을 생성함으로서, URL구조를 디자인 할 수 있습니다. URLconfs는 DJango가 주어진 URL을 주어진 파이썬 코드와 연결하는 방법 입니다. -ڰ Django-powerd û , ý Python dotted syntax ִ ڿ ϴ :setting:'ROOT_URLCONF' մϴ. Django URLconf ε մϴ. ׸, Ʒ Ʃ - ``urlpatterns`` ˻ մϴ. +사용자가 Django-powerd 페이지를 요청 할 때, 시스템은 Python dotted syntax에 있는 문자열을 포함하는 :setting:'ROOT_URLCONF' 설정을 참고 합니다. Django 는 URLconf 모듈을 로드 합니다. 그리고, 아래와 같은 포맷의 튜플인 모듈-레벨 변수인 ``urlpatterns``를 검색 합니다. (regular expression, Python callback function [, optional dictionary]) -DJango ù ° ǥĿ ؼ, ġϴ ã û URL ǥİ ϸ鼭 Ʈ Ʒ ϴ. +DJango는 첫 번째 정규표현식에서 시작 해서, 일치하는 결과를 찾을 때 까지 요청 받은 URL을 개별 정규표현식과 비교하면서 리스트 아래로 내려갑니다. - ġϴ ã, Django ̽ ݹ Լ ȣ մϴ. , :class:`~django.http.HttpRequest` ü ù ° ڷ ϰ, ǥĿ ã ƹ keyword ڷ մϴ. ɼ the dictionaryκ ƹ keyword մϴ.(Ʃ ° ). + 일치하는 결과를 찾으면, Django는 파이썬 콜백 함수를 호출 합니다. 이 때, :class:`~django.http.HttpRequest` 객체를 첫 번째 인자로 하고, 정규표현식에서 찾은 아무 값을 keyword 인자로 합니다. 옵션으로 the dictionary로부터 아무 keyword를 사용 합니다.(튜플의 임의의 세번째 아이템). -:class:`~django.http.HttpRequest` ü ؼ ڼ ˰ ʹٸ, :doc:`/ref/request-response` ϼ. URLconfs ؼ ڼ ˰ ʹٸ, :doc:`/topics/http/urls` ϼ. +:class:`~django.http.HttpRequest` 객체에 대해서 자세히 알고 싶다면, :doc:`/ref/request-response` 를 참고 하세요. URLconfs 에 대해서 자세히 알고 싶다면, :doc:`/topics/http/urls`를 참고 하세요. -ڽ 1 ó ``django-admin.py startproject mysite`` , ⺻ URLconf ``mysite/urls.py`` ߽ϴ. Դٰ ڵ :setting:`ROOT_URLCONF` (``settings.py`` ȿ ִ) ``mysite/urls.py`` Ű ߽ϴ.:: +자습서 1에서 처음 ``django-admin.py startproject mysite`` 를 실행 했을때, 기본 URLconf를 ``mysite/urls.py``에 생성 했습니다. 게다가 자동으로 :setting:`ROOT_URLCONF` 설정을(``settings.py`` 안에 있는) ``mysite/urls.py``를 가리키도록 설정 했습니다.:: ROOT_URLCONF = 'mysite.urls' - Դϴ. ``mysite/urls.py`` Ʒ մϴ.:: +예제를 볼 차례 입니다. ``mysite/urls.py``를 아래와 같이 수정 합니다.:: from django.conf.urls import patterns, include, url @@ -71,58 +71,58 @@ DJango url(r'^admin/', include(admin.site.urls)), ) - ϵ մϴ. Ʈ "/polls/23/"̶ û ϸ, Django :setting:`ROOT_URLCONF` Ű ֱ ̽ ε Դϴ. ̽ ``urlpatterns`` ̸ ãϴ. ׸, ǥĵ traverses մϴ. ̽ ġϴ ǥ ã -- ``r'^polls/(?P\d+)/$'`` -- ̽ ``polls/views.py`` ִ ``detail()`` Լ ε մϴ. ħ, ̽ Ʒ ``detail()`` Լ ȣ մϴ. +여기까지를 리뷰 하도록 합니다. 누군가가 당신의 웹 사이트에 "/polls/23/"이라는 요청을 하면, Django는 :setting:`ROOT_URLCONF` 설정이 가리키고 있기 때문에 이 파이썬 모듈을 로드 할 것 입니다. 위의 파이썬 모듈은 ``urlpatterns``라는 이름을 가진 변수를 찾습니다. 그리고, 정규표현식들을 순서대로 traverses 합니다. 위의 파이썬 모듈이 일치하는 정규표현식을 찾았을때 -- ``r'^polls/(?P\d+)/$'`` -- 위의 파이썬 모듈은 ``polls/views.py``에 있는 ``detail()`` 함수를 로드 합니다. 마침내, 파이썬 모듈은 아래와 같이 ``detail()`` 함수를 호출 합니다. detail(request=, poll_id='23') -``poll_id='23'`` ``(?P\d+)`` Դϴ. ȣ() ؼ ϰ ġϴ ؽƮ "captures"ϰ, Լ ڷ ϴ; ``?P`` ġϴ νϱ ̸ մϴ. ׸ ``\d+`` ڰ ; ǥԴϴ.( : ǥĿ \d 0~9 ڸ ǹϰ + ڰ 1 ̻ Ÿ ȴٴ ǹ մϴ. , 1 ̻ ڰ ȴٴ Դϴ. ) +``poll_id='23'``는 ``(?P\d+)``에서 온 것 입니다. 패턴 주위에 괄호()를 사용해서 그 패턴과 일치하는 텍스트를 "captures"하고, 뷰 함수에게 인자로 보냅니다; ``?P``는 일치하는 패턴을 인식하기 위한 이름을 정의 합니다. 그리고 ``\d+``는 숫자가 나와야 할 순서라는 정규표현식입니다.(역자 주: 정규 표현식에서 \d는 0~9 사이의 숫자를 의미하고 +는 앞 문자가 1번 이상 나타나면 된다는 것을 의미 합니다. 따라서, 1개 이상의 숫자가 있으면 된다는 뜻입니다. ) - URL ϵ ǥ̱ , ǥ ϵ ϴ. ׸, Ʒ ϴ ̰ ʴ ``.php`` URL ν ʿ䰡 ϴ :: + URL 패턴들은 정규표현식이기 때문에, 당신이 정규표현식으로 무엇을 하든 제한이 없습니다. 그리고, 당신이 아래와 같이 하는 악취미가 있지 않는 한은 ``.php``같은 URL 부스러기 들을 붙일 필요가 없습니다 :: (r'^polls/latest\.php$', 'polls.views.index'), -׷, . ٺ ϱ. +그렇지만, 하지마세요. 바보 같으니까요. -̷ ǥĵ GET, POST Ķ͵ Ǵ ̸ ˻ ʴ ٴ Ͻʽÿ. ``http://www.example.com/myapp/`` û, URLconf ``myapp/`` ã Դϴ. ``http://www.example.com/myapp/?page=3`` û, URLconf ``myapp/`` ã Դϴ. +이런 정규표현식들은 GET, POST 파라미터들 또는 도메인 이름을 검색하지는 않는 다는 것을 기억하십시오. 예를 들어 ``http://www.example.com/myapp/``을 향한 요청에서, URLconf는 ``myapp/``만 찾을 것 입니다. ``http://www.example.com/myapp/?page=3``를 향한 요청에서, URLconf는 ``myapp/``만 찾을 것 입니다. -, ǥĿ ʿϸ, `Wikipedia's entry`_ ׸ :mod:`re` Ͻʽÿ. , Jeffrey Friedl ϸ å "Mastering Regular Expressions" ݴϴ. +만약, 정규표현식에 대해 도움이 필요하면, `Wikipedia's entry`_ 그리고 :mod:`re` 모듈의 문서를 참고 하십시오. 또, Jeffrey Friedl 의 오라일리의 책 "Mastering Regular Expressions" 도 끝내줍니다. -Finally, a performance note : ó URLconf ε Ǿ , ǥĵ ˴ϴ. URLconf û ϴ. +Finally, a performance note : 처음 URLconf 모듈이 로드 되어 있을때, 이 정규표현식들은 컴파일 됩니다. URLconf는 엄청나게 빠릅니다. .. _Wikipedia's entry: http://en.wikipedia.org/wiki/Regular_expression -ù ° ۼ ϱ +첫 번째 뷰 작성 하기 ===================== -츮 URLconf ϴ. ƹ 䵵 ʾҽϴ. ׷, Django Ʒ URLconf ö ִ Ȯ Ͻʽÿ. +우리는 단지 URLconf 만 만들 었습니다. 아직 아무런 뷰도 생성 하지 않았습니다. 그렇지만, Django가 아래의 URLconf를 철저히 따르고 있는지 확인 하십시오. -Django ⵿ ŵϴ. +Django 개발 웹 서버를 출동 시킵니다. .. code-block:: bash python manage.py runserver - "http://localhost:8000/polls/" ̵ Ͻʽÿ. - ϰ ÷ Ʒ ޼ Դϴ.:: +웹브라우져에서 "http://localhost:8000/polls/" 로 이동 하십시오. +당신은 유쾌하게 컬러링된 아래와 같은 메세지의 에러 페이지를 보게 될 것 입니다.:: ViewDoesNotExist at /polls/ Could not import polls.views.index. View does not exist in module polls.views. - ``polls/views.py`` ⿡ ``index()`` Լ ۼ ϴ. +이 에러는 ``polls/views.py`` 모듈에 ``index()`` 함수를 작성한 적이 없기 때문에 생겼습니다. -"/polls/23/", "/polls/23/results/" ׸ "/polls/23/vote/" õ ʽÿ. ޼ Django  信 Ϸ ߴ ˷ݴϴ(׸, ۼ ʾұ ã⿡ մϴ). +"/polls/23/", "/polls/23/results/" 그리고 "/polls/23/vote/" 도 시도해 보십시오. 에러 메세지들은 Django가 어떤 뷰에 접근 하려고 했는지 알려줍니다(그리고, 당신이 뷰들을 작성 하지 않았기 때문에 찾기에 실패 합니다). -ù ° 並 ۼ ð Դϴ. ``polls/views.py``  Ʒ ̽ ڵ带 Է մϴ.:: +첫 번 째 뷰를 작성 할 시간 입니다. ``polls/views.py``를 열어서 아래의 파이썬 코드를 입력 합니다.:: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the poll index.") - Դϴ. "/polls/" ̵ϸ, ۼ ؽƮ ־ մϴ. +실제로 가능한 가장 간단한 뷰 입니다. 브라우저에서 "/polls/" 로 이동하면, 당신이 작성한 텍스트를 볼 수 있어야 합니다. -並 ߰ ϴ. ڸ ݾ ٸϴ. (ϼ, URLconf ǥ 'captured'Ǿ ڷ ɴϴ.) +뷰를 몇 개 더 추가해 봅니다. 이 뷰들은 인자를 가지기 때문에 조금씩 다릅니다. (기억하세요, URLconf에서 정규표현식으로 무엇이 'captured'되었든지 인자로 들어옵니다.) def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id) @@ -133,19 +133,19 @@ Django def vote(request, poll_id): return HttpResponse("You're voting on poll %s." % poll_id) - "/polls/34/" ѷ. `detail()` ޼ҵ带 ϰ, URL Է ID Ÿϴ. "/polls/34/results/" "/polls/34/vote/" õ . -- URL placeholder results ǥ ݴϴ. +브라우저에서 "/polls/34/"를 둘러보세요. `detail()` 메소드를 실행하고, 당신이 URL에 입력한 ID를 나타냅니다. "/polls/34/results/"과 "/polls/34/vote/"도 시도해 보세요. -- 이 URL들은 placeholder results와 투표 페이지 를 보여줍니다. - ϴ ۼ ϱ +실제로 동작하는 뷰 작성 하기 ====================================== - ߿ ϳ մϴ. û ִ :class:`~django.http.HttpResponse` ü ȯ ϰų :exc:`~django.http.Http404` ܸ ߻մϴ. ſ ޷Ƚϴ. + 각각의 뷰는 둘 중에 하나를 수행합니다. 요청받은 페이지에 대한 컨텐츠를 가지고 있는 :class:`~django.http.HttpResponse` 객체를 반환 하거나 :exc:`~django.http.Http404` 같은 예외를 발생합니다. 나머지는 당신에게 달렸습니다. - 並 ͺ̽ records , ƴҼ ֽϴ. Django ִ° ø ý ֽϴ. Ǵ Ƽ ̽ ø ý Ҽ, Ҽ ֽϴ. -PDF ϰų, XML ϰų, ZIP ϰų, ϵ ̵ ϴ ̽ ̺귯 Ͻʽÿ. +당신의 뷰를 데이터베이스에서 records들을 읽을수도, 아닐수도 있습니다. Django에 있는것 같은 템플릿 시스템을 사용 할 수도 있습니다. 또는 서드 파티 파이썬 템플릿 시스템을 사용할수도, 안할수도 있습니다. +PDF 파일을 생성하거나, XML을 출력하거나, ZIP파일을 생성하거나, 당신이 무엇을 원하든 간에 무엇이든 원하는 파이썬 라이브러리들을 사용 하십시오. - Django ʿ :class:`~django.http.HttpResponse` Դϴ. Ǵ Դϴ. +모든 Django가 필요한 것은 :class:`~django.http.HttpResponse` 입니다. 또는 예외 입니다. -ϱ ?, 츮 :doc:`Tutorial 1 ` ٷ Django ͺ̽ API ô. ¥ ϰ, ޸ , ýۿ ִ ֱ 5 ǥ ִ``index()`` 並 õ ô. +사용하기 쉽기 ?문에, 우리가 :doc:`Tutorial 1 `에서 다루었던 Django만의 데이터베이스 API를 사용해 봅시다. 여기 날짜 순서로 정렬하고, 콤마로 나눈, 시스템에 있는 최근 5개의 투표 질문들을 보여주는``index()`` 뷰를 시도해 봅시다. from polls.models import Poll from django.http import HttpResponse @@ -155,9 +155,9 @@ PDF output = ', '.join([p.question for p in latest_poll_list]) return HttpResponse(output) - ڵ忡 ֽϴ. 信 ϵ ڵ ߽ϴ. , ̴ ¸ Ϸ Ѵٸ, ̽ ڵ带 ϰ ɰ Դϴ. +위에 코드에는 문제가 있습니다. 페이지 디자인을 뷰에 하드 코딩 했습니다. 만약, 당신이 페이지가 보이는 형태를 변경 하려고 한다면, 이 파이썬 코드를 수정 하게 될것 입니다. you want to change the way the page looks, you'll have to edit this Python code. -׷Ƿ ̽κ иϱ ؼ Django ø ý ̿ غ մϴ. +그러므로 디자인을 파이썬으로부터 분리하기 위해서 Django의 템플릿 시스템을 이용 해보도록 합니다. from django.template import Context, loader from polls.models import Poll @@ -171,22 +171,22 @@ you want to change the way the page looks, you'll have to edit this Python code. }) return HttpResponse(t.render(c)) - ڵ "polls/index.html" ø ε ؼ ؽƮ մϴ. -ؽƮ ̽ ü ̸ ø Դϴ. +위의 코드는 "polls/index.html" 템플릿을 로드 해서 컨텍스트를 전달 합니다. +컨텍스트는 파이썬 객체들 이름을 가진 사전 매핑 템플릿 변수 입니다. - ΰħ Ͻʽÿ. ɰ Դϴ:: +페이지를 새로고침 하십시오. 에러를 보게 될것 입니다:: TemplateDoesNotExist at /polls/ polls/index.html -. ø . ù °, Ͻý ƹ Django ִ 丮 Ͻʽÿ. (Django runs as whatever user your -server runs.) , ϵ root . Ȼ , 丮 ۺ ʾƾ մϴ. -׸, ``settings.py`` :setting:`TEMPLATE_DIRS` ؼ, Django ø ã ִ ˷ ֽʽÿ. -- Turorial 2 "Customize the admin look and feel" ǿ Ѱ ó ϸ ˴ϴ. +아. 아직 템플릿이 없군요. 첫 번째, 당신의 파일시스템 아무데나 Django가 접근 할 수 있는 곳에 디렉토리를 생성 하십시오. (Django runs as whatever user your +server runs.) 대신, 그 파일들은 당신의 문서 root에 넣지 마세요. 보안상의 이유로, 그 디렉토리를 퍼블릭으로 만들지 않아야 합니다. +그리고, ``settings.py``의 :setting:`TEMPLATE_DIRS`를 수정해서, Django에게 어디서 템플릿들을 찾을 수 있는지 알려 주십시오. -- Turorial 2의 "Customize the admin look and feel" 섹션에서 한것 처럼 하면 됩니다. - Ϸ ߴٸ, ``polls`` 丮 ø 丮 ϼ. - ȿ ``index.html`` ϼ. 츮 ``loader.get_template('polls/index.html')`` ڵ ýۿ ִ "[template_directory]/polls/index.html" Ǵ Ͻʽÿ. +위의 내용을 완료 했다면, ``polls`` 디렉토리를 를 당신의 템플릿 디렉토리에 생성 하세요. +그 안에 ``index.html`` 파일을 생성하세요. 우리의 ``loader.get_template('polls/index.html')`` 코드는 파일 시스템에 있는 "[template_directory]/polls/index.html" 과 매핑 되는 것을 기억하십시오. -Ʒ ڵ带 ø Էϼ. +아래의 코드를 템플릿에 입력하세요. .. code-block:: html+django @@ -200,12 +200,12 @@ server runs.)

No polls are available.

{% endif %} - εϸ, Turorial 1 "What's up" ǥ ϴ bulleted-list ־ մϴ. ũ ǥ ŵϴ. +웹 브라우저에서 페이지를 로드하면, Turorial 1의 "What's up" 투표를 포함하는 bulleted-list를 볼 수 있어야 합니다. 이 링크는 그 투표의 세부 페이지를 가리킵니다. - ڳ: render_to_response() +지름길 코너: render_to_response() -------------------------------- -render_to_response() ø εϰ, ؽƮ ä, :class:`~django.http.HttpResponse` ü ø Բ ȯϱ οϴ Դϴ. Django մϴ. ü ``index()`` 並 ۼ߽ϴ. +render_to_response()는 템플릿을 로드하고, 컨텍스트를 채우고, :class:`~django.http.HttpResponse` 객체를 렌더된 템플릿의 결과와 함께 반환하기 위해 자주 싸용하는 구문입니다. Django는 지름길을 제공 합니다. 전체 ``index()`` 뷰를 재작성했습니다. from django.shortcuts import render_to_response from polls.models import Poll @@ -214,15 +214,15 @@ render_to_response() latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list}) -츮 信 ؼ ѹ ϸ, ̻ :mod:`~django.template.loader`, :class:`~django.template.Context` and -:class:`~django.http.HttpResponse` ҷ ʿ䰡 ٴ ϼ. +우리는 모든 뷰에 대해서 한번만 하면, 더이상 :mod:`~django.template.loader`, :class:`~django.template.Context` and +:class:`~django.http.HttpResponse`를 불러올 필요가 없다는 것을 기억하세요. -:func:`~django.shortcuts.render_to_response` Լ ø ̸ ù ° ڷ, ° ڷ ϴ. Լ ־ ؽƮ Բ ø ü :class:`~django.http.HttpResponse` ȯ մϴ. +:func:`~django.shortcuts.render_to_response` 함수는 템플릿 이름을 첫 번째 인자로, 선택 가능한 두 번째 인자로 사전을 갖습니다. 그 함수는 주어진 컨텍스트와 함께 렌더링된 템플릿 객체의 :class:`~django.http.HttpResponse` 를 반환 합니다. -404 +404 띄우기 =========== -, ǥ 並 ô. -- ־ ǥ ǥմϴ. 䰡 ֽϴ:: +자, 세부 투표 뷰를 봅시다. -- 주어진 투표에 대한 제목을 표시합니다. 여기 뷰가 있습니다:: from django.http import Http404 # ... @@ -233,18 +233,18 @@ render_to_response() raise Http404 return render_to_response('polls/detail.html', {'poll': p}) - ֽϴ. ǥ Բ û ID 䰡 :exc:`~django.http.Http404`ܸ ϴ. +이전에 보지 못한 개념이 있습니다. 투표와 함께 요청받은 ID가 존재 하지 않으면 뷰가 :exc:`~django.http.Http404`예외를 띄웁니다. -츮 ߿ `polls/detail.html`` Դϴ. ׷, ϰ ʹٸ, :: +우리는 조금 나중에 당신이 `polls/detail.html``에 무엇을 넣을지 고민 할 것 입니다. 그러나, 당신이 빠르게 예제를 동작하게 만들고 싶다면, 단지:: {{ poll }} -ڵ尡 ݺ ֵ մϴ. +코드가 지금부터 시작 할 수 있도록 합니다. - ڳ: get_object_or_404() +지름길 코너: get_object_or_404() ------------------------------- -get_object_or404() :meth:`~django.db.models.query.QuerySet.get` ϰ, ü :exc:`~django.http.Http404` ϴ Դϴ. Django մϴ. ``detail()`` 並 ۼ ߽ϴ.:: +get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`를 사용하고, 객체가 없을 때는 :exc:`~django.http.Http404`를 띄우기 위해 자주 사용하는 구문 입니다. Django 는 지름길을 제공 합니다. ``detail()`` 뷰를 재작성 했습니다.:: from django.shortcuts import render_to_response, get_object_or_404 # ... @@ -252,48 +252,48 @@ get_object_or404() p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p}) -:func:`~django.shortcuts.get_object_or_404`Լ DJango ù ° ڷ ް, :meth:`~django.db.models.query.QuerySet.get` Լ ڸ Ű ڷ ޽ϴ. , ü , :exc:`~django.http.Http404` ϴ. +:func:`~django.shortcuts.get_object_or_404`함수는 DJango 모델을 첫 번째 인자로 받고, :meth:`~django.db.models.query.QuerySet.get` 함수를 지나온 임의의 숫자를 키워드 인자로 받습니다. 만약, 객체가 존재하지 않으면, :exc:`~django.http.Http404`를 띄웁니다. -.. :: ö +.. 충고:: 철학 - 츮 :exc:`~django.core.exceptions.ObjectDoesNotExist` ؼ ڵ ܸ óϴ Լ :func:`~django.shortcuts.get_object_or_404` ? + 왜 우리가 더 높은 레벨에서 :exc:`~django.core.exceptions.ObjectDoesNotExist`를 사용해서 자동으로 예외를 처리하는 대신 헬퍼 함수인 :func:`~django.shortcuts.get_object_or_404`를 사용 했을까? instead of automatically catching the :exc:`~django.core.exceptions.ObjectDoesNotExist` exceptions at a higher - Ǵ :exc:`~django.core.exceptions.ObjectDoesNotExist` ϴ :exc:`~django.http.Http404` API ? + 또는 :exc:`~django.core.exceptions.ObjectDoesNotExist`를 사용하는 대신 :exc:`~django.http.Http404`를 띄우는 모델 API를 가질까? :exc:`~django.core.exceptions.ObjectDoesNotExist`? - ϱ ̴. One of the - Django 䰡 ǥ ϳ ϴ ̴. + 그 이유는 모델 계층을 뷰 계층에 결합하기 때문이다. One of the + Django의 으뜸가는 디자인 목표중 하나는 느슨한 결합을 유지하는 것이다. - :func:`~django.shortcuts.get_object_or_404` Ȱ ϴ :func:`~django.shortcuts.get_list_or_404` Լ ִ. -- :meth:`~django.db.models.query.QuerySet.get` :meth:`~django.db.models.query.QuerySet.filter` ϴ Ѵ. :func:`~django.shortcuts.get_list_or_404` Ʈ 쿡 :exc:`~django.http.Http404` . +물론 :func:`~django.shortcuts.get_object_or_404`와 거의 똑같이 동작하는 :func:`~django.shortcuts.get_list_or_404` 함수도 있다. -- :meth:`~django.db.models.query.QuerySet.get` 대신 :meth:`~django.db.models.query.QuerySet.filter`를 사용하는 경우는 제외한다. :func:`~django.shortcuts.get_list_or_404` 는 리스트가 비어 있을 경우에 :exc:`~django.http.Http404`를 띄운다. -404 (page not found) ۼϱ +404 (page not found) 뷰 작성하기 ================================= - 信 :exc:`~django.http.Http404` Ű, Django 404 ٷ Ư 並 ε ̴. Djnago Ʈ URLconf(׸ Ʈ URLconf ``handler404`` ؾ Ѵ. ̿ ġ õȴ.) ``handler404`` string in python dotted syntax ãμ 404 ٷ Ư 並 ã ̴. -- · Ϲ URLconf ݹ Ѵ. 404 üδ ƯѰ ƹ͵ . Ϲ ̴. + 당신이 뷰에서 :exc:`~django.http.Http404`를 일으키면, Django는 404 오류를 다루기로한 특별한 뷰를 로드 할 것 이다. Djnago는 당신의 루트 URLconf(그리고 오직 루트 URLconf에서 ``handler404``를 설정해야 한다. 이외의 위치에서는 모두 무시된다.)에서 ``handler404`` string in python dotted syntax 변수를 찾음으로서 404오류를 다루기로한 특별한 뷰를 찾을 것이다. -- 같은 형태로 일반적인 URLconf 콜백들을 사용 한다. 404 뷰 자체로는 특별한게 아무것도 없다. 일반적인 뷰일 뿐이다. -Ϲ 404 µ Ű澵 ʿ䰡 . ``handler404`` , :func:`django.views.defaults.page_not_found` - ⺻ Ѵ. 쿡 ִ. ``404.html`` ø rootø 丮 ؾ Ѵ. ⺻ 404 ø 404 ̴. :setting:`DEBUG` ``False`` (in your settings module) ϰų, ``404.html`` - , ``Http500`` . ׷Ƿ ``404.html`` ϴ . +일반적으로 당신은 404 뷰들을 만드는데 신경쓸 필요가 없다. 만약 ``handler404``를 설정하지 않으면, 내장된 :func:`django.views.defaults.page_not_found` +를 기본적으로 사용한다. 이 경우에또 여전히 한 가지 할 일이 남아 있다. ``404.html`` 템플릿을 당신의 root템플릿 디렉토리에 생성 해야 한다. 기본적인 404 뷰는 그 템플릿을 모든 404 오류에 사용 할 것이다. 만약 :setting:`DEBUG`를 ``False`` (in your settings module)로 설정 하거나, ``404.html`` +파일을 만들지 않으면, ``Http500``을 대신 띄운다. 그러므로 ``404.html``을 생성하는 것을 기억하자. -404 鿡 ؼ ˾Ƶξ Ұ ִ. +404 뷰들에 대해서 몇 가지더 알아두어야 할것이 있다. -* :setting:`DEBUG` ``True`` ߴٸ( ȿ) 404 ̴.(׸ ``404.html`` ø ʴ´). ֳϸ traceback ǥϱ ̴. +* :setting:`DEBUG`를 ``True``로 설정 했다면(설정 모듈 안에서) 당신의 404 뷰는 절대로 사용하지 않을 것이다.(그리고 ``404.html`` 템플릿은 절대 렌더 되지 않는다). 왜냐하면 traceback을 대신 표시하기 때문이다. 404 view will never be used (and thus the ``404.html`` template will never be rendered) because the traceback will be displayed instead. -* 404 Django URLconf ǥ ˻ϰ, ġϴ ǥ ã ȣѴ. +* 404뷰는 Django가 URLconf 내의 모든 정규표현식을 검색하고도, 일치하는 표현을 찾지 못했을 때도 호출한다. every regular expression in the URLconf. -500 (server error) ۼϱ +500 (server error) 뷰 작성하기 =============================== -ϰ, Ʈ URLconf Ƹ 쿡 ȣϱ 並 Ű ``handler500`` ϰ ִ. ڵ忡 Ÿ ߻Ѵ. +비슷하게, 당신의 루트 URLconf는 아마도 서버 오류인 경우에 호출하기 위한 뷰를 가리키는 ``handler500``을 정의 하고 있다. 서버 오류는 뷰 코드에서 런타임 에러가 있을때 발생한다. -ø ý ϱ +템플릿 시스템 사용하기 ======================= -츮 ǥ ø̼ ``detail()`` ư . ``poll`` ؽƮ ־, "polls/detail.html" ø  Ǵ : +우리 투표 어플리케이션의 ``detail()`` 뷰로 돌아가 보자. ``poll``이 컨텍스트 변수로 주어졌을때, "polls/detail.html" 템플릿이 어떻게 되는지 보도록 하자: .. code-block:: html+django @@ -304,17 +304,17 @@ get_object_or404() {% endfor %} -ø ý Ӽ鿡 ϱ ؼ dot-lookup Ѵ. ``{{ poll.question }}`` , Django ó ``poll`` ü ã´. ã⿡ ϸ, ƮƮ ȸ Ѵ. -- which works, in this case. , ƮƮ ȸ ϸ, list-index ȸ õ Ѵ. +템플릿 시스템은 변수 속성들에 접근 하기 위해서 dot-lookup 구문을 사용 한다. ``{{ poll.question }}``의 예제에서 보면, Django는 처음에 ``poll`` 객체에서 사전을 찾는다. 찾기에 실패하면, 어트리뷰트를 조회 한다. -- which works, in this case. 만약, 어트리뷰트 조회에 실패하면, list-index 조회를 시도 한다. -:ttag:`{% for %}` ޼ҵ ȣ ߻Ѵ: -``poll.choice_set.all`` ̽ ڵ ``poll.choice_set.all()`` ȯ Ѵ. ̽ ڵ ``poll.choice_set.all()`` ü an iterable ȯϰ, :ttag:`{% for %}` ±׿ ϱ ˸´. +:ttag:`{% for %}` 루프에서 메소드 호출이 발생한다: +``poll.choice_set.all`` 은 파이썬 코드 ``poll.choice_set.all()``로 변환 한다. 파이썬 코드 ``poll.choice_set.all()``는 선택한 객체들의 an iterable을 반환하고, :ttag:`{% for %}` 태그에서 사용하기 알맞다. -ø ڼ :doc:`template guide ` . +템플릿에 대한 자세한 내용은 :doc:`template guide ` 를 보세요. -URLconfs ܼȭ ϱ +URLconfs를 단순화 하기 ======================== - ø ýۻ̸ Ⱦ ϱ⿡ ð ɸϴ. URLconf ó, ȿ ʿ ߺ ִٴ ˾ Դϴ. +뷰와 템플릿 시스템사이를 종횡무진 하기에는 시간이 좀 걸립니다. 당신이 URLconf를 수정 한 것 처럼, 당신은 그 안에 상당한 불필요한 중복이 있다는 것을 알아차렸을 것입니다. urlpatterns = patterns('', url(r'^polls/$', 'polls.views.index'), @@ -323,9 +323,9 @@ URLconfs url(r'^polls/(?P\d+)/vote/$', 'polls.views.vote'), ) -ٽø ``polls.views`` ݹ鿡 ġ մϴ. +다시말해 ``polls.views`` 는 모든 콜백에 위치 합니다. -ֳϸ common case, URLconf ӿũ prefixs鿡 մϴ. prefixes ̾ ֽϴ. ׸, ̾Ƴ prefixes :func:`~django.conf.urls.patterns` Ʒ ù ° ڷ ߰ ֽϴ. :: +왜냐하면 common case에, URLconf 프레임워크는 공통적인 prefixs들에 대한 지름길을 제공 합니다. 당신은 공통적인 prefixes들을 뽑아 낼수 있습니다. 그리고, 뽑아낸 prefixes들을 :func:`~django.conf.urls.patterns`에 아래와 같이 첫 번째 인자로 추가 할 수 있습니다. :: urlpatterns = patterns('polls.views', url(r'^polls/$', 'index'), @@ -334,10 +334,10 @@ URLconfs url(r'^polls/(?P\d+)/vote/$', 'vote'), ) - ð ġ մϴ. մϴ. +이 방법은 이전의 포매팅과 기능적으로 일치 합니다. 더 깔끔합니다. -Ϲ URLconf ݹ鿡 ϳ ø̼ prefix ϰ ʴٸ, :func:`~django.conf.urls.patterns` ֽϴ. -. ``mysite/urls.py`` ü Ʒ ϴ. :: +일반적으로 URLconf의 모든 콜백에 하나의 애플리케이션을 위한 prefix를 적용하고 싶지 않다면, 여러개의 :func:`~django.conf.urls.patterns`를 연결 할 수 있습니다. +. ``mysite/urls.py`` 전체는 아래와 같습니다. :: from django.conf.urls import patterns, include, url @@ -355,16 +355,16 @@ URLconfs url(r'^admin/', include(admin.site.urls)), ) -URLconf յ ߱ +URLconf의 결합도 낮추기 ======================= -while we're at it, 츮 Django Ʈ 츮 ǥ- URL иϴ ð մϴ. Django ۵ pluggable ϵ Ǿ ֽϴ. -- Ư ּ ٸ Django installation ؾ մϴ. +while we're at it, 우리는 Django 프로젝트 설정으로 부터 우리의 투표-앱 URL 들을 분리하는 시간을 가져야 합니다. Django 앱들은 pluggable 하도록 되어 있습니다. -- 각각의 특정한 앱이 최소한의 수정으로 다른 Django installation 으로 이전 가능해야 합니다. -츮 ǥ иǾ ֽϴ. ``python manage.py startapp`` 丮 Ͻʽÿ. ׷, URLconf ϳ Django յǾ ֽϴ. +우리의 투표 앱은 이 시점에서 상당히 분리되어 있습니다. ``python manage.py startapp``가 생성한 엄격한 디렉토리 구조에 감사하십시오. 그렇지만, URLconf 하나만 Django 설정들과 결합되어 있습니다. - 츮 ``mysite/urls.py`` ִ URL ߽ϴ. ׷, URL Django installation ƴ϶, Ư Դϴ. -- ׷ URL 丮 ̵ մϴ. + 우리는 ``mysite/urls.py``에 있는 URL들은 수정했습니다. 그러나, 앱의 URL 디자인은 Django installation이 아니라, 특정 앱 지향적입니다. -- 그래서 URL들을 앱 디렉토리 안으로 이동 합니다. -``mysite/urls.py`` ``polls/urls.py`` Ͻʽÿ. ׸, ``mysite/urls.py`` ǥ- URL ϰ, :func:`~django.conf.urls.include` ڸ ߰ ϵ մϴ:: +``mysite/urls.py`` 파일을 ``polls/urls.py``로 복사 하십시오. 그리고, ``mysite/urls.py``을 투표-한정 URL들을 제고 하고, :func:`~django.conf.urls.include`를 그 자리에 추가 하도록 변경 합니다:: from django.conf.urls import patterns, include, url @@ -376,19 +376,19 @@ while we're at it, url(r'^admin/', include(admin.site.urls)), ) -:func:`~django.conf.urls.include` ϰ ٸ URLconf մϴ. -ǥ ``$``(ڿ ġϴ ) ʰ, trailling slash ϼ. Django :func:`~django.conf.urls.include` Լ , it chops off whatever part of the -URL matched up to that point ׸ ߰ ó ؼ URLconf ڿ մϴ. +:func:`~django.conf.urls.include`은 간단하게 다른 URLconf를 참조 합니다. +정규표현식은 ``$``(문자열의 끝과 일치하는 문자)를 가지지 않고, trailling slash를 가지는 점을 기억하세요. 어디든지 Django가 :func:`~django.conf.urls.include` 함수를 만나면, it chops off whatever part of the +URL matched up to that point 그리고 추가 처리를 위해서 포함한 URLconf로 남은 문자열을 전송 합니다. -ڰ ýۿ "/polls/34/" ̵ϴ 쿡 ߻ϴ ô: +사용자가 이 시스템에서 "/polls/34/"으로 이동하는 경우에 발생하는 일을 봅시다: -* Django ``'^polls/'`` ġϴ ãԴϴ. +* Django는 ``'^polls/'``에서 일치하는 것을 찾을것입니다. -* ׸, Django ġϴ (``"polls/"``) Դϴ. ׸ - -- ``"34/"`` -- 'polls.urls' URLconf ߰ ó ؼ ϴ. +* 그리고나서, Django 는 일치하는 문자(``"polls/"``)를 벗겨 낼것 입니다. 그리고 + 남은 문자 -- ``"34/"`` --를 'polls.urls' URLconf로 추가 처리를 위해서 보냅니다. further processing. -, URLconf Django յ ߾ϴ. 츮 տ ִ "polls/" ϰ, Ʈ ε ν ``polls.urls`` URLconf յ ߾ϴ. ``polls/urls.py`` Ʒ ƾ մϴ. :: +이제, URLconf와 Django 설정의 결합도를 낮추었습니다. 우리는 개별 라인 맨 앞에 있는 "polls/"를 삭제하고, 관리자 사이트에 등록한 라인들을 삭제 함으로써 ``polls.urls``와 URLconf의 결합도를 낮추었습니다. ``polls/urls.py`` 파일은 지금 아래와 같아야 합니다. :: from django.conf.urls import patterns, include, url @@ -399,9 +399,9 @@ URL matched up to that point url(r'^(?P\d+)/vote/$', 'vote'), ) -:func:`~django.conf.urls.include` URLconf յ ߴ ̵ URL plug-and-play ݴϴ. , ǥ URLconf ֽϴ. ǥ "/polls/" ؿ ְ, "/fun_polls/" ؿ, "/content/polls/" ؿ, ׸ ٸ  root ֽϴ. ׸ Դϴ. +:func:`~django.conf.urls.include`와 URLconf의 결합도를 낮추는 아이디어는 URL들의 plug-and-play를 쉽게 만들어 줍니다. 이제, 투표들은 각자 URLconf를 가지고 있습니다. 투표들은 "/polls/" 밑에도 있을 수 있고, "/fun_polls/" 밑에도, "/content/polls/" 밑에도, 그리고 다른 어떠한 root 경로 에도 있을 수 있습니다. 그리고 앱은 여전히 잘 동작 할 것 입니다. - ǥ ۵ ΰ ƴ϶, θ մϴ. +모든 투표 앱들은 절대 경로가 아니라, 상대 경로를 사용 합니다. - 並 ۼ ϴ Ϳ ͼ ܼ ó ʸ 並 ؼ :doc:`part 4 of this tutorial -` оʽÿ. + 뷰를 작성 하는 것에 익숙해 지면 단순한 폼 처리와 제너릭 뷰를 배우기 위해서 :doc:`part 4 of this tutorial +`를 읽어보십시오. \ No newline at end of file From 115cbbab42cdb222f3eb8256b0ffe77787ee4822 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A0=95=EC=84=B1=ED=83=9C?= Date: Wed, 15 Aug 2012 15:07:42 +0900 Subject: [PATCH 023/128] fix, update / intro/tutorial04 .. --- intro/tutorial04.txt | 75 +++++++++++++++++++------------------------- 1 file changed, 32 insertions(+), 43 deletions(-) diff --git a/intro/tutorial04.txt b/intro/tutorial04.txt index 60b6aad..188c405 100644 --- a/intro/tutorial04.txt +++ b/intro/tutorial04.txt @@ -44,9 +44,9 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 (Cross Site Request Forgeries)에 대해 고민해야한다.고맙게도, 장고는 사이트 간 요청 위조(CSRF)에 대해 보호하기위한 사용하기 쉬운 시스템을 가지고 있기 때문에, 너무 심각하게 고민할 필요가 없다. 간단히 말하면, 내부 URL들을 향하는 모든 POST 폼은 - 템플릿 태그 :ttag:`{% csrf_token %}`/ 을 사용해야한다. + 템플릿 태그 :ttag:`{% csrf_token %}`\ 을 사용해야한다. -:ttag:`{% csrf_token %}`\ 태그는 템플릿 문접에서 평범하게 접근이 불가능한 요청(request) 개체로부터의 정보를 필요로 한다. 이부분을 적용하기 위해, 다음과 같은 작은 조정이 ``detail`` 뷰에 필요하다 :: +:ttag:`{% csrf_token %}` 태그는 템플릿 문법에서 평범하게 접근이 불가능한 요청(request) 개체로부터의 정보를 필요로 한다. 이부분을 적용하기 위해, 다음과 같은 작은 조정이 ``detail`` 뷰에 필요하다 :: from django.template import RequestContext # ... @@ -57,7 +57,7 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 이것이 작동하는 것에 대한 자세한 내용은 :ref:`RequestContext ` 부분의 문서를 참고하라. -이제 전송된 자료를 다룰 장고 뷰를 만들고, 그것을 가지고 무엇인가를 해보자. :doc:`자습서 3 `\ 에서 아 라인을 포함하는 설물조사 어플리케이션을 위해 URLconf를 만들것을 기억하라:: +이제 전송된 자료를 다룰 장고 뷰를 만들고, 그것을 가지고 무엇인가를 해보자. :doc:`자습서 3 `\ 에서 설문조사 어플리케이션을 위해 아래에 나와있는 코드를 포함하는 URLconf를 만들었었다. :: (r'^(?P\d+)/vote/$', 'vote'), @@ -89,17 +89,13 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 위 코드는 이 자습서에서 아직 다루지 않은 몇 가지를 포함하고 있다: -* :attr:`request.POST ` is a dictionary-like - object that lets you access submitted data by key name. In this case, - ``request.POST['choice']`` returns the ID of the selected choice, as a - string. :attr:`request.POST ` values are - always strings. +* :attr:`request.POST ` 는 키로 전송된 자료에 + 접근할 수 있도록 해주는 사전과 같은 객체이다. 이 경우에서 ``request.POST['choice']``\ 는 + 선택된 설문지의 ID를 문자열로 반환한다. :attr:`request.POST `\ 의 값은 항상 문자열들이다. - Note that Django also provides :attr:`request.GET - ` for accessing GET data in the same way -- - but we're explicitly using :attr:`request.POST - ` in our code, to ensure that data is only - altered via a POST call. + Django는 같은 방법으로 GET 자료에 접근하기 위해 :attr:`request.GET `\ 를 + 제공한다. 그러나 POST 요청으로만 자료가 수정되게하기 위해서, 우리는 + 명시적으로 코드에 :attr:`request.POST `\ 를 사용하고 있다. * 만약 POST 자료에 ``choice``\ 가 없으면, ``request.POST['choice']``\ 는 :exc:`KeyError`\ 를 일으킨다. 위의 코드는 :exc:`KeyError`\ 를 체크하고, ``choice``\ 가 주어지지 않은 경우에는 @@ -111,27 +107,23 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 사용자가 재전송할 URL. (이 경우에 우리가 URL을 어떻게 구성하는지 다음 항목을 보라). - 위 소스안의 파이썬 주석내용대로, POST 자료를 성공적으로 처리한 후에는 항상 - :class:`~django.http.HttpResponseRedirect` after successfully dealing with - POST data. 이것은 장고에만 특정한 팁이 아니다, - 좋은 웹 개발관례일 뿐이다. + 위 소스안의 주석내용대로, POST 자료를 성공적으로 처리한 후에는 항상 + :class:`~django.http.HttpResponseRedirect`\ 를 반환해야한다. 이것은 + 장고에만 특정한 팁이 아니다. 좋은 웹 개발관례일 뿐이다. * 우리는 이 예제에서 :class:`~django.http.HttpResponseRedirect` 생성자 안의 :func:`~django.core.urlresolvers.reverse` 함수를 사용하고 있다. 이 함수는 함수에서 URL을 하드코딩하는 행위를 안하게 도와준다. - 제어를 전달하기 원하는 view의 이름을 제공하고, URL패턴의 변수부분이 그 뷰를 가리킨다. - 이 경우에, URLconf를 사용하여 우리는 자습서 3에서 설정하였다. In this - case, using the URLconf we set up in Tutorial 3, this + 제어를 전달하기 원하는 뷰의 이름을 제공하고, URL패턴의 변수부분이 그 뷰를 가리킨다. + 이 경우에, URLconf를 사용하여 우리는 자습서 3에서 설정하였다. 아래와 같은 문자열을 반환할 것이다. :: '/polls/3/results/' - ... ``3``\ 은 ``p.id``\ 의 값이다. 이 리다이렉트된 URL은 - 마지막 페이지를 보여주기위해 ``'results'`` 뷰를 호출한다. 뷰 이름(풀네임)을 - 사용해야한다는 것을 주의하라(접두사를 포함하여). + ... ``3``\ 은 ``p.id``\ 의 값이다. 이 리다이렉트된 URL은 마지막 페이지를 보여주기위해 ``'results'`` 뷰를 호출한다. 뷰 이름(풀네임)을 사용해야한다는 것을 주의하라(접두사를 포함하여) . -자습서 3에서 언급했듯이, ``request``\ 은 :class:`~django.http.HttpRequest`\ 개체이다. :class:`~django.http.HttpRequest` 개체에 대해 더 알고 싶다면 :doc:`request and response documentation `\ 을 보라. +자습서 3에서 언급했듯이, ``request``\ 는 :class:`~django.http.HttpRequest`\ 개체이다. :class:`~django.http.HttpRequest` 개체에 대해 더 알고 싶다면 :doc:`request and response documentation `\ 을 참고하라. 어떤 이가 설문조사에 설문을 하고난 뒤에는, ``vote()`` 뷰는 설문조사 결과 페이지로 리다이렉트한다. 그 뷰를 작성해보자 :: @@ -139,7 +131,7 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/results.html', {'poll': p}) -이것은 :doc:`Tutorial 3`\ 의 ``detail()`` view와 거의 동일하다. 다른점은 템플릿 이름밖에 없다. 우리는 후에 이 쓸데없는 것들을 수정할 것이다. +이것은 :doc:`Tutorial 3`\ 의 ``detail()`` 뷰와 거의 동일하다. 다른점은 템플릿 이름밖에 없다. 우리는 후에 이 쓸데없는 것들을 수정할 것이다.(역자주:쓸데없는 것이라고 한 이유는 위 파일이 필요없어지기 때문입니다.) 이제, ``results.html`` 템플릿을 만들자: @@ -155,19 +147,19 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 Vote again? -이제, 웹브라주여에서 ``/polls/1/`` 페이지로 가자, 그리고 설문조사를 해보자. 당신이 설문조사를 할 때마다 값이 반영된 결과페이지를 볼것이다. 만약 당신이 설문지를 선택하지 않고 폼을 전송했다면, 에러메시지를 보게될 것이다. +이제, 웹 브라우저에서 ``/polls/1/`` 페이지로 가자, 그리고 설문조사를 해보자. 당신이 설문조사를 할 때마다 값이 반영된 결과페이지를 볼것이다. 만약 당신이 설문지를 선택하지 않고 폼을 전송했다면, 에러메시지를 보게될 것이다. 제네릭 뷰 사용하기 : 적은 코드가 더 좋음 ====================================== -``detail()`` ( :doc:`자습 3 `\ 에서의) 과 ``results()`` -뷰는 매우 비슷하다. -- 그리고, 위에서 언급한 것 처럼 장황하다. 설문 목록들을 보여주는 ``index()`` 뷰(이것도 자습서 3에서), 는 비슷하다. +``detail()`` ( :doc:`자습서 3 `\ 에서의) 과 ``results()`` +뷰는 매우 비슷하다. -- 그리고, 위에서 언급한 것 처럼 장황하다. 설문 목록들을 보여주는 ``index()`` 뷰(이것도 자습서 3에서)도 마찬가지이다. -이 뷰들은 기본적인 웹 개발의 일반적인 케이스들:(URL로 전달된 매개변수로부터 데이터베이스에서 자료를 얻고, 템플릿을 불러오며, 처리된 템플릿을 반환하는)을 제공한다. 매우 일반적인 것들이기 때문에, 장고는 "제네릭 뷰" 시스템이라 불리는 지름길을 제공한다. +이 뷰들은 기본적인 웹 개발의 일반적인 케이스들:(URL로 전달된 매개변수로부터 데이터베이스에서 자료를 얻고, 템플릿을 불러오며, 처리된 템플릿을 반환하는)을 제공한다. 이것들이 매우 일반적인 것들이기 때문에, 장고는 "제네릭 뷰" 시스템이라 불리는 지름길을 제공한다. 앱을 쓰기위해 파이썬 코드를 쓸 필요가 없을 정도로 제네릭 뷰는 일반적인(역자주-중복되고, 장황한) 패턴들을 제거한다. -제네릭 뷰 시스템을 사용해서 우리의 설문자 앱을 바꿔보자. 그리고 우리의 코드를 삭제할 수도 있다. 변환하기에는 몇 단계를 거쳐야 한다. 우리는: +제네릭 뷰 시스템을 사용해서 우리의 설문조사 앱을 바꿔보자. 그리고 우리의 코드를 삭제할 수도 있다. 변환하기에는 몇 단계를 거쳐야 한다. 우리는: 1. URLconf를 변환한다. @@ -181,13 +173,13 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 일반적으로, 장고 앱을 작성할 때, 당신은 제네릭 뷰가 당신의 문제에 잘 맞는지 평가할 것이고, 절반정도 작성된 당신의 코드를 - 리펙토링 하기보다는 처음부터 제네릭 뷰를 사용할 것이다. 그러나 이 자습서는 + 다시 작성하기보다는 처음부터 제네릭 뷰를 사용할 것이다. 그러나 이 자습서는 지금까지 핵심개념들을 배우기위해 의도적으로 "힘든 방법으로", 뷰 작성하기에 초점을 맞춰왔다. 계산기를 사용하기전에 기본적인 산수를 알아야하지 않겠는가. -먼저, ``polls/urls.py``\ 의 URLconf를 보라. 지금까지의 자습서 내용대로라면 아래와 같은 내용이 보일것이다. +먼저, ``polls/urls.py``\ 의 URLconf를 보자. 지금까지의 자습서 내용대로라면 아래와 같은 내용이 보일것이다. :: from django.conf.urls import patterns, include, url @@ -224,24 +216,21 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 여기에서 제네릭 뷰 두 개를 사용하고 있다: :class:`~django.views.generic.list.ListView` 와 -:class:`~django.views.generic.detail.DetailView`.. 이 두 개의 뷰들은 각각, "개체들의 목록을 보여주기" 와 "개체의 특정한 형식에 맞춘 세부 페이지 보여주기" 란 개념을 가지고 있다. +:class:`~django.views.generic.detail.DetailView`. 이 두 개의 뷰들은 각각, "개체들의 목록을 보여주기" 와 "개체의 특정한 형식에 맞춘 세부 페이지 보여주기" 란 개념을 가지고 있다. * 각 제네릭 뷰는 제네릭 뷰가 어떤 모델에 작용할지 알아야한다 .. 그것은 ``model`` 파라미터를 사용하여 제공된다. -* :class:`~django.views.generic.list.DetailView` 제네릭 뷰는 - ``"pk"``라 불리는 URL에서 가져온 기본 키 값을 받을 준비를 하고 있다 - , 그래서 우리는 ``poll_id``\ 를 ``pk``\ 로 변경했다 - . +* :class:`~django.views.generic.list.DetailView` 제네릭 뷰는 + URL에서 가져온 기본 키 값(``"pk"``\ 라 불리는)을 받을 준비를 + 하고 있다. 그래서 우리는 ``poll_id``\ 를 ``pk``\ 로 변경했다. * 우리는 results 뷰에 ``poll_results``\ 란 이름을 추가했다, 그렇게 하면 URL 이후에 오는 변수를 참조할 수 있게 된다.( 이것에 관한 정보는 :ref:`naming URL patterns - ` 문서를 보라). We're also using the - :func:`~django.conf.urls.url` function from - :mod:`django.conf.urls` here. It's a good habit to use - :func:`~django.conf.urls.url` when you are providing a - pattern name like this. + ` 문서를 보라). 또 우리는 여기에서 :mod:`django.conf.urls`\ 의 + :func:`~django.conf.urls.url` 함수를 사용했다. 이와같은 패턴 이름을 제공하는 경우에 + :func:`~django.conf.urls.url`\ 사용은 좋은 습관이다. 기본적으로 :class:`~django.views.generic.list.DetailView` 제네릭 뷰는 ``/_detail.html``\ 이라 불리는 템플릿을 사용한다. 우리는 ``"polls/poll_detail.html"`` 템플릿을 사용할 것이다. 자동생성되는 기본 템플릿 이름 대신에 특정한 템릿 이름을 사용하여 장고에게 전달하기 위해 ``template_name`` 를 사용한다. 또한 우리는 ``results`` 리스트 뷰를 위해 ``template_name``\ 를 지정해야한다 -- 비록 둘 다 같은 :class:`~django.views.generic.list.DetailView`\ 이긴 하지만. 이것은 results 뷰와 detail 뷰가 달리 표현되는 것을 보장한다. @@ -272,4 +261,4 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 * 진보된 관리자 기능: 권한 * 진보된 관리자 기능: 사용자 정의 자바스크립트 -그 동안, :doc:`where to go from here `\ 에서 몇몇 부분들을 살펴볼 수 있다. +그 동안, :doc:`where to go from here `\ 에서 몇몇 부분들을 살펴볼 수 있다. \ No newline at end of file From e05c5feca1d7ec9509a2d13f17a7408ef3d4e491 Mon Sep 17 00:00:00 2001 From: HyunJin Moon Date: Wed, 15 Aug 2012 19:38:48 +0900 Subject: [PATCH 024/128] Update intro/tutorial03.txt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 어투 수정  --- intro/tutorial03.txt | 185 +++++++++++++++++++++---------------------- 1 file changed, 91 insertions(+), 94 deletions(-) diff --git a/intro/tutorial03.txt b/intro/tutorial03.txt index c16e6d2..8081064 100644 --- a/intro/tutorial03.txt +++ b/intro/tutorial03.txt @@ -2,61 +2,61 @@ Writing your first Django app, part 3 ===================================== -이 자습서는 :doc:`Tutorial 2 `의 마지막에 이어서 시작 합니다. 자, 우리는 계속해서 "뷰"라고 하는 퍼블릭 인터페이스를 작성하는데 중점을 두고 웹-투표 어플리케이션을 진행 합니다. +이 자습서는 :doc:`Tutorial 2 `의 마지막에 이어서 시작 합니다. 우리는 계속해서 "뷰"라고 하는 퍼블릭 인터페이스를 작성하는데 중점을 두고 웹-투표 애플리케이션을 계속 합니다. 철학 ========== -뷰는 Django 어플리케이션에서 특정한 기능을 수행하거나, 특정한 템플릿을 가지는 웹 페이지의 "타입" 입니다. 예를 들어 웹블로그 어플리케이션에는 아래와 같은 뷰들을 가질 수 있습니다. +뷰는 Django 애플리케이션에서 특정한 기능을 수행하거나, 특정한 템플릿을 가지는 웹 페이지의 "유형" 입니다. 예를 들어 웹블로그 애플리케이션은 아래와 같은 뷰들을 가질 것 입니다. -* 블로그 홈페이지 -- 최신 엔트리를 몇개 display 합니다. +* 블로그 홈페이지 -- 최신 엔트리 몇 개를 표시 합니다. -* 엔트리 "세부" 페이지 -- 한 개의 엔트리를 위한 퍼머링크 입니다. +* 엔트리 "세부" 페이지 -- 한 개의 엔트리를 위한 퍼머링크 페이지입니다. -* 연도별 아카이브 페이지 -- 주어진 연도에 있는 모든 달을 엔트리와 함께 나타냅니다. - given year. +* 연도별 아카이브 페이지 -- 주어진 연도에 있는 모든 달들을 엔트리와 함께 나타냅니다. + -* 월별 아카이브 페이지 -- 주어진 달에 있는 모든 날을 엔트리와 함께 나타냅니다. - given month. +* 월별 아카이브 페이지 -- 주어진 달에 있는 모든 날들을 엔트리와 함께 나타냅니다. + * 일별 아카이브 페이지 -- 주어진 날에 있는 모든 엔트리를 나타냅니다. * 코멘트 달기 -- 주어진 엔트리에 코멘트를 포스팅 합니다. -우리 투표 어플리케이션에는 아래와 같이 네 개의 뷰가 있습니다. +투표 애플리케이션에는 아래와 같이 네 개의 뷰가 있습니다. -* 투표 "인덱스" 페이지 -- 최근 몇 개의 투표를 나타냅니다. +* 투표 "인덱스" 페이지 -- 몇 개의 최신 투표를 나타냅니다. -* 투표 "세부" 페이지 -- 투표의 질문을 투표 할 수 있는 폼과 함께 나타냅니다. 질문은 보여주지 않습니다. - with a form to vote. +* 투표 "세부" 페이지 -- 투표의 질문을 투표 할 수 있는 폼과 함께 나타냅니다. 투표 결과는 보여주지 않습니다. + * 투표 "결과" 페이지 -- 특정 투표의 결과를 나타냅니다. * 투표 하기 -- 특정 투표에서 특정 선택지에 투표합니다. - poll. + -Django 에서 개별 뷰는 간단한 파이썬 함수로 나타낼수 있습니다. +Django 에서 개별 뷰는 간단한 파이썬 함수로 나타냅니다. URL 디자인 하기 ================ -URL 구조를 디자인 하는 것은 뷰를 작성하는 첫 번째 단계입니다. 당신은 URLconf라는 파이썬 모듈을 생성함으로서, URL구조를 디자인 할 수 있습니다. URLconfs는 DJango가 주어진 URL을 주어진 파이썬 코드와 연결하는 방법 입니다. +URL 구조를 디자인 하는 것은 뷰를 작성하는 첫 번째 단계입니다. URLconf라는 파이썬 모듈을 생성함으로써, URL구조를 디자인 할 수 있습니다. URLconfs는 Django가 주어진 URL을 주어진 파이썬 코드와 연결하는 방법 입니다. -사용자가 Django-powerd 페이지를 요청 할 때, 시스템은 Python dotted syntax에 있는 문자열을 포함하는 :setting:'ROOT_URLCONF' 설정을 참고 합니다. Django 는 URLconf 모듈을 로드 합니다. 그리고, 아래와 같은 포맷의 튜플인 모듈-레벨 변수인 ``urlpatterns``를 검색 합니다. +사용자가 Django-powered 페이지를 요청 할 때, 시스템은 Python dotted syntax에 있는 문자열을 포함하는 :setting:'ROOT_URLCONF' 설정을 참고 합니다. Django 는 URLconf 모듈을 로드 합니다. 그리고, 아래와 같은 포맷의 튜플인 모듈-레벨 변수인 ``urlpatterns``를 검색 합니다. (regular expression, Python callback function [, optional dictionary]) -DJango는 첫 번째 정규표현식에서 시작 해서, 일치하는 결과를 찾을 때 까지 요청 받은 URL을 개별 정규표현식과 비교하면서 리스트 아래로 내려갑니다. +Django는 첫 번째 정규표현식을 시작으로, 일치하는 결과를 찾을 때 까지 요청 받은 URL을 각각의 정규표현식과 비교하면서 리스트 아래로 내려갑니다. - 일치하는 결과를 찾으면, Django는 파이썬 콜백 함수를 호출 합니다. 이 때, :class:`~django.http.HttpRequest` 객체를 첫 번째 인자로 하고, 정규표현식에서 찾은 아무 값을 keyword 인자로 합니다. 옵션으로 the dictionary로부터 아무 keyword를 사용 합니다.(튜플의 임의의 세번째 아이템). + 일치하는 결과를 찾으면, Django는 파이썬 콜백 함수를 호출 합니다. 이 때, :class:`~django.http.HttpRequest` 객체를 첫 번째 인자로 하고, 정규표현식에서 찾은 임의의 값을 키워드 인자로 가집니다. 옵션으로 그 사전에서 임의의 키워드(튜플의 세 번째 아이템)를 가져다가 사용 합니다. :class:`~django.http.HttpRequest` 객체에 대해서 자세히 알고 싶다면, :doc:`/ref/request-response` 를 참고 하세요. URLconfs 에 대해서 자세히 알고 싶다면, :doc:`/topics/http/urls`를 참고 하세요. -자습서 1에서 처음 ``django-admin.py startproject mysite`` 를 실행 했을때, 기본 URLconf를 ``mysite/urls.py``에 생성 했습니다. 게다가 자동으로 :setting:`ROOT_URLCONF` 설정을(``settings.py`` 안에 있는) ``mysite/urls.py``를 가리키도록 설정 했습니다.:: +자습서 1에서 처음 ``django-admin.py startproject mysite`` 를 실행 했을때, 기본 URLconf를 ``mysite/urls.py``에 생성 했습니다. 게다가 자동으로 :setting:`ROOT_URLCONF`을 =(``settings.py`` 안에 있는) ``mysite/urls.py``를 가리키도록 설정 했습니다.:: ROOT_URLCONF = 'mysite.urls' -예제를 볼 차례 입니다. ``mysite/urls.py``를 아래와 같이 수정 합니다.:: +예제를 보겠습니다. ``mysite/urls.py``를 아래와 같이 수정 합니다.:: from django.conf.urls import patterns, include, url @@ -71,49 +71,49 @@ DJango는 첫 번째 정규표현식에서 시작 해서, 일치하는 결과를 url(r'^admin/', include(admin.site.urls)), ) -여기까지를 리뷰 하도록 합니다. 누군가가 당신의 웹 사이트에 "/polls/23/"이라는 요청을 하면, Django는 :setting:`ROOT_URLCONF` 설정이 가리키고 있기 때문에 이 파이썬 모듈을 로드 할 것 입니다. 위의 파이썬 모듈은 ``urlpatterns``라는 이름을 가진 변수를 찾습니다. 그리고, 정규표현식들을 순서대로 traverses 합니다. 위의 파이썬 모듈이 일치하는 정규표현식을 찾았을때 -- ``r'^polls/(?P\d+)/$'`` -- 위의 파이썬 모듈은 ``polls/views.py``에 있는 ``detail()`` 함수를 로드 합니다. 마침내, 파이썬 모듈은 아래와 같이 ``detail()`` 함수를 호출 합니다. +여기 까지의 내용을 설명하면. 누군가 웹 사이트에 "/polls/23/"이라는 요청을 하면, Django는 :setting:`ROOT_URLCONF` 설정이 가리키고 있기 때문에 위의 파이썬 모듈을 로드 할 것 입니다. 위의 파이썬 모듈은 ``urlpatterns``라는 이름을 가진 변수를 찾습니다. 그리고, 정규표현식들을 순서대로 순회 합니다. 위의 파이썬 모듈이 일치하는 정규표현식을 찾았을때 -- ``r'^polls/(?P\d+)/$'`` -- 위의 파이썬 모듈은 ``polls/views.py``에 있는 ``detail()`` 함수를 로드 합니다. 끝으로 파이썬 모듈은 아래와 같이 ``detail()`` 함수를 호출 합니다. detail(request=, poll_id='23') -``poll_id='23'``는 ``(?P\d+)``에서 온 것 입니다. 패턴 주위에 괄호()를 사용해서 그 패턴과 일치하는 텍스트를 "captures"하고, 뷰 함수에게 인자로 보냅니다; ``?P``는 일치하는 패턴을 인식하기 위한 이름을 정의 합니다. 그리고 ``\d+``는 숫자가 나와야 할 순서라는 정규표현식입니다.(역자 주: 정규 표현식에서 \d는 0~9 사이의 숫자를 의미하고 +는 앞 문자가 1번 이상 나타나면 된다는 것을 의미 합니다. 따라서, 1개 이상의 숫자가 있으면 된다는 뜻입니다. ) +``poll_id='23'``는 ``(?P\d+)``에서 온 것 입니다. 패턴 주위에 괄호()를 사용해서 그 패턴과 일치하는 텍스트를 "captures"하고, 뷰 함수에게 인자로 보냅니다; ``?P``는 일치하는 패턴을 인식하는데 사용 할 이름을 정의 합니다. 그리고 ``\d+``는 숫자가 나와야 할 순서를 의미하는 정규표현식입니다.(역자 주: 정규 표현식에서 \d는 0~9 사이의 숫자를 의미하고 +는 앞 문자가 1번 이상 나타나면 된다는 것을 의미 합니다. 따라서, 1개 이상의 숫자가 있으면 된다는 뜻입니다. ) - URL 패턴들은 정규표현식이기 때문에, 당신이 정규표현식으로 무엇을 하든 제한이 없습니다. 그리고, 당신이 아래와 같이 하는 악취미가 있지 않는 한은 ``.php``같은 URL 부스러기 들을 붙일 필요가 없습니다 :: + URL 패턴들은 정규표현식이기 때문에, 무엇을 하든 제한이 없습니다. 그리고, 아래와 같은 악취미가 있지 않는 한 ``.php``같은 URL 부스러기 들을 붙일 필요가 없습니다 :: (r'^polls/latest\.php$', 'polls.views.index'), -그렇지만, 하지마세요. 바보 같으니까요. +위 처럼, 하지마세요. 바보 같으니까요. 이런 정규표현식들은 GET, POST 파라미터들 또는 도메인 이름을 검색하지는 않는 다는 것을 기억하십시오. 예를 들어 ``http://www.example.com/myapp/``을 향한 요청에서, URLconf는 ``myapp/``만 찾을 것 입니다. ``http://www.example.com/myapp/?page=3``를 향한 요청에서, URLconf는 ``myapp/``만 찾을 것 입니다. -만약, 정규표현식에 대해 도움이 필요하면, `Wikipedia's entry`_ 그리고 :mod:`re` 모듈의 문서를 참고 하십시오. 또, Jeffrey Friedl 의 오라일리의 책 "Mastering Regular Expressions" 도 끝내줍니다. +만약, 정규표현식에 대해 도움이 필요하면, `Wikipedia's entry`_ 그리고 :mod:`re` 모듈의 문서를 참고 하십시오. 또, Jeffrey Friedl 의 오라일리의 책 "Mastering Regular Expressions" 도 죽여줍니다. -Finally, a performance note : 처음 URLconf 모듈이 로드 되어 있을때, 이 정규표현식들은 컴파일 됩니다. URLconf는 엄청나게 빠릅니다. +Finally, a performance note : 처음 URLconf 모듈이 로드 되었을때, 이 정규표현식들은 컴파일 되었습니다. 그래서, 매우 빠릅니다. .. _Wikipedia's entry: http://en.wikipedia.org/wiki/Regular_expression 첫 번째 뷰 작성 하기 ===================== -우리는 단지 URLconf 만 만들 었습니다. 아직 아무런 뷰도 생성 하지 않았습니다. 그렇지만, Django가 아래의 URLconf를 철저히 따르고 있는지 확인 하십시오. +우리는 URLconf 만 만들었습니다. 아직 아무 뷰도 생성 하지 않았습니다. 그렇지만 이전에 Django가 아래의 URLconf를 철저히 따르고 있는지 확실히 하십시오. -Django 개발 웹 서버를 출동 시킵니다. +이제 Django 개발 웹 서버를 구동합니다. .. code-block:: bash python manage.py runserver 웹브라우져에서 "http://localhost:8000/polls/" 로 이동 하십시오. -당신은 유쾌하게 컬러링된 아래와 같은 메세지의 에러 페이지를 보게 될 것 입니다.:: +당신은 유쾌하게 컬러링된 아래 메세지의 에러 페이지를 보게 될 것 입니다.:: ViewDoesNotExist at /polls/ Could not import polls.views.index. View does not exist in module polls.views. -이 에러는 ``polls/views.py`` 모듈에 ``index()`` 함수를 작성한 적이 없기 때문에 생겼습니다. +이 오류는 ``polls/views.py`` 모듈에 ``index()`` 함수를 작성한 적이 없기 때문에 발생 합니다. -"/polls/23/", "/polls/23/results/" 그리고 "/polls/23/vote/" 도 시도해 보십시오. 에러 메세지들은 Django가 어떤 뷰에 접근 하려고 했는지 알려줍니다(그리고, 당신이 뷰들을 작성 하지 않았기 때문에 찾기에 실패 합니다). +"/polls/23/", "/polls/23/results/" 그리고 "/polls/23/vote/" 도 시도해 보십시오. 오류 메세지들은 Django가 어떤 뷰에 접근 하려고 했는지 알려줍니다(그리고, 당신이 뷰들을 작성 하지 않았기 때문에 찾기에 실패 합니다). -첫 번 째 뷰를 작성 할 시간 입니다. ``polls/views.py``를 열어서 아래의 파이썬 코드를 입력 합니다.:: +첫 번째 뷰를 작성 합니다. ``polls/views.py``를 열어서 아래의 파이썬 코드를 입력 합니다.:: from django.http import HttpResponse @@ -133,19 +133,19 @@ Django 개발 웹 서버를 출동 시킵니다. def vote(request, poll_id): return HttpResponse("You're voting on poll %s." % poll_id) -브라우저에서 "/polls/34/"를 둘러보세요. `detail()` 메소드를 실행하고, 당신이 URL에 입력한 ID를 나타냅니다. "/polls/34/results/"과 "/polls/34/vote/"도 시도해 보세요. -- 이 URL들은 placeholder results와 투표 페이지 를 보여줍니다. +브라우저에서 "/polls/34/"를 둘러보세요. `detail()` 메소드를 실행하고, URL에 입력한 ID를 나타냅니다. "/polls/34/results/"과 "/polls/34/vote/"도 시도해 보세요. -- 이 URL들은 placeholder results와 투표 페이지 를 보여줍니다. 실제로 동작하는 뷰 작성 하기 ====================================== 각각의 뷰는 둘 중에 하나를 수행합니다. 요청받은 페이지에 대한 컨텐츠를 가지고 있는 :class:`~django.http.HttpResponse` 객체를 반환 하거나 :exc:`~django.http.Http404` 같은 예외를 발생합니다. 나머지는 당신에게 달렸습니다. -당신의 뷰를 데이터베이스에서 records들을 읽을수도, 아닐수도 있습니다. Django에 있는것 같은 템플릿 시스템을 사용 할 수도 있습니다. 또는 서드 파티 파이썬 템플릿 시스템을 사용할수도, 안할수도 있습니다. -PDF 파일을 생성하거나, XML을 출력하거나, ZIP파일을 생성하거나, 당신이 무엇을 원하든 간에 무엇이든 원하는 파이썬 라이브러리들을 사용 하십시오. +당신의 뷰는 데이터베이스에서 레코드들을 읽을수도, 아닐수도 있습니다. Django에 있는 것 같은 템플릿 시스템 --또는 서드 파티 파이썬 템플릿 시스템 -- 을 사용할수도, 안할수도 있습니다. +PDF 파일을 생성하거나, XML을 출력하거나, ZIP파일을 생성하거나, 당신이 무엇을 원하든 간에 원하는 파이썬 라이브러리들을 사용 하십시오. 모든 Django가 필요한 것은 :class:`~django.http.HttpResponse` 입니다. 또는 예외 입니다. -사용하기 쉽기 ?문에, 우리가 :doc:`Tutorial 1 `에서 다루었던 Django만의 데이터베이스 API를 사용해 봅시다. 여기 날짜 순서로 정렬하고, 콤마로 나눈, 시스템에 있는 최근 5개의 투표 질문들을 보여주는``index()`` 뷰를 시도해 봅시다. +사용하기 편리하므로, 우리가 :doc:`Tutorial 1 `에서 다루었던 Django가 가지고 있는 데이터베이스 API를 사용해 봅시다. 날짜 순서로 정렬하고, 콤마로 나눈, 시스템에 있는 최근 5개의 투표 질문들을 보여주는``index()`` 뷰를 만들어봅시다. from polls.models import Poll from django.http import HttpResponse @@ -155,9 +155,9 @@ PDF 파일을 생성하거나, XML을 출력하거나, ZIP파일을 생성하거 output = ', '.join([p.question for p in latest_poll_list]) return HttpResponse(output) -위에 코드에는 문제가 있습니다. 페이지 디자인을 뷰에 하드 코딩 했습니다. 만약, 당신이 페이지가 보이는 형태를 변경 하려고 한다면, 이 파이썬 코드를 수정 하게 될것 입니다. +위의 코드에는 문제가 있습니다. 페이지 디자인을 뷰에 하드 코딩 했습니다. 만약 페이지가 보이는 형태를 변경 하려고 한다면, 파이썬 코드를 수정 하게 될것 입니다. you want to change the way the page looks, you'll have to edit this Python code. -그러므로 디자인을 파이썬으로부터 분리하기 위해서 Django의 템플릿 시스템을 이용 해보도록 합니다. +그래서 디자인을 파이썬으로부터 분리하기 위해서 Django 템플릿 시스템을 이용합니다. from django.template import Context, loader from polls.models import Poll @@ -171,7 +171,7 @@ you want to change the way the page looks, you'll have to edit this Python code. }) return HttpResponse(t.render(c)) -위의 코드는 "polls/index.html" 템플릿을 로드 해서 컨텍스트를 전달 합니다. +위의 코드는 "polls/index.html" 템플릿을 로드하고 컨텍스트를 전달 합니다. 컨텍스트는 파이썬 객체들 이름을 가진 사전 매핑 템플릿 변수 입니다. 페이지를 새로고침 하십시오. 에러를 보게 될것 입니다:: @@ -179,14 +179,14 @@ you want to change the way the page looks, you'll have to edit this Python code. TemplateDoesNotExist at /polls/ polls/index.html -아. 아직 템플릿이 없군요. 첫 번째, 당신의 파일시스템 아무데나 Django가 접근 할 수 있는 곳에 디렉토리를 생성 하십시오. (Django runs as whatever user your -server runs.) 대신, 그 파일들은 당신의 문서 root에 넣지 마세요. 보안상의 이유로, 그 디렉토리를 퍼블릭으로 만들지 않아야 합니다. -그리고, ``settings.py``의 :setting:`TEMPLATE_DIRS`를 수정해서, Django에게 어디서 템플릿들을 찾을 수 있는지 알려 주십시오. -- Turorial 2의 "Customize the admin look and feel" 섹션에서 한것 처럼 하면 됩니다. +아. 아직 템플릿이 없군요. 첫 번째, 당신의 파일시스템 아무곳에나 Django가 접근 할 수 있는 곳에 디렉토리를 생성 하십시오. (Django runs as whatever user your +server runs.) 대신, 그 파일들은 문서 root에 넣지 마세요. 보안 문제가 있으므로, 디렉토리를 퍼블릭으로 만들지 않아야 합니다. +그리고, ``settings.py``의 :setting:`TEMPLATE_DIRS`를 수정해서, Django에게 어디서 템플릿들을 찾을 수 있는지 알려 주십시오. -- 자습서 2의 "Customize the admin look and feel" 섹션에서 한것 처럼 하면 됩니다. -위의 내용을 완료 했다면, ``polls`` 디렉토리를 를 당신의 템플릿 디렉토리에 생성 하세요. -그 안에 ``index.html`` 파일을 생성하세요. 우리의 ``loader.get_template('polls/index.html')`` 코드는 파일 시스템에 있는 "[template_directory]/polls/index.html" 과 매핑 되는 것을 기억하십시오. +위의 내용을 완료 했다면, ``polls`` 디렉토리를 템플릿 디렉토리에 생성 하십시오. +그 안에 ``index.html`` 파일을 생성하십시오. 우리의 ``loader.get_template('polls/index.html')`` 코드는 파일 시스템에 있는 "[template_directory]/polls/index.html" 과 매핑 된다는 것을 기억하십시오. -아래의 코드를 템플릿에 입력하세요. +아래의 코드를 템플릿에 입력하십시오. .. code-block:: html+django @@ -200,12 +200,12 @@ server runs.) 대신, 그 파일들은 당신의 문서 root에 넣지 마세요

No polls are available.

{% endif %} -웹 브라우저에서 페이지를 로드하면, Turorial 1의 "What's up" 투표를 포함하는 bulleted-list를 볼 수 있어야 합니다. 이 링크는 그 투표의 세부 페이지를 가리킵니다. +웹 브라우저에서 페이지를 로드하면, 자습서 1의 "What's up" 투표를 포함하는 bulleted-list를 볼 수 있어야 합니다. 이 링크는 투표의 세부 페이지를 가리킵니다. -지름길 코너: render_to_response() +지름길: render_to_response() -------------------------------- -render_to_response()는 템플릿을 로드하고, 컨텍스트를 채우고, :class:`~django.http.HttpResponse` 객체를 렌더된 템플릿의 결과와 함께 반환하기 위해 자주 싸용하는 구문입니다. Django는 지름길을 제공 합니다. 전체 ``index()`` 뷰를 재작성했습니다. +render_to_response()는 템플릿을 로드하고, 컨텍스트를 채우고, :class:`~django.http.HttpResponse` 객체를 렌더링된 템플릿의 결과와 함께 반환하기 위해 자주 사용하는 구문입니다. Django는 지름길을 제공 합니다. 전체 ``index()`` 뷰를 재작성했습니다. from django.shortcuts import render_to_response from polls.models import Poll @@ -214,15 +214,14 @@ render_to_response()는 템플릿을 로드하고, 컨텍스트를 채우고, :c latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list}) -우리는 모든 뷰에 대해서 한번만 하면, 더이상 :mod:`~django.template.loader`, :class:`~django.template.Context` and -:class:`~django.http.HttpResponse`를 불러올 필요가 없다는 것을 기억하세요. +모든 뷰에서 한 번만 위의 작업을 하면, 더이상 :mod:`~django.template.loader`, :class:`~django.template.Context` 그리고 :class:`~django.http.HttpResponse`를 불러올 필요가 없다는 것을 기억하십시오. -:func:`~django.shortcuts.render_to_response` 함수는 템플릿 이름을 첫 번째 인자로, 선택 가능한 두 번째 인자로 사전을 갖습니다. 그 함수는 주어진 컨텍스트와 함께 렌더링된 템플릿 객체의 :class:`~django.http.HttpResponse` 를 반환 합니다. +:func:`~django.shortcuts.render_to_response` 함수는 템플릿 이름을 첫 번째 인자로, 선택 가능한 두 번째 인자로 사전을 갖습니다. :func:`~django.shortcuts.render_to_response` 함수는 주어진 컨텍스트와 함께 렌더링된 템플릿 객체의 :class:`~django.http.HttpResponse` 를 반환 합니다. 404 띄우기 =========== -자, 세부 투표 뷰를 봅시다. -- 주어진 투표에 대한 제목을 표시합니다. 여기 뷰가 있습니다:: +세부 투표 뷰를 봅시다. -- 세부 투표 뷰는 주어진 투표에 대한 제목을 표시합니다. 아래에 뷰가 있습니다:: from django.http import Http404 # ... @@ -233,18 +232,18 @@ render_to_response()는 템플릿을 로드하고, 컨텍스트를 채우고, :c raise Http404 return render_to_response('polls/detail.html', {'poll': p}) -이전에 보지 못한 개념이 있습니다. 투표와 함께 요청받은 ID가 존재 하지 않으면 뷰가 :exc:`~django.http.Http404`예외를 띄웁니다. +위의 코드에는 이전에 보지 못한 개념이 있습니다. 투표와 함께 요청받은 ID가 존재 하지 않으면 뷰가 :exc:`~django.http.Http404`예외를 띄웁니다. -우리는 조금 나중에 당신이 `polls/detail.html``에 무엇을 넣을지 고민 할 것 입니다. 그러나, 당신이 빠르게 예제를 동작하게 만들고 싶다면, 단지:: +`polls/detail.html``에 무엇을 넣을지는 조금 나중에 고민 할 것 입니다. 그렇지만, 빠르게 예제를 동작하게 만들고 싶다면, 단지:: {{ poll }} -코드가 지금부터 시작 할 수 있도록 합니다. +코드가 지금 당장 코드를 시작 할 수 있게 할 것 입니다. -지름길 코너: get_object_or_404() +지름길: get_object_or_404() ------------------------------- -get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`를 사용하고, 객체가 없을 때는 :exc:`~django.http.Http404`를 띄우기 위해 자주 사용하는 구문 입니다. Django 는 지름길을 제공 합니다. ``detail()`` 뷰를 재작성 했습니다.:: +get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`를 사용기위해서 자주 사용하는 구문입니다. 객체가 없을 때는 :exc:`~django.http.Http404`를 띄웁니다. Django 는 지름길을 제공 합니다. ``detail()`` 뷰를 재작성 했습니다.:: from django.shortcuts import render_to_response, get_object_or_404 # ... @@ -252,48 +251,47 @@ get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`를 사용하 p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p}) -:func:`~django.shortcuts.get_object_or_404`함수는 DJango 모델을 첫 번째 인자로 받고, :meth:`~django.db.models.query.QuerySet.get` 함수를 지나온 임의의 숫자를 키워드 인자로 받습니다. 만약, 객체가 존재하지 않으면, :exc:`~django.http.Http404`를 띄웁니다. +:func:`~django.shortcuts.get_object_or_404`함수는 Django 모델을 첫 번째 인자로 받고, :meth:`~django.db.models.query.QuerySet.get` 함수에서 전달된 임의의 숫자를 키워드 인자로 받습니다. 만약, 객체가 존재하지 않으면, :exc:`~django.http.Http404`를 띄웁니다. .. 충고:: 철학 - 왜 우리가 더 높은 레벨에서 :exc:`~django.core.exceptions.ObjectDoesNotExist`를 사용해서 자동으로 예외를 처리하는 대신 헬퍼 함수인 :func:`~django.shortcuts.get_object_or_404`를 사용 했을까? - instead of automatically catching the - :exc:`~django.core.exceptions.ObjectDoesNotExist` exceptions at a higher - 또는 :exc:`~django.core.exceptions.ObjectDoesNotExist`를 사용하는 대신 :exc:`~django.http.Http404`를 띄우는 모델 API를 가질까? + 왜 우리가 더 높은 레벨에서 :exc:`~django.core.exceptions.ObjectDoesNotExist`를 사용해서 자동으로 예외를 처리하는 대신 헬퍼 함수인 :func:`~django.shortcuts.get_object_or_404`를 사용 했을까요? + + + 또는 :exc:`~django.core.exceptions.ObjectDoesNotExist`를 사용하는 대신 :exc:`~django.http.Http404`를 띄우는 모델 API를 가지도록 했을까요? :exc:`~django.core.exceptions.ObjectDoesNotExist`? - 그 이유는 모델 계층을 뷰 계층에 결합하기 때문이다. One of the - Django의 으뜸가는 디자인 목표중 하나는 느슨한 결합을 유지하는 것이다. + 그 이유는 모델 계층을 뷰 계층에 결합 하기 때문입니다. + Django의 으뜸가는 디자인 목표중 하나는 느슨한 결합을 유지하는 것입니다. -물론 :func:`~django.shortcuts.get_object_or_404`와 거의 똑같이 동작하는 :func:`~django.shortcuts.get_list_or_404` 함수도 있다. -- :meth:`~django.db.models.query.QuerySet.get` 대신 :meth:`~django.db.models.query.QuerySet.filter`를 사용하는 경우는 제외한다. :func:`~django.shortcuts.get_list_or_404` 는 리스트가 비어 있을 경우에 :exc:`~django.http.Http404`를 띄운다. + 물론 :func:`~django.shortcuts.get_object_or_404`와 거의 똑같이 동작하는 :func:`~django.shortcuts.get_list_or_404` 함수도 있습니다. -- :meth:`~django.db.models.query.QuerySet.get` 대신 :meth:`~django.db.models.query.QuerySet.filter`를 사용하는 경우는 제외합니다. :func:`~django.shortcuts.get_list_or_404` 는 리스트가 비어 있을 경우에 :exc:`~django.http.Http404`를 띄웁니다. 404 (page not found) 뷰 작성하기 ================================= - 당신이 뷰에서 :exc:`~django.http.Http404`를 일으키면, Django는 404 오류를 다루기로한 특별한 뷰를 로드 할 것 이다. Djnago는 당신의 루트 URLconf(그리고 오직 루트 URLconf에서 ``handler404``를 설정해야 한다. 이외의 위치에서는 모두 무시된다.)에서 ``handler404`` string in python dotted syntax 변수를 찾음으로서 404오류를 다루기로한 특별한 뷰를 찾을 것이다. -- 같은 형태로 일반적인 URLconf 콜백들을 사용 한다. 404 뷰 자체로는 특별한게 아무것도 없다. 일반적인 뷰일 뿐이다. + 뷰에서 :exc:`~django.http.Http404`를 일으키면, Django는 404 오류를 다루기로한 특별한 뷰를 로드 할 것 입니다. Djnago는 루트 URLconf(그리고 오직 루트 URLconf에서 ``handler404``를 설정해야 합니다. 이외의 위치에서는 모두 무시합니다.)에서 ``handler404`` string in python dotted syntax 변수를 찾음으로써 404오류를 다루기로한 특별한 뷰를 찾을 것입니다. -- 같은 형태로 일반적인 URLconf 콜백들을 사용 합니다. 404 뷰 자체로는 특별한게 아무것도 없습니다. 일반적인 뷰일 뿐입니다. -일반적으로 당신은 404 뷰들을 만드는데 신경쓸 필요가 없다. 만약 ``handler404``를 설정하지 않으면, 내장된 :func:`django.views.defaults.page_not_found` -를 기본적으로 사용한다. 이 경우에또 여전히 한 가지 할 일이 남아 있다. ``404.html`` 템플릿을 당신의 root템플릿 디렉토리에 생성 해야 한다. 기본적인 404 뷰는 그 템플릿을 모든 404 오류에 사용 할 것이다. 만약 :setting:`DEBUG`를 ``False`` (in your settings module)로 설정 하거나, ``404.html`` -파일을 만들지 않으면, ``Http500``을 대신 띄운다. 그러므로 ``404.html``을 생성하는 것을 기억하자. +일반적으로는 404 뷰들을 만드는데 신경쓸 필요가 없습니다. 만약 ``handler404``를 설정하지 않으면, 내장된 :func:`django.views.defaults.page_not_found`를 기본적으로 사용합니다. 이 경우에도 여전히 한 가지 할 일이 남아 있기는 합니다. ``404.html`` 템플릿을 root템플릿 디렉토리에 생성 해야 합니다. 기본적인 404 뷰는 그 템플릿을 모든 404 오류에 사용 할 것입니다. 만약 :setting:`DEBUG`를 ``False`` (in your settings module)로 설정 하거나, ``404.html`` +파일을 만들지 않으면, ``Http500``을 대신 띄웁니다. 그런 이유로 ``404.html``을 생성하는 것을 기억하십시오. -404 뷰들에 대해서 몇 가지더 알아두어야 할것이 있다. +404 뷰들에 대해서 몇 가지더 알아두어야 할 것이 있습니다. -* :setting:`DEBUG`를 ``True``로 설정 했다면(설정 모듈 안에서) 당신의 404 뷰는 절대로 사용하지 않을 것이다.(그리고 ``404.html`` 템플릿은 절대 렌더 되지 않는다). 왜냐하면 traceback을 대신 표시하기 때문이다. - 404 view will never be used (and thus the ``404.html`` template will never - be rendered) because the traceback will be displayed instead. +* :setting:`DEBUG`를 ``True``로 설정 했다면(설정 모듈 안에서) 404 뷰는 절대로 사용하지 않을 것입니다. (그리고 ``404.html`` 템플릿은 절대 렌더 되지 않습니다). 왜냐하면 traceback을 대신 표시하기 때문입니다. + + -* 404뷰는 Django가 URLconf 내의 모든 정규표현식을 검색하고도, 일치하는 표현을 찾지 못했을 때도 호출한다. - every regular expression in the URLconf. +* 404 뷰는 Django가 URLconf 내의 모든 정규표현식을 검색하고도, 일치하는 표현을 찾지 못했을 때도 호출합니다. + 500 (server error) 뷰 작성하기 =============================== -비슷하게, 당신의 루트 URLconf는 아마도 서버 오류인 경우에 호출하기 위한 뷰를 가리키는 ``handler500``을 정의 하고 있다. 서버 오류는 뷰 코드에서 런타임 에러가 있을때 발생한다. +비슷하게, 루트 URLconf는 서버 오류인 경우에 호출하기 위한 뷰를 가리키는 ``handler500``을 정의 하고 있을 것 입니다. 서버 오류는 뷰 코드에서 런타임 에러가 있을때 발생합니다. 템플릿 시스템 사용하기 ======================= -우리 투표 어플리케이션의 ``detail()`` 뷰로 돌아가 보자. ``poll``이 컨텍스트 변수로 주어졌을때, "polls/detail.html" 템플릿이 어떻게 되는지 보도록 하자: +투표 어플리케이션의 ``detail()`` 뷰로 돌아가 보도록 합니다. ``poll``이 컨텍스트 변수로 주어졌을때, "polls/detail.html" 템플릿이 어떻게 되는지 보도록 합니다.: .. code-block:: html+django @@ -304,17 +302,17 @@ get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`를 사용하 {% endfor %} -템플릿 시스템은 변수 속성들에 접근 하기 위해서 dot-lookup 구문을 사용 한다. ``{{ poll.question }}``의 예제에서 보면, Django는 처음에 ``poll`` 객체에서 사전을 찾는다. 찾기에 실패하면, 어트리뷰트를 조회 한다. -- which works, in this case. 만약, 어트리뷰트 조회에 실패하면, list-index 조회를 시도 한다. + 템플릿 시스템은 변수 어트리뷰트들에 접근 하기 위해서 dot-lookup 구문을 사용 합니다. ``{{ poll.question }}``의 예제에서 보면, Django는 처음에 ``poll`` 객체에서 사전을 찾습니다. 찾기에 실패하면, 어트리뷰트를 조회 합니다. -- 이 경우에는 잘 동작 합니다. 만약, 어트리뷰트 조회에 실패하면, list-index 조회를 시도 합니다. -:ttag:`{% for %}` 루프에서 메소드 호출이 발생한다: -``poll.choice_set.all`` 은 파이썬 코드 ``poll.choice_set.all()``로 변환 한다. 파이썬 코드 ``poll.choice_set.all()``는 선택한 객체들의 an iterable을 반환하고, :ttag:`{% for %}` 태그에서 사용하기 알맞다. +:ttag:`{% for %}` 루프에서 메소드 호출이 발생합니다: +``poll.choice_set.all`` 은 파이썬 코드 ``poll.choice_set.all()``로 변환 합니다. 파이썬 코드 ``poll.choice_set.all()``는 선택한 객체들의 an iterable을 반환하고, :ttag:`{% for %}` 태그에서 사용하기 적당합니다. 템플릿에 대한 자세한 내용은 :doc:`template guide ` 를 보세요. URLconfs를 단순화 하기 ======================== -뷰와 템플릿 시스템사이를 종횡무진 하기에는 시간이 좀 걸립니다. 당신이 URLconf를 수정 한 것 처럼, 당신은 그 안에 상당한 불필요한 중복이 있다는 것을 알아차렸을 것입니다. +뷰와 템플릿 시스템사이를 종횡무진 하기에는 시간이 좀 걸립니다. URLconf를 수정 하는 동안, 내부에 상당한 양의 불필요한 중복이 있다는 것을 알아차렸을 것입니다. urlpatterns = patterns('', url(r'^polls/$', 'polls.views.index'), @@ -323,9 +321,9 @@ URLconfs를 단순화 하기 url(r'^polls/(?P\d+)/vote/$', 'polls.views.vote'), ) -다시말해 ``polls.views`` 는 모든 콜백에 위치 합니다. +다시말해 ``polls.views``가 모든 콜백에 있습니다. -왜냐하면 common case에, URLconf 프레임워크는 공통적인 prefixs들에 대한 지름길을 제공 합니다. 당신은 공통적인 prefixes들을 뽑아 낼수 있습니다. 그리고, 뽑아낸 prefixes들을 :func:`~django.conf.urls.patterns`에 아래와 같이 첫 번째 인자로 추가 할 수 있습니다. :: +왜냐하면 공통적인 경우에, URLconf 프레임워크는 공통적인 prefixs들에 대한 지름길을 제공 합니다. 당신은 공통적인 prefixe들을 뽑아 낼수 있습니다. 그리고, 뽑아낸 prefixes들을 :func:`~django.conf.urls.patterns`에 아래와 같이 첫 번째 인자로 추가 할 수 있습니다. :: urlpatterns = patterns('polls.views', url(r'^polls/$', 'index'), @@ -358,13 +356,13 @@ URLconfs를 단순화 하기 URLconf의 결합도 낮추기 ======================= -while we're at it, 우리는 Django 프로젝트 설정으로 부터 우리의 투표-앱 URL 들을 분리하는 시간을 가져야 합니다. Django 앱들은 pluggable 하도록 되어 있습니다. -- 각각의 특정한 앱이 최소한의 수정으로 다른 Django installation 으로 이전 가능해야 합니다. +while we're at it, 우리는 Django 프로젝트 설정으로 부터 우리의 투표-앱 URL 들을 분리하는 시간을 가져야 합니다. Django 앱들은 플러그인 처럼 사용 할수 있도록 만들었습니다. -- 각각의 특정한 앱이 최소한의 수정으로 다른 Django installation 으로 이전 가능해야 합니다. -우리의 투표 앱은 이 시점에서 상당히 분리되어 있습니다. ``python manage.py startapp``가 생성한 엄격한 디렉토리 구조에 감사하십시오. 그렇지만, URLconf 하나만 Django 설정들과 결합되어 있습니다. +이 시점에서 투표 앱은 상당히 결합도가 낮습니다. ``python manage.py startapp``가 생성한 엄격한 디렉토리 구조에 감사하기 바랍니다. 그렇나, 단 하나 URLconf가 Django 설정들과 결합되어 있습니다. - 우리는 ``mysite/urls.py``에 있는 URL들은 수정했습니다. 그러나, 앱의 URL 디자인은 Django installation이 아니라, 특정 앱 지향적입니다. -- 그래서 URL들을 앱 디렉토리 안으로 이동 합니다. + ``mysite/urls.py``에 있는 URL들은 수정했습니다. 그러나, 앱의 URL 디자인은 Django installation이 아니라, 특정 앱 지향적입니다. -- 그래서 URL들을 앱 디렉토리 안으로 이동 합니다. -``mysite/urls.py`` 파일을 ``polls/urls.py``로 복사 하십시오. 그리고, ``mysite/urls.py``을 투표-한정 URL들을 제고 하고, :func:`~django.conf.urls.include`를 그 자리에 추가 하도록 변경 합니다:: +``mysite/urls.py`` 파일을 ``polls/urls.py``로 복사 하십시오. 그리고, ``mysite/urls.py``에서 투표-한정 URL들을 제거 하고, :func:`~django.conf.urls.include`를 그 자리에 추가 하도록 변경 합니다:: from django.conf.urls import patterns, include, url @@ -377,18 +375,17 @@ while we're at it, 우리는 Django 프로젝트 설정으로 부터 우리의 ) :func:`~django.conf.urls.include`은 간단하게 다른 URLconf를 참조 합니다. -정규표현식은 ``$``(문자열의 끝과 일치하는 문자)를 가지지 않고, trailling slash를 가지는 점을 기억하세요. 어디든지 Django가 :func:`~django.conf.urls.include` 함수를 만나면, it chops off whatever part of the -URL matched up to that point 그리고 추가 처리를 위해서 포함한 URLconf로 남은 문자열을 전송 합니다. +정규표현식은 ``$``(문자열의 끝과 일치하는 문자)를 가지지 않고, trailling slash를 가지는 점을 기억하십시오. 어디든지 Django가 :func:`~django.conf.urls.include` 함수를 만나면, it chops off whatever part of the URL matched up to that point 그리고 추가 처리를 위해서 포함한 URLconf로 남은 문자열을 전송 합니다. -사용자가 이 시스템에서 "/polls/34/"으로 이동하는 경우에 발생하는 일을 봅시다: +사용자가 이 시스템에서 "/polls/34/"으로 이동하는 경우 무슨 일이 생기는지 보십시오: * Django는 ``'^polls/'``에서 일치하는 것을 찾을것입니다. -* 그리고나서, Django 는 일치하는 문자(``"polls/"``)를 벗겨 낼것 입니다. 그리고 +* 그리고나서, Django 는 일치하는 문자(``"polls/"``)를 벗겨 낼것 입니다. 남은 문자 -- ``"34/"`` --를 'polls.urls' URLconf로 추가 처리를 위해서 보냅니다. - further processing. + -이제, URLconf와 Django 설정의 결합도를 낮추었습니다. 우리는 개별 라인 맨 앞에 있는 "polls/"를 삭제하고, 관리자 사이트에 등록한 라인들을 삭제 함으로써 ``polls.urls``와 URLconf의 결합도를 낮추었습니다. ``polls/urls.py`` 파일은 지금 아래와 같아야 합니다. :: + 이제, URLconf와 Django 설정의 결합도를 낮추었습니다. 우리는 개별 라인 맨 앞에 있는 "polls/"를 삭제하고, 관리자 사이트에 등록한 라인들을 삭제 함으로써 ``polls.urls``와 URLconf의 결합도를 낮추었습니다. ``polls/urls.py`` 파일은 지금 아래와 같아야 합니다. :: from django.conf.urls import patterns, include, url @@ -399,7 +396,7 @@ URL matched up to that point 그리고 추가 처리를 위해서 포함한 URLc url(r'^(?P\d+)/vote/$', 'vote'), ) -:func:`~django.conf.urls.include`와 URLconf의 결합도를 낮추는 아이디어는 URL들의 plug-and-play를 쉽게 만들어 줍니다. 이제, 투표들은 각자 URLconf를 가지고 있습니다. 투표들은 "/polls/" 밑에도 있을 수 있고, "/fun_polls/" 밑에도, "/content/polls/" 밑에도, 그리고 다른 어떠한 root 경로 에도 있을 수 있습니다. 그리고 앱은 여전히 잘 동작 할 것 입니다. +:func:`~django.conf.urls.include`와 URLconf의 결합도를 낮추는 아이디어는 URL들의 플러그인플레이를 쉽게 만들어 줍니다. 이제 투표들은 각자 URLconf를 가지고 있습니다. 투표들은 "/polls/" 밑에도 있을 수 있고, "/fun_polls/" 밑에도, "/content/polls/" 밑에도, 그리고 다른 어떠한 루트 경로 에도 있을 수 있습니다. 그리고 앱은 여전히 잘 동작 할 것 입니다. 모든 투표 앱들은 절대 경로가 아니라, 상대 경로를 사용 합니다. From f28cc39a5901aa01c1770cb37c744bf0ef9f404a Mon Sep 17 00:00:00 2001 From: Yong Choi Date: Wed, 15 Aug 2012 19:40:54 +0900 Subject: [PATCH 025/128] Update intro/tutorial04.txt --- intro/tutorial04.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/intro/tutorial04.txt b/intro/tutorial04.txt index 188c405..93ec9ce 100644 --- a/intro/tutorial04.txt +++ b/intro/tutorial04.txt @@ -1,4 +1,4 @@ -===================================== +==================================== 첫번째 장고 앱 만들기! part 4 ==================================== From 7acbe59b227201fdd11b44060ea9dc0c4a5b4b82 Mon Sep 17 00:00:00 2001 From: TheTower <16thetower@gmail.com> Date: Wed, 15 Aug 2012 19:50:10 +0900 Subject: [PATCH 026/128] =?UTF-8?q?install=20=EB=B2=88=EC=97=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- intro/install.txt | 184 ++++++++++++++++++++++------------------------ 1 file changed, 86 insertions(+), 98 deletions(-) diff --git a/intro/install.txt b/intro/install.txt index e29266a..d023b19 100644 --- a/intro/install.txt +++ b/intro/install.txt @@ -1,98 +1,86 @@ -Quick install guide -=================== - -Before you can use Django, you'll need to get it installed. We have a -:doc:`complete installation guide ` that covers all the -possibilities; this guide will guide you to a simple, minimal installation -that'll work while you walk through the introduction. - -Install Python --------------- - -Being a Python Web framework, Django requires Python. It works with any Python -version from 2.5 to 2.7 (due to backwards incompatibilities in Python 3.0, -Django does not currently work with Python 3.0; see :doc:`the Django FAQ -` for more information on supported Python versions and the 3.0 -transition), these versions of Python include a lightweight database called -SQLite_ so you won't need to set up a database just yet. - -.. _sqlite: http://sqlite.org/ - -Get Python at http://www.python.org. If you're running Linux or Mac OS X, you -probably already have it installed. - -.. admonition:: Django on Jython - - If you use Jython_ (a Python implementation for the Java platform), you'll - need to follow a few additional steps. See :doc:`/howto/jython` for details. - -.. _jython: http://www.jython.org/ - -You can verify that Python is installed by typing ``python`` from your shell; -you should see something like:: - - Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) - [GCC 4.0.1 (Apple Inc. build 5465)] on darwin - Type "help", "copyright", "credits" or "license" for more information. - >>> - -Set up a database ------------------ - -If you installed Python 2.5 or later, you can skip this step for now. - -If not, or if you'd like to work with a "large" database engine like PostgreSQL, -MySQL, or Oracle, consult the :ref:`database installation information -`. - -Remove any old versions of Django ---------------------------------- - -If you are upgrading your installation of Django from a previous version, you -will need to :ref:`uninstall the old Django version before installing the new -version `. - -Install Django --------------- - -You've got three easy options to install Django: - -* Install a version of Django :doc:`provided by your operating system - distribution `. This is the quickest option for those - who have operating systems that distribute Django. - -* :ref:`Install an official release `. This - is the best approach for users who want a stable version number and aren't - concerned about running a slightly older version of Django. - -* :ref:`Install the latest development version - `. This is best for users who want the - latest-and-greatest features and aren't afraid of running brand-new code. - -.. admonition:: Always refer to the documentation that corresponds to the - version of Django you're using! - - If you do either of the first two steps, keep an eye out for parts of the - documentation marked **new in development version**. That phrase flags - features that are only available in development versions of Django, and - they likely won't work with an official release. - - -Verifying ---------- - -To verify that Django can be seen by Python, type ``python`` from your shell. -Then at the Python prompt, try to import Django:: - - >>> import django - >>> print django.get_version() - 1.3 - - -That's it! ----------- - -That's it -- you can now :doc:`move onto the tutorial `. - - - + ġ ȳ +=================== + +Django ϱ ؼ ġ ʿմϴ. 츮 :doc:` ġ Ϻ ̵ ` ϰ , ȳ ϰ ּ ġ ʿ մϴ. + +̽ ġϱ +-------------- + +Django ̽ ӿũ, Django ̽ ʿ մϴ. ̽ 2.5 ~ 2.7 մϴ.(̽ 3.0 ȣȯ ʱ⿡, +Django ̽ 3.0 ϴ; ̽ 3.0 ڼ Ȯ ּ. :doc:`Django FAQ +`) ̽ 淮 ̽ SQLite_ ϰ ֱ⿡, ͵̽ ʿ ʽϴ. + +.. _sqlite Ʈ ֽϴ. http://sqlite.org/ + +̽ Ʈ ֽϴ. http://www.python.org. Mac OS X Ѵٸ, ̹ ġǾ ֽϴ. + +.. ::Jython Django + + Jython_ (ڹ ÷ Python) Ѵٸ +  ߰ ġ ʿմϴ. :doc:`/howto/jython` ڼ ֽϴ. + +.. _jython Ʈ Դϴ. http://www.jython.org/ + +̽ Ȯϰ ġ Ǿ ִٸ, 'python' ɾ Է , ǥð Դϴ. + + Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) + [GCC 4.0.1 (Apple Inc. build 5465)] on darwin + Type "help", "copyright", "credits" or "license" for more information. + >>> + + ̽ +----------------- + +̽ 2.5 ̻ ġǾ ִٸ ʾƵ ˴ϴ. + +PostgreSQL,MySQL, Oracle ū ͺ̽ ʿϴٸ, :ref:` ̽ ġ +` ϼ. + + Django +--------------------------------- + + Django ġǾ ִٸ ׷̵尡 ʿմϴ. ּ. :ref:`ο ġ Django ϱ `. + +Django ġϱ +-------------- + +Django ġ ϱ 3 ɼ: + +* Django ġϱ :doc:` ü ϴ ġϱ + `. ̰ + ü ϴ Django ġϱ ɼԴϴ. + +* :ref:` ġϱ`. ̰ + Django ణ Ҿϴٸ + ֽ Django ġϴ ּ ̴. + +* :ref: ֽ ġϱ + `. ̰ ֽŰ ְ ο ڵ ࿡ + ڵ鿡 Դϴ. + +.. :: ̿ϰ ִ Django + شϴ Ȯϼ! + + ù °, ° ܰ ϳ ϸ ** ο ** ǥõ + Ϻκ Դϴ.  ÷ + ̸, + ȣȯ ֽϴ. + + +Ȯ +--------- + +Django Ȯϰ ġ Ǿ ִ, 'python' ɾ Է ϸ ̽㿡 ֽϴ. +̽ ޽ Django Դϴ. Then at the Python prompt, try to import Django:: + + >>> import django + >>> print django.get_version() + 1.3 + + +!---------- + + ϴ. ̵ϼ~ :doc:` ڽ(tutorial) ̵ϱ`. + + + From 5a37036d8b9b7bdbd5d4dc8ad2c4555780222d37 Mon Sep 17 00:00:00 2001 From: HyunJin Moon Date: Wed, 15 Aug 2012 20:19:39 +0900 Subject: [PATCH 027/128] Update intro/tutorial03.txt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 최종 점검본 --- intro/tutorial03.txt | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/intro/tutorial03.txt b/intro/tutorial03.txt index 8081064..0be642c 100644 --- a/intro/tutorial03.txt +++ b/intro/tutorial03.txt @@ -75,7 +75,7 @@ Django는 첫 번째 정규표현식을 시작으로, 일치하는 결과를 찾 detail(request=, poll_id='23') -``poll_id='23'``는 ``(?P\d+)``에서 온 것 입니다. 패턴 주위에 괄호()를 사용해서 그 패턴과 일치하는 텍스트를 "captures"하고, 뷰 함수에게 인자로 보냅니다; ``?P``는 일치하는 패턴을 인식하는데 사용 할 이름을 정의 합니다. 그리고 ``\d+``는 숫자가 나와야 할 순서를 의미하는 정규표현식입니다.(역자 주: 정규 표현식에서 \d는 0~9 사이의 숫자를 의미하고 +는 앞 문자가 1번 이상 나타나면 된다는 것을 의미 합니다. 따라서, 1개 이상의 숫자가 있으면 된다는 뜻입니다. ) +``poll_id='23'``는 ``(?P\d+)``에서 온 것 입니다. 패턴 주위에 괄호()를 사용해서 그 패턴과 일치하는 텍스트를 "포"하고, 뷰 함수에게 인자로 보냅니다; ``?P``는 일치하는 패턴을 인식하는데 사용 할 이름을 정의 합니다. 그리고 ``\d+``는 숫자가 나와야 할 순서를 의미하는 정규표현식입니다.(역자 주: 정규착 표현식에서 \d는 0~9 사이의 숫자를 의미하고 +는 앞 문자가 1번 이상 나타나면 된다는 것을 의미 합니다. 따라서, 1개 이상의 숫자가 있으면 된다는 뜻입니다. URL 패턴들은 정규표현식이기 때문에, 무엇을 하든 제한이 없습니다. 그리고, 아래와 같은 악취미가 있지 않는 한 ``.php``같은 URL 부스러기 들을 붙일 필요가 없습니다 :: @@ -85,7 +85,7 @@ Django는 첫 번째 정규표현식을 시작으로, 일치하는 결과를 찾 이런 정규표현식들은 GET, POST 파라미터들 또는 도메인 이름을 검색하지는 않는 다는 것을 기억하십시오. 예를 들어 ``http://www.example.com/myapp/``을 향한 요청에서, URLconf는 ``myapp/``만 찾을 것 입니다. ``http://www.example.com/myapp/?page=3``를 향한 요청에서, URLconf는 ``myapp/``만 찾을 것 입니다. -만약, 정규표현식에 대해 도움이 필요하면, `Wikipedia's entry`_ 그리고 :mod:`re` 모듈의 문서를 참고 하십시오. 또, Jeffrey Friedl 의 오라일리의 책 "Mastering Regular Expressions" 도 죽여줍니다. +만약, 정규표현식에 대해 도움이 필요하면, `Wikipedia's entry`_ 그리고 :mod:`re` 모듈의 문서를 참고 하십시오. 또, Jeffrey Friedl 의 오라일리의 책 "Mastering Regular Expressions" 도 끝내줍니다. Finally, a performance note : 처음 URLconf 모듈이 로드 되었을때, 이 정규표현식들은 컴파일 되었습니다. 그래서, 매우 빠릅니다. @@ -122,7 +122,7 @@ Finally, a performance note : 처음 URLconf 모듈이 로드 되었을때, 이 실제로 가능한 가장 간단한 뷰 입니다. 브라우저에서 "/polls/" 로 이동하면, 당신이 작성한 텍스트를 볼 수 있어야 합니다. -뷰를 몇 개 더 추가해 봅니다. 이 뷰들은 인자를 가지기 때문에 조금씩 다릅니다. (기억하세요, URLconf에서 정규표현식으로 무엇이 'captured'되었든지 인자로 들어옵니다.) +뷰를 몇 개 더 추가해 봅니다. 이 뷰들은 인자를 가지기 때문에 조금씩 다릅니다. (기억하세요, URLconf에서 정규표현식으로 무엇이 '포착'되었든지 인자로 들어옵니다.) def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id) @@ -155,8 +155,7 @@ PDF 파일을 생성하거나, XML을 출력하거나, ZIP파일을 생성하거 output = ', '.join([p.question for p in latest_poll_list]) return HttpResponse(output) -위의 코드에는 문제가 있습니다. 페이지 디자인을 뷰에 하드 코딩 했습니다. 만약 페이지가 보이는 형태를 변경 하려고 한다면, 파이썬 코드를 수정 하게 될것 입니다. -you want to change the way the page looks, you'll have to edit this Python code. +위의 코드에는 문제가 있습니다. 페이지 디자인을 뷰에 하드 코딩 했습니다. 만약 페이지가 보이는 형태를 변경 하려고 한다면, 파이썬 코드를 수정 해야 합니다. 그래서 디자인을 파이썬으로부터 분리하기 위해서 Django 템플릿 시스템을 이용합니다. from django.template import Context, loader @@ -269,7 +268,7 @@ get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`를 사용기 404 (page not found) 뷰 작성하기 ================================= - 뷰에서 :exc:`~django.http.Http404`를 일으키면, Django는 404 오류를 다루기로한 특별한 뷰를 로드 할 것 입니다. Djnago는 루트 URLconf(그리고 오직 루트 URLconf에서 ``handler404``를 설정해야 합니다. 이외의 위치에서는 모두 무시합니다.)에서 ``handler404`` string in python dotted syntax 변수를 찾음으로써 404오류를 다루기로한 특별한 뷰를 찾을 것입니다. -- 같은 형태로 일반적인 URLconf 콜백들을 사용 합니다. 404 뷰 자체로는 특별한게 아무것도 없습니다. 일반적인 뷰일 뿐입니다. + 뷰에서 :exc:`~django.http.Http404`를 일으키면, Django는 404 오류를 다루기로한 특별한 뷰를 로드 할 것 입니다. Django는 루트 URLconf(그리고 오직 루트 URLconf에서 ``handler404``를 설정해야 합니다. 이외의 위치에서는 모두 무시합니다.)에서 ``handler404`` python dotted syntax 내의 문자열 변수를 찾음으로써 404오류를 다루기로한 특별한 뷰를 찾을 것입니다. -- 같은 형태로 일반적인 URLconf 콜백들을 사용 합니다. 404 뷰 자체로는 특별한게 아무것도 없습니다. 일반적인 뷰일 뿐입니다. 일반적으로는 404 뷰들을 만드는데 신경쓸 필요가 없습니다. 만약 ``handler404``를 설정하지 않으면, 내장된 :func:`django.views.defaults.page_not_found`를 기본적으로 사용합니다. 이 경우에도 여전히 한 가지 할 일이 남아 있기는 합니다. ``404.html`` 템플릿을 root템플릿 디렉토리에 생성 해야 합니다. 기본적인 404 뷰는 그 템플릿을 모든 404 오류에 사용 할 것입니다. 만약 :setting:`DEBUG`를 ``False`` (in your settings module)로 설정 하거나, ``404.html`` 파일을 만들지 않으면, ``Http500``을 대신 띄웁니다. 그런 이유로 ``404.html``을 생성하는 것을 기억하십시오. @@ -356,7 +355,7 @@ URLconfs를 단순화 하기 URLconf의 결합도 낮추기 ======================= -while we're at it, 우리는 Django 프로젝트 설정으로 부터 우리의 투표-앱 URL 들을 분리하는 시간을 가져야 합니다. Django 앱들은 플러그인 처럼 사용 할수 있도록 만들었습니다. -- 각각의 특정한 앱이 최소한의 수정으로 다른 Django installation 으로 이전 가능해야 합니다. +하는 김에 우리는 Django 프로젝트 설정으로 부터 우리의 투표-앱 URL 들을 분리하는 시간을 가져야 합니다. Django 앱들은 플러그인 처럼 사용 할수 있도록 만들었습니다. -- 각각의 특정한 앱이 최소한의 수정으로 다른 Django installation 으로 이전 가능해야 합니다. 이 시점에서 투표 앱은 상당히 결합도가 낮습니다. ``python manage.py startapp``가 생성한 엄격한 디렉토리 구조에 감사하기 바랍니다. 그렇나, 단 하나 URLconf가 Django 설정들과 결합되어 있습니다. @@ -375,7 +374,7 @@ while we're at it, 우리는 Django 프로젝트 설정으로 부터 우리의 ) :func:`~django.conf.urls.include`은 간단하게 다른 URLconf를 참조 합니다. -정규표현식은 ``$``(문자열의 끝과 일치하는 문자)를 가지지 않고, trailling slash를 가지는 점을 기억하십시오. 어디든지 Django가 :func:`~django.conf.urls.include` 함수를 만나면, it chops off whatever part of the URL matched up to that point 그리고 추가 처리를 위해서 포함한 URLconf로 남은 문자열을 전송 합니다. +정규표현식은 ``$``(문자열의 끝과 일치하는 문자)를 가지지 않고, trailling slash를 가지는 점을 기억하십시오. 어디든지 Django가 :func:`~django.conf.urls.include` 함수를 만나면, 해당 시점에서 URL의 일치하는 부분을 잘라냅니다. 그리고, 남은 문자열을 추가 처리를 위해서 불러들인 URLconf로 전송 합니다. 사용자가 이 시스템에서 "/polls/34/"으로 이동하는 경우 무슨 일이 생기는지 보십시오: @@ -401,4 +400,4 @@ while we're at it, 우리는 Django 프로젝트 설정으로 부터 우리의 모든 투표 앱들은 절대 경로가 아니라, 상대 경로를 사용 합니다. 뷰를 작성 하는 것에 익숙해 지면 단순한 폼 처리와 제너릭 뷰를 배우기 위해서 :doc:`part 4 of this tutorial -`를 읽어보십시오. \ No newline at end of file +`를 읽어보십시오. From a37c364df0daedaa86333f92d3cde5c8905b7dea Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Sat, 18 Aug 2012 07:45:19 +0900 Subject: [PATCH 028/128] =?UTF-8?q?intro/index=20=EB=B2=88=EC=97=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- intro/index.txt | 65 ++++++++++++++++++++++--------------------------- 1 file changed, 29 insertions(+), 36 deletions(-) diff --git a/intro/index.txt b/intro/index.txt index 19290a5..7414af6 100644 --- a/intro/index.txt +++ b/intro/index.txt @@ -1,36 +1,29 @@ -Getting started -=============== - -New to Django? Or to Web development in general? Well, you came to the right -place: read this material to quickly get up and running. - -.. toctree:: - :maxdepth: 1 - - overview - install - tutorial01 - tutorial02 - tutorial03 - tutorial04 - whatsnext - -.. seealso:: - - If you're new to Python_, you might want to start by getting an idea of what - the language is like. Django is 100% Python, so if you've got minimal - comfort with Python you'll probably get a lot more out of Django. - - If you're new to programming entirely, you might want to start with this - `list of Python resources for non-programmers`_ - - If you already know a few other languages and want to get up to speed with - Python quickly, we recommend `Dive Into Python`_ (also available in a - `dead-tree version`_). If that's not quite your style, there are quite - a few other `books about Python`_. - - .. _python: http://python.org/ - .. _list of Python resources for non-programmers: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers - .. _dive into python: http://diveintopython.net/ - .. _dead-tree version: http://www.amazon.com/exec/obidos/ASIN/1590593561/ref=nosim/jacobian20 - .. _books about Python: http://wiki.python.org/moin/PythonBooks \ No newline at end of file +시작하기 +=============== + +Django, 혹은 일반적인 웹 개발이 처음이신가요? 그렇다면 바로 찾아오셨습니다. 다음의 문서를 훑어보고 바로 시작해보세요. + +.. toctree:: + :maxdepth: 1 + + overview + install + tutorial01 + tutorial02 + tutorial03 + tutorial04 + whatsnext + +.. seealso:: + + 파이썬_\ 이 처음이시라면, 그에 대해 살펴보시는 것이 좋습니다. 장고는 100% 파이썬으로 만들어졌기 때문에, 파이썬에 대해 약간 알고 있으면 Django를 이해하는 데에 도움이 됩니다. + + 프로그래밍에 대한 경험이 전혀 없으시다면, `프로그래머가 아닌 사람들을 위한 파이썬 자료`_\ 를 참고하시기 바랍니다. + + 이미 다른 언어를 몇가지 알고 있고 있는 상태에서 파이썬을 배우고자 한다면 `파이썬으로 뛰어들기`_(`종이 책`_\ 으로도 나와있습니다)를 추천합니다. 그외에 `파이썬에 관한 책들`_\ 도 있습니다. + + .. _파이썬: http://python.org/ + .. _프로그래머가 아닌 사람들을 위한 파이썬 자료: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers + .. _파이썬으로 뛰어들기: http://diveintopython.net/ + .. _종이 책: http://www.amazon.com/exec/obidos/ASIN/1590593561/ref=nosim/jacobian20 + .. _파이썬에 관한 책들: http://wiki.python.org/moin/PythonBooks \ No newline at end of file From 4cd4497452da11103ed11b84583f227172adb0f9 Mon Sep 17 00:00:00 2001 From: Yong Choi Date: Sat, 18 Aug 2012 07:58:03 +0900 Subject: [PATCH 029/128] Update intro/tutorial02.txt --- intro/tutorial02.txt | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/intro/tutorial02.txt b/intro/tutorial02.txt index bd0d2bd..a51378f 100644 --- a/intro/tutorial02.txt +++ b/intro/tutorial02.txt @@ -11,7 +11,7 @@ 위해서 Django 는 모델을 위한 관리자 인터페이스 생성을 완전히 자동화 하였습니다. Django 는 뉴스를 준비하는 환경을 위해 만들어졌으며, - "컨텐츠 발행인"과 "공개" 사이트를 완벽히 분리하였습니. 사이트 관리자들은 + "컨텐츠 발행인"과 "공개" 사이트를 완벽히 분리하였습니다. 사이트 관리자들은 새로운 스토리나 이벤트, 스포츠 점수 결과 등을 추가하기 위해 시스템을 이용하며, 이런 컨텐츠들은 공개 사이트에 노출됩니다. Django 는 사이트 관리자들이 컨텐츠를 수정할 수 있는 통합 인터페이스를 제공함으로서 문제를 해결합니다. @@ -48,7 +48,7 @@ # url(r'^$', '{{ project_name }}.views.home', name='home'), # url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), - # 관리자 싸이트 문서를 활성화 시키기 위해 admin/doc 의 주석을 제거 해 주세요.: + # 관리자 사이트 문서를 활성화 시키기 위해 admin/doc 의 주석을 제거 해 주세요.: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # 관리자 사이트를 활성화 시키기 위해 다음 줄의 주석을 제거 해 주세요.: @@ -100,7 +100,7 @@ Groups, users, sites 등 몇 개의 수정 가능한 컨텐츠를 확인할 수 관리자 사이트에서 수정 가능한 설문조사 앱 만들기 ========================================= -그러데 우리의 설문조사 앱은 어디에 있나요?아직 관리자 사이트 첫 페이지에 보이지 않습니다. +그러데 우리의 설문조사 앱은 어디에 있나요? 아직 관리자 사이트 첫 페이지에 보이지 않습니다. 단 한가지 할 일: 우선 관리자 사이트에게 ``Poll`` 개체가 관리자 인터페이스가 필요하다고 알려줘야 합니다. 이를 위해 ``polls`` 디렉토리 안에 ``admin.py`` 파일을 생성하고 아래와 같이 수정합니다:: @@ -115,13 +115,13 @@ Groups, users, sites 등 몇 개의 수정 가능한 컨텐츠를 확인할 수 무료 관리 기능 탐험하기 ==================================== -자, 이제 ``Poll`` 이 등록되었고, Django 는 ``Poll`` 을 관리 사이트 첫 페이지에 보여줘야 함을 알고 있습니다: +자, 이제 ``Poll`` 이 등록되었고, Django 는 ``Poll`` 을 관리 사이트 첫 페이지에 보여줘야 함을 알고 있습니다. .. image:: _images/admin03t.png :alt: polls가 보여지는 Django 관리자 사이트 첫 페이지 이제 "Polls."를 클릭하면 polls의 "change list" 를 볼 수 있습니다. 이 페이지에서는 데이터베이스의 모든 poll이 보여지게 되며 이중 한개를 선택하여 변경할 수 있습니다. -여기에 우리가 첫 번째 자습서에서 생성한 "What's up?" poll을 확인할 수 있습니다: +여기에 우리가 첫 번째 자습서에서 생성한 "What's up?" poll을 확인할 수 있습니다. .. image:: _images/admin04t.png :alt: Poll 변경 리스트 페이지 @@ -144,7 +144,7 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: 기능이 제공됩니다. 날짜는 "Today" 바로입력과 달력 팝업이 제공되며, 시간에는 "Now" 바로입력과 일반적으로 시간 입력에 사용되는 간편한 팝업이 제공됩니다. -페이지 하단에는 몇가지 옵션이 제공됩니다: +페이지 하단에는 몇가지 옵션이 제공됩니다. * Save -- 변경사항을 저장하고 현재 개체 타입의 변경된 목록 페이지를 보여줍니다. @@ -181,12 +181,12 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: 여러분은 위와 같은 패턴 -- Model admin 개체 생성, ``admin.site.register()`` 의 두번째 인자로 전달 -- 을 통해 언제든 개체의 관리 사이트 옵션을 변경할 수 있습니다. -이번 예제는 "Publication date" 필드가 "Question" 필드의 앞에 오도록 수정하였습니다.: +이번 예제는 "Publication date" 필드가 "Question" 필드의 앞에 오도록 수정하였습니다. .. image:: _images/admin07.png :alt: 재 정렬된 필드들 -단지 두 개의 필드에서는 크게 인상적이지 않을 지 모르지만 수십개의 필드가 있는 폼 에서는 직관적인 순서를 선택하는 것이 보다 세세한 사용성 측면에서 중요합니다. +단지 두 개의 필드에서는 크게 인상적이지 않을 지 모르지만 수십개의 필드가 있는 폼에서는 직관적인 순서를 선택하는 것이 보다 세세한 사용성 측면에서 중요합니다. 또한 수십개의 필드를 포함한 폼을 다룰 때에는 이들을 폼의 필드셋(fieldsets)으로 분리할 수도 있습니다.:: @@ -199,13 +199,13 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: admin.site.register(Poll, PollAdmin) 필드셋의 튜플(tuple)에 있는 각각의 첫 번째 요소는 필드셋의 제목을 의미합니다. -아래에서 우리가 만든 폼이 어떻게 보이는지 확인할 수 있습니다.: +아래에서 우리가 만든 폼이 어떻게 보이는지 확인할 수 있습니다. .. image:: _images/admin08t.png :alt: 필드셋을 보여주는 폼 각각의 필드셋에는 여러분이 원하는 HTML 클래스를 할당할 수 있습니다. Django 는 특정 필드셋이 처음에 접혀 있는 모습으로 보여질 수 있도록``"collapse"`` 클래스를 제공합니다. -이는 잘 사용하지 않지만 많은 필드를 가지고 있는 길이가 긴 폼이 있을 때 유용 할 것입니다.:: +이는 잘 사용하지 않지만 많은 필드를 가지고 있는 길이가 긴 폼이 있을 때 유용 할 것입니다.: class PollAdmin(admin.ModelAdmin): fieldsets = [ @@ -241,7 +241,7 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: 그러나 시스템에 Choice 개체를 추가하는 작업은 비효율적인 작업입니다 . 만약 여러분이 Poll 개체를 만들 때 여러개의 Choice를 추가할 수 있다면 더 좋을 것 입니다. 자, 그럼 어떻게 하는지 알아봅시다. -Choice 모델을 호출하는 ``register()`` 를 제거하세요. 그런 다음 ``Poll`` 을 불러오기 위해 등록 코드를 수정하세요.:: +Choice 모델을 호출하는 ``register()`` 를 제거하세요. 그런 다음 ``Poll`` 을 불러오기 위해 등록 코드를 수정하세요.: class ChoiceInline(admin.StackedInline): model = Choice @@ -258,7 +258,7 @@ Choice 모델을 호출하는 ``register()`` 를 제거하세요. 그런 다음 이런 작업은 Django에게 "Choice 개체들이 Poll 관리자 페이지에서 수정됨" 을 알려줍니다. 기본적으로 3개의 충분한 Choice 필드를 제공합니다." -"Add poll" 페이지를 열어 어떻게 보이는지 확인 해 봅시다. 그 전에 개발 서버를 재 시작 해 주세요.: +"Add poll" 페이지를 열어 어떻게 보이는지 확인 해 봅시다. 그 전에 개발 서버를 재시작 해 주세요. .. image:: _images/admin11t.png :alt: Choice 가 포함된 Poll 페이지 @@ -270,7 +270,7 @@ Choice 모델을 호출하는 ``register()`` 를 제거하세요. 그런 다음 class ChoiceInline(admin.TabularInline): #... -``StackedInline`` 대신에 ``TabularInline`` 을 사용하면 연관된 개체는 보다 간소화 된 표 기반 형식으로 표현됩니다.: +``StackedInline`` 대신에 ``TabularInline`` 을 사용하면 연관된 개체는 보다 간소화된 표 기반 형식으로 표현됩니다. .. image:: _images/admin12.png :alt: 보다 간소화된 Choice를 포함한 Poll 추가 페이지 @@ -370,16 +370,16 @@ Django의 기본 관리자 사이트 템플릿은 재정의(Override) 될 수 파일을 기본 디렉토리에서 여러분의 커스텀 디렉토리에 복사 한 후 수정하세요. 여기서 날카로운 여러분은 의문이 생길겁니다.: 만약 기본적으로 :setting:`TEMPLATE_DIRS` 가 비어있다면, -Django 는 어떻게 기본 관리자 사이트 템플릿을 찾나요?정답은, Django는 기본적으로 각 앱 패키지의 하위디렉토리에 있는 ``templates/`` 의 템플릿을 자동으로 대체하여 사용합니다. 보다 자세한 정보를 위해 :ref:`template loader documentation ` 을 참조하세요. +Django 는 어떻게 기본 관리자 사이트 템플릿을 찾나요? 정답은, Django는 기본적으로 각 앱 패키지의 하위디렉토리에 있는 ``templates/`` 의 템플릿을 자동으로 대체하여 사용합니다. 보다 자세한 정보를 위해 :ref:`template loader documentation ` 을 참조하세요. 관리자 사이트 첫 페이지 커스터마이즈 하기 ============================== -여러분은 이제 Django 관리 사이트의 첫 페이지 룩앤필도 커스터마이즈 하고 싶을 것 입니다. +여러분은 이제 Django 관리 사이트의 첫 페이지 룩앤필도 커스터마이즈 하고 싶을 것입니다. 기본적으로 첫 페이지는 :setting:`INSTALLED_APPS` 에 등록된 모든 앱을 알파벳 순서로 보여줍니다. 여러분은 아마 레이아웃을 여러분이 원하는데로 변경하고 싶을 것 입니다. 초기 페이지는 관리자 사이트에서 가장 중요한 페이지 이며 쉽게 사용할 수 있어야 합니다. 초기 페이지의 커스터마이즈 템플릿은 ``admin/index.html`` 파일 입니다. (이 전 섹션에서 ``admin/base_site.html`` 에서 한 작업들을 그대로 해 주세요. -- 파일을 기본 디렉토리에서 여러분의 커스텀 디렉토리에 복사 한 후 수정하세요.) 파일을 수정 할 때 ``app_list`` 변수를 확인할 수 있을 것 입니다. 변수는 여러분이 설치한 모든 Django 앱이 포함되어 있을 것 입니다. 이 링크를 그대로 사용해도 되지만, 어려분이 생각하는 데로 관리자 페이지의 개체에 링크를 직접 연결할 수도 있습니다. 다시 한번 얘기 드리지만, 템플릿 언어를 모른다고 걱정하지 마세요. -- 세 번째 자습서에서 보다 자세히 알아볼 것 입니다. -이제 관리자 사이트에 익숙 해 졌다면, :doc:`세 번째 자습서 -` 를 통해 공개된 poll 뷰에 대해 알아봅시다. +이제 관리자 사이트에 익숙해졌다면, :doc:`세 번째 자습서 +`\ 를 통해 공개된 poll 뷰에 대해 알아봅시다. From 2e83b8b189dfc7e4d299bfcce5ca47b34e7dc553 Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Sat, 18 Aug 2012 08:01:31 +0900 Subject: [PATCH 030/128] =?UTF-8?q?intro/index=20=EA=B5=90=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- intro/index.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/intro/index.txt b/intro/index.txt index 7414af6..fe1a237 100644 --- a/intro/index.txt +++ b/intro/index.txt @@ -20,7 +20,7 @@ Django, 혹은 일반적인 웹 개발이 처음이신가요? 그렇다면 바 프로그래밍에 대한 경험이 전혀 없으시다면, `프로그래머가 아닌 사람들을 위한 파이썬 자료`_\ 를 참고하시기 바랍니다. - 이미 다른 언어를 몇가지 알고 있고 있는 상태에서 파이썬을 배우고자 한다면 `파이썬으로 뛰어들기`_(`종이 책`_\ 으로도 나와있습니다)를 추천합니다. 그외에 `파이썬에 관한 책들`_\ 도 있습니다. + 이미 다른 언어를 몇가지 알고 있고 있는 상태에서 파이썬을 배우고자 한다면 `파이썬으로 뛰어들기`_\ 를 추천합니다(`종이 책`_\ 으로도 나와있습니다). 그외에 `파이썬에 관한 책들`_\ 도 있습니다. .. _파이썬: http://python.org/ .. _프로그래머가 아닌 사람들을 위한 파이썬 자료: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers From 81118e2cabe0c875e07d7f4a1acf5703f496825c Mon Sep 17 00:00:00 2001 From: Yong Choi Date: Sat, 18 Aug 2012 08:17:30 +0900 Subject: [PATCH 031/128] Update intro/tutorial02.txt --- intro/tutorial02.txt | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/intro/tutorial02.txt b/intro/tutorial02.txt index a51378f..f5f9802 100644 --- a/intro/tutorial02.txt +++ b/intro/tutorial02.txt @@ -103,7 +103,9 @@ Groups, users, sites 등 몇 개의 수정 가능한 컨텐츠를 확인할 수 그러데 우리의 설문조사 앱은 어디에 있나요? 아직 관리자 사이트 첫 페이지에 보이지 않습니다. 단 한가지 할 일: 우선 관리자 사이트에게 ``Poll`` -개체가 관리자 인터페이스가 필요하다고 알려줘야 합니다. 이를 위해 ``polls`` 디렉토리 안에 ``admin.py`` 파일을 생성하고 아래와 같이 수정합니다:: +개체가 관리자 인터페이스가 필요하다고 알려줘야 합니다. 이를 위해 ``polls`` 디렉토리 안에 ``admin.py`` 파일을 생성하고 아래와 같이 수정합니다. + +:: from polls.models import Poll from django.contrib import admin @@ -188,7 +190,9 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: 단지 두 개의 필드에서는 크게 인상적이지 않을 지 모르지만 수십개의 필드가 있는 폼에서는 직관적인 순서를 선택하는 것이 보다 세세한 사용성 측면에서 중요합니다. -또한 수십개의 필드를 포함한 폼을 다룰 때에는 이들을 폼의 필드셋(fieldsets)으로 분리할 수도 있습니다.:: +또한 수십개의 필드를 포함한 폼을 다룰 때에는 이들을 폼의 필드셋(fieldsets)으로 분리할 수도 있습니다. + +:: class PollAdmin(admin.ModelAdmin): fieldsets = [ @@ -205,13 +209,15 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: :alt: 필드셋을 보여주는 폼 각각의 필드셋에는 여러분이 원하는 HTML 클래스를 할당할 수 있습니다. Django 는 특정 필드셋이 처음에 접혀 있는 모습으로 보여질 수 있도록``"collapse"`` 클래스를 제공합니다. -이는 잘 사용하지 않지만 많은 필드를 가지고 있는 길이가 긴 폼이 있을 때 유용 할 것입니다.: +이는 잘 사용하지 않지만 많은 필드를 가지고 있는 길이가 긴 폼이 있을 때 유용할 것입니다. - class PollAdmin(admin.ModelAdmin): - fieldsets = [ - (None, {'fields': ['question']}), - ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), - ] +:: + + class PollAdmin(admin.ModelAdmin): + fieldsets = [ + (None, {'fields': ['question']}), + ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), + ] .. image:: _images/admin09.png :alt: 처음에 접혀있는 필드셋 @@ -241,7 +247,9 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: 그러나 시스템에 Choice 개체를 추가하는 작업은 비효율적인 작업입니다 . 만약 여러분이 Poll 개체를 만들 때 여러개의 Choice를 추가할 수 있다면 더 좋을 것 입니다. 자, 그럼 어떻게 하는지 알아봅시다. -Choice 모델을 호출하는 ``register()`` 를 제거하세요. 그런 다음 ``Poll`` 을 불러오기 위해 등록 코드를 수정하세요.: +Choice 모델을 호출하는 ``register()`` 를 제거하세요. 그런 다음 ``Poll`` 을 불러오기 위해 등록 코드를 수정하세요. + +:: class ChoiceInline(admin.StackedInline): model = Choice @@ -265,7 +273,7 @@ Choice 모델을 호출하는 ``register()`` 를 제거하세요. 그런 다음 이렇게 작동합니다.: 관련된 세개의 슬롯 -- ``extra`` 에 의해 선택된 -- 이 있고 언제든지 생성된 개체의 "수정" 페이지로 되돌아올 수 있으며, 또다른 세개의 추가 슬롯을 사용할 수도 있다. -한 가자 작은 문제에 대해 생각 해 봅시다. 관련된 Choice 개체를 입력하기 위해 모든 필드가 넓은 공간에 보여지고 있습니다. 이러한 이유로 Django 는 표를 이용하여 연관된 개체를 한 줄로 보여줍니다.; 다른과 같이 ``ChoiceInline`` 를 변경하세요.:: +한 가지 작은 문제에 대해 생각 해 봅시다. 관련된 Choice 개체를 입력하기 위해 모든 필드가 넓은 공간에 보여지고 있습니다. 이러한 이유로 Django 는 표를 이용하여 연관된 개체를 한 줄로 보여줍니다.; 다른과 같이 ``ChoiceInline`` 를 변경하세요.:: class ChoiceInline(admin.TabularInline): #... From 92a635b71316476f44d570d477af797c85079d77 Mon Sep 17 00:00:00 2001 From: Yong Choi Date: Sat, 18 Aug 2012 08:25:55 +0900 Subject: [PATCH 032/128] Update intro/tutorial02.txt --- intro/tutorial02.txt | 74 +++++++++++++++++++++++++++----------------- 1 file changed, 46 insertions(+), 28 deletions(-) diff --git a/intro/tutorial02.txt b/intro/tutorial02.txt index f5f9802..ba3441d 100644 --- a/intro/tutorial02.txt +++ b/intro/tutorial02.txt @@ -33,7 +33,7 @@ 제거하세요 -- 총 세 개 행의 주석을 제거해야 합니다. 이 파일은 URL 설정(URLconf) 파일이며 다음 자습서에서 보다 자세히 알아보겠습니다. 지금 여러분이 알아야 할 부분은 URL roots 를 어플리케이션에 연결시키는 것 입니다. 연결 후 여러분은 - 아래와 같은 ``urls.py`` 파일을 확인하실 수 있습니다: + 아래와 같은 ``urls.py`` 파일을 확인하실 수 있습니다. .. parsed-literal:: @@ -55,21 +55,21 @@ **url(r'^admin/', include(admin.site.urls)),** ) - (굵게 표시된 행이 주석이 제거된 행 입니다.) + (굵게 표시된 행이 주석이 제거된 행입니다.) 개발 서버 실행하기 ============================ 이제 개발 서버를 실행 시키고 본격적으로 관리자 사이트를 탐험해 보도록 하겠습니다. -첫 번째 자습서에서 배운 내용을 참고하여 아래와 같이 개발 서버를 실행 해 보세요: +첫 번째 자습서에서 배운 내용을 참고하여 아래와 같이 개발 서버를 실행 해 보세요. .. code-block:: bash python manage.py runserver 이제 웹 브라우저를 실행하고 로컬 도메인의 "/admin/" 으로 이동하세요 -- 예: -http://127.0.0.1:8000/admin/. 관리자 사이트의 로그인 화면을 볼 수 있을 것 입니다: +http://127.0.0.1:8000/admin/. 관리자 사이트의 로그인 화면을 볼 수 있을 것 입니다. .. image:: _images/admin01.png :alt: Django 관리자 사이트 로그인 화면 @@ -90,7 +90,7 @@ http://127.0.0.1:8000/admin/. 관리자 사이트의 로그인 화면을 볼 수 관리자 사이트 들어가기 ==================== -자, 이제 로그인 해 보세요. (첫번째 자습서에서 최고 관리자 계정을 생성한 것을 기억 하시나요? 만약 생성하지 않았거나, 비밀번호가 기억나지 않는다면 :ref:`다른 계정을 생성` 해 보세요.) 장고 관리자 사이트의 첫 페이지를 확인할 수 있을 것 입니다: +자, 이제 로그인 해 보세요. (첫번째 자습서에서 최고 관리자 계정을 생성한 것을 기억 하시나요? 만약 생성하지 않았거나, 비밀번호가 기억나지 않는다면 :ref:`다른 계정을 생성` 해 보세요.) 장고 관리자 사이트의 첫 페이지를 확인할 수 있을 것 입니다. .. image:: _images/admin02t.png :alt: Django 관리자 사이트 첫 페이지 @@ -112,7 +112,7 @@ Groups, users, sites 등 몇 개의 수정 가능한 컨텐츠를 확인할 수 admin.site.register(Poll) -수정사항을 확인하기 위해 개발 서버를 재시작 해야 합니다. 일반적으로 파일이 수정되면 서버는 자동으로 수정된 코드를 다시 불러오지만 새로 생성된 파일은 자동으로 불러오지 않습니다. +수정사항을 확인하기 위해 개발 서버를 재시작해야 합니다. 일반적으로 파일이 수정되면 서버는 자동으로 수정된 코드를 다시 불러오지만 새로 생성된 파일은 자동으로 불러오지 않습니다. 무료 관리 기능 탐험하기 ==================================== @@ -122,20 +122,20 @@ Groups, users, sites 등 몇 개의 수정 가능한 컨텐츠를 확인할 수 .. image:: _images/admin03t.png :alt: polls가 보여지는 Django 관리자 사이트 첫 페이지 -이제 "Polls."를 클릭하면 polls의 "change list" 를 볼 수 있습니다. 이 페이지에서는 데이터베이스의 모든 poll이 보여지게 되며 이중 한개를 선택하여 변경할 수 있습니다. +이제 "Polls"를 클릭하면 polls의 "change list" 를 볼 수 있습니다. 이 페이지에서는 데이터베이스의 모든 poll이 보여지게 되며 이중 한개를 선택하여 변경할 수 있습니다. 여기에 우리가 첫 번째 자습서에서 생성한 "What's up?" poll을 확인할 수 있습니다. .. image:: _images/admin04t.png :alt: Poll 변경 리스트 페이지 -Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: +Poll을 수정하기 위해 "What's up?" poll을 클릭하세요. .. image:: _images/admin05t.png :alt: Poll 개체 수정 폼 여기서 짚고 넘어가기: -* 폼은 Poll 모델로 부터 자동적으로 생성되었습니다. +* 폼은 Poll 모델로부터 자동적으로 생성되었습니다. * 서로 다른 모델의 필드 타입 (:class:`~django.db.models.DateTimeField`, :class:`~django.db.models.CharField`) 에 따라 적절한 HTML 입력 위젯이 @@ -164,7 +164,7 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: 정확한 값이 보여지는 것을 확인할 수 있을 것입니다. "Today" 와 "Now" 바로입력 버튼을 누르면 "Date published"의 정보를 바꿀 수 있습니다. 그리고 "Save and continue editing." 를 클릭한 후 오른쪽 위의 "History" 를 클릭 해 보세요. -이 페이지 에서는 Django 관리 사이트에서 이루어진 현 개체의 모든 변경 사항의 목록을 확인할 수 있으며, 수정 시간과 수정을 한 사용자 이름도 확인할 수 있습니다.: +이 페이지 에서는 Django 관리 사이트에서 이루어진 현 개체의 모든 변경 사항의 목록을 확인할 수 있으며, 수정 시간과 수정을 한 사용자 이름도 확인할 수 있습니다. .. image:: _images/admin06t.png :alt: Poll 개체의 History 페이지 @@ -174,7 +174,9 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: 몇분 동안 간단히 코드를 살펴보며 감탄한 것 처럼 여러분은 코드를 작성 할 필요가 없습니다. 단지 Poll 모델과 ``admin.site.register(Poll)`` 을 등록 하는 것 만으로, Django는 기본적인 폼의 외형을 생성할 수 있었습니다. 때때로 여러분은 관리자 사이트 폼의 외형과 작업을 커스터마이즈 해야 할 필요가 있을 것 입니다. 이는 여러분이 개채를 등록할 때 필요한 옵션을 Django 에게 알려주면 됩니다.. -수정 폼의 필드를 재 정렬 하는 예제를 통해서 어떻게 커스터마이즈 할 수 있는지 알아봅시다. ``admin.site.register(Poll)`` 라인을 아래와 같이 수정 해 봅시다.:: +수정 폼의 필드를 재 정렬 하는 예제를 통해서 어떻게 커스터마이즈 할 수 있는지 알아봅시다. ``admin.site.register(Poll)`` 라인을 아래와 같이 수정 해 봅시다. + +:: class PollAdmin(admin.ModelAdmin): fields = ['pub_date', 'question'] @@ -229,13 +231,15 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: 아직까지는요. -두 가지 방법을 통해 이 문제를 해결할 수 있습니다. 첫 번째 방법은 관리자 페이지에 ``Poll`` 과 함께 ``Choice`` 를 등록하는 것 입니다. 참 쉽죠?:: +두 가지 방법을 통해 이 문제를 해결할 수 있습니다. 첫 번째 방법은 관리자 페이지에 ``Poll`` 과 함께 ``Choice`` 를 등록하는 것 입니다. 참 쉽죠? + +:: from polls.models import Choice admin.site.register(Choice) -자, 이제 Django 관리자 페이지에서 "Choices" 옵션을 사용가능한것을 볼 수 있습니다. 자 이제 아래와 같은 "Add choice" 을 확인할 수 있습니다.: +자, 이제 Django 관리자 페이지에서 "Choices" 옵션을 사용가능한것을 볼 수 있습니다. 자 이제 아래와 같은 "Add choice" 을 확인할 수 있습니다. .. image:: _images/admin10.png :alt: Choice 의 관리 페이지 @@ -244,7 +248,7 @@ Poll을 수정하기 위해 "What's up?" poll을 클릭하세요: "Poll" 다음에 있는 "Add Another" 링크에 주목하세요. 다른 개체에 대한 ``ForeignKey`` 관계를 가지고 있는 모든 개체는 손쉽게 이용할 수 있습니다. "Add Another" 를 클릭하면 "Add poll" 폼이 있는 팝업 윈도우를 볼 수 있습니다. 팝업 윈도우에서 Poll을 추가 하고 "Save" 버튼을 누르면 Django 는 Poll을 데이터베이스에 저장하고 여러분이 보고있는 "Add choice"의 선택된 Choice에 동적으로 추가합니다. -그러나 시스템에 Choice 개체를 추가하는 작업은 비효율적인 작업입니다 . +그러나 시스템에 Choice 개체를 추가하는 작업은 비효율적인 작업입니다. 만약 여러분이 Poll 개체를 만들 때 여러개의 Choice를 추가할 수 있다면 더 좋을 것 입니다. 자, 그럼 어떻게 하는지 알아봅시다. Choice 모델을 호출하는 ``register()`` 를 제거하세요. 그런 다음 ``Poll`` 을 불러오기 위해 등록 코드를 수정하세요. @@ -273,7 +277,9 @@ Choice 모델을 호출하는 ``register()`` 를 제거하세요. 그런 다음 이렇게 작동합니다.: 관련된 세개의 슬롯 -- ``extra`` 에 의해 선택된 -- 이 있고 언제든지 생성된 개체의 "수정" 페이지로 되돌아올 수 있으며, 또다른 세개의 추가 슬롯을 사용할 수도 있다. -한 가지 작은 문제에 대해 생각 해 봅시다. 관련된 Choice 개체를 입력하기 위해 모든 필드가 넓은 공간에 보여지고 있습니다. 이러한 이유로 Django 는 표를 이용하여 연관된 개체를 한 줄로 보여줍니다.; 다른과 같이 ``ChoiceInline`` 를 변경하세요.:: +한 가지 작은 문제에 대해 생각 해 봅시다. 관련된 Choice 개체를 입력하기 위해 모든 필드가 넓은 공간에 보여지고 있습니다. 이러한 이유로 Django 는 표를 이용하여 연관된 개체를 한 줄로 보여줍니다.; 다른과 같이 ``ChoiceInline`` 를 변경하세요. + +:: class ChoiceInline(admin.TabularInline): #... @@ -293,26 +299,32 @@ Choice 모델을 호출하는 ``register()`` 를 제거하세요. 그런 다음 .. image:: _images/admin04t.png :alt: Poll 변경 리스트 페이지 -기본적으로 Django 는 각 개체를 ``str()`` 로 보여줍니다. 그러나 각 필드를 직접 보여주는게 더 효과적일 수도 있습니다. 이를 위해 ``list_display`` 관리 옵션을 사용합니다. ``list_display`` 옵션은 개체의 변경 리스트에서 컬럼 이름으로 사용되는 필드 이름의 튜플로 구성됩니다.:: +기본적으로 Django 는 각 개체를 ``str()`` 로 보여줍니다. 그러나 각 필드를 직접 보여주는 것이 더 효과적일 수도 있습니다. 이를 위해 ``list_display`` 관리 옵션을 사용합니다. ``list_display`` 옵션은 개체의 변경 리스트에서 컬럼 이름으로 사용되는 필드 이름의 튜플로 구성됩니다. + +:: class PollAdmin(admin.ModelAdmin): # ... list_display = ('question', 'pub_date') -좋은 지표로 삼기 위해 첫번째 자습서에서 만든 커스텀 메소드인 ``was_published_recently`` 을 포함시켜 봅시다.:: +좋은 지표로 삼기 위해 첫번째 자습서에서 만든 커스텀 메소드인 ``was_published_recently`` 을 포함시켜 봅시다. + +:: class PollAdmin(admin.ModelAdmin): # ... list_display = ('question', 'pub_date', 'was_published_recently') -이제 아래와 같은 Poll 변경 리스트를 확인하실 수 있습니다.: +이제 아래와 같은 Poll 변경 리스트를 확인하실 수 있습니다. .. image:: _images/admin13t.png :alt: 업데이트 된 Poll 변경 리스트 페이지 -컬럼 값에 따라 정렬하기 위해 컬럼 헤더를 클릭 해 보세요. -- 커스텀 메소드인 ``was_published_recently`` 는 정렬을 지원하지 않습니다. ``was_published_recently`` 의 컬럼 해더는 기본적으로 메소드의 이름으로 포현되며(공백은 밑줄로 대체) 각 컬럼은 문자열로 표현되게 됩니다. +컬럼 값에 따라 정렬하기 위해 컬럼 헤더를 클릭해 보세요. -- 커스텀 메소드인 ``was_published_recently`` 는 정렬을 지원하지 않습니다. ``was_published_recently`` 의 컬럼 해더는 기본적으로 메소드의 이름으로 포현되며(공백은 밑줄로 대체) 각 컬럼은 문자열로 표현되게 됩니다. + +여러분은 아래와 같이 ``models.py`` 에 있는 몇 개의 어트리뷰트를 변경하여 보다 보기 좋게 만들 수 있습니다. -여러분은 아래와 같이 ``models.py`` 에 있는 몇 개의 어트리뷰트를 변경하여 보다 보기 좋게 만들 수 있습니다.:: +:: class Poll(models.Model): # ... @@ -335,13 +347,17 @@ admin.py 파일을 수정하여 Poll 수정 리스트를 향상시킬 수 있습 ``pub_date`` 은 :class:`~django.db.models.fields.DateTimeField` 이기 때문에 Django 는 적절한 옵션을 제공합니다.: "Any date," "Today," "Past 7 days," "This month," "This year." -꽤 사용하기 편하게 구성되죠?이제 검색 기능을 추가 해 봅시다.:: +꽤 사용하기 편하게 구성되죠?이제 검색 기능을 추가 해 봅시다. + +:: search_fields = ['question'] 위의 옵션은 수정 목록 상단에 검색창(Search Box)를 추가합니다. 사용자가 검색어를 입력하면 Django 는 ``question`` 필드를 검색합니다. 여러분은 여러분이 원하는 만큼 필드를 추가할 수 있으며 내부에서 ``LIKE`` 질의를 하기 때문에 데이터베이스의 효율을 높일 수 있습니다. -마지막으로 Poll 개체는 날짜를 포함하므로 손쉽게 날짜 순으로 보여줄 수 있습니다. 아래 코드를 추가하세요.:: +마지막으로 Poll 개체는 날짜를 포함하므로 손쉽게 날짜 순으로 보여줄 수 있습니다. 아래 코드를 추가하세요. + +:: date_hierarchy = 'pub_date' @@ -349,7 +365,7 @@ days," "This month," "This year." 최상위 수준에서 선택 가능한 모든 연도가 표시됩니다. 또한 월 에서 일까지 순차적으로 선택할 수 있습니다. 이제 수정 리스트의 페이지네이션에 대하여 알아봅시다. 기본적으로 한 페이지에 100개의 아이템이 보여집니다. 이제 수정 목록 페이지네이션(Change-list pagination), 검색창(search boxes), -필터(filters), 날짜 구조화(date-hierarchies) and 컬럼 헤더 정렬(column-header-ordering) 모두 여러분이 생각하는 데로 작동합니다. +필터(filters), 날짜 구조화(date-hierarchies) and 컬럼 헤더 정렬(column-header-ordering) 모두 여러분이 생각하는 대로 작동합니다. 관리자 사이트 룩앤필(Look and feel) 커스터마이즈 하기 ================================= @@ -360,7 +376,9 @@ Django 의 템플릿 시스템을 이용하면 쉽게 변경할 수 있습니다 설정 파일(``mysite/settings.py``, 기억하나요?)을 열어 :setting:`TEMPLATE_DIRS` 설정을 봅시다. :setting:`TEMPLATE_DIRS` 은 Django 템플릿을 불러올 때 확인하는 파일 시스템 디렉토리로 구성된 튜플로 구성됩니다. 이는 검색을 위한 패스 입니다. -기본적으로 :setting:`TEMPLATE_DIRS` 는 비어있습니다. 이제 Django에게 어디에 우리의 템플릿이 있는지 알려주기 위해 한 줄 추가 해 봅시다.:: +기본적으로 :setting:`TEMPLATE_DIRS` 는 비어있습니다. 이제 Django에게 어디에 우리의 템플릿이 있는지 알려주기 위해 한 줄 추가 해 봅시다. + +:: TEMPLATE_DIRS = ( '/home/my_username/mytemplates', # 여러분의 디렉토리로 변경 해 주세요. @@ -369,21 +387,21 @@ Django 의 템플릿 시스템을 이용하면 쉽게 변경할 수 있습니다 이제 Django 소스코드의 기본 Django 관리자 템플릿 디렉토리 (``django/contrib/admin/templates``) 에 있는 ``admin/base_site.html``를 여러분이 :setting:`TEMPLATE_DIRS`에 지정한 디렉토리의 ``admin`` 하위 디렉토리로 복사합니다. 예를 들어, 만약 여러분의 :setting:`TEMPLATE_DIRS` 에 위와 같이 ``'/home/my_username/mytemplates'`` 가 포함되어 있다면, ``django/contrib/admin/templates/admin/base_site.html`` 를 ``/home/my_username/mytemplates/admin/base_site.html`` 로 복사하세요. ``admin`` 의 하위 디렉토리를 잊지 마세요. -다음으로, 파일을 수정하여 이미 입력 되 있는 Django 텍스트를 적절한 여러분의 사이트 이름으로 교체 해 주세요. +다음으로, 파일을 수정하여 이미 입력 되어 있는 Django 텍스트를 적절한 여러분의 사이트 이름으로 교체해 주세요. 이 템플릿 파일은 여러개의 ``{% block branding %}`` 과 ``{{ title }}`` 을 포함하고 있습니다. ``{%`` 와 ``{{`` 는 Django 템플릿 언어 중 일부입니다. Django 가 ``admin/base_site.html`` 를 출력할 때 HTML 페이지를 완성하기 위하여 이 텀플릿 언어는 평가됩니다. 여러분이 지금 템플릿에 대해 잘 알지 못해도 걱정하지 마세요. 세번째 자습서에서 Django의 탐플릿 언어에 대해 자세히 알아볼 것 입니다. Django의 기본 관리자 사이트 템플릿은 재정의(Override) 될 수 있다는 것만 알아두세요. 템플릿을 재정의 하기 위해, 위에서 한 작업들을 ``base_site.html`` 에 해 주세요. -- -파일을 기본 디렉토리에서 여러분의 커스텀 디렉토리에 복사 한 후 수정하세요. +파일을 기본 디렉토리에서 여러분의 커스텀 디렉토리에 복사한 후 수정하세요. 여기서 날카로운 여러분은 의문이 생길겁니다.: 만약 기본적으로 :setting:`TEMPLATE_DIRS` 가 비어있다면, -Django 는 어떻게 기본 관리자 사이트 템플릿을 찾나요? 정답은, Django는 기본적으로 각 앱 패키지의 하위디렉토리에 있는 ``templates/`` 의 템플릿을 자동으로 대체하여 사용합니다. 보다 자세한 정보를 위해 :ref:`template loader documentation ` 을 참조하세요. +Django는 어떻게 기본 관리자 사이트 템플릿을 찾나요? 정답은, Django는 기본적으로 각 앱 패키지의 하위 디렉토리에 있는 ``templates/`` 의 템플릿을 자동으로 대체하여 사용합니다. 보다 자세한 정보를 위해 :ref:`template loader documentation ` 을 참조하세요. 관리자 사이트 첫 페이지 커스터마이즈 하기 ============================== -여러분은 이제 Django 관리 사이트의 첫 페이지 룩앤필도 커스터마이즈 하고 싶을 것입니다. +여러분은 이제 Django 관리 사이트의 첫 페이지 룩앤필도 커스터마이즈하고 싶을 것입니다. 기본적으로 첫 페이지는 :setting:`INSTALLED_APPS` 에 등록된 모든 앱을 알파벳 순서로 보여줍니다. 여러분은 아마 레이아웃을 여러분이 원하는데로 변경하고 싶을 것 입니다. 초기 페이지는 관리자 사이트에서 가장 중요한 페이지 이며 쉽게 사용할 수 있어야 합니다. From b1e4c423b10f3fb7deb9d4582345873423d10304 Mon Sep 17 00:00:00 2001 From: Yong Choi Date: Sat, 18 Aug 2012 09:25:36 +0900 Subject: [PATCH 033/128] Update intro/tutorial03.txt --- intro/tutorial03.txt | 111 +++++++++++++++++++++++++++---------------- 1 file changed, 69 insertions(+), 42 deletions(-) diff --git a/intro/tutorial03.txt b/intro/tutorial03.txt index 0be642c..b28fc31 100644 --- a/intro/tutorial03.txt +++ b/intro/tutorial03.txt @@ -2,7 +2,7 @@ Writing your first Django app, part 3 ===================================== -이 자습서는 :doc:`Tutorial 2 `의 마지막에 이어서 시작 합니다. 우리는 계속해서 "뷰"라고 하는 퍼블릭 인터페이스를 작성하는데 중점을 두고 웹-투표 애플리케이션을 계속 합니다. +이 자습서는 :doc:`Tutorial 2 `\ 의 마지막에 이어서 시작 합니다. 우리는 계속해서 "뷰"라고 하는 퍼블릭 인터페이스를 작성하는데 중점을 두고 웹-투표 애플리케이션을 계속 합니다. 철학 ========== @@ -50,13 +50,15 @@ Django는 첫 번째 정규표현식을 시작으로, 일치하는 결과를 찾 일치하는 결과를 찾으면, Django는 파이썬 콜백 함수를 호출 합니다. 이 때, :class:`~django.http.HttpRequest` 객체를 첫 번째 인자로 하고, 정규표현식에서 찾은 임의의 값을 키워드 인자로 가집니다. 옵션으로 그 사전에서 임의의 키워드(튜플의 세 번째 아이템)를 가져다가 사용 합니다. -:class:`~django.http.HttpRequest` 객체에 대해서 자세히 알고 싶다면, :doc:`/ref/request-response` 를 참고 하세요. URLconfs 에 대해서 자세히 알고 싶다면, :doc:`/topics/http/urls`를 참고 하세요. +:class:`~django.http.HttpRequest` 객체에 대해서 자세히 알고 싶다면, :doc:`/ref/request-response`\ 를 참고 하세요. URLconfs 에 대해서 자세히 알고 싶다면, :doc:`/topics/http/urls`\ 를 참고 하세요. -자습서 1에서 처음 ``django-admin.py startproject mysite`` 를 실행 했을때, 기본 URLconf를 ``mysite/urls.py``에 생성 했습니다. 게다가 자동으로 :setting:`ROOT_URLCONF`을 =(``settings.py`` 안에 있는) ``mysite/urls.py``를 가리키도록 설정 했습니다.:: +자습서 1에서 처음 ``django-admin.py startproject mysite`` 를 실행 했을때, 기본 URLconf를 ``mysite/urls.py``\ 에 생성했습니다. 게다가 자동으로 :setting:`ROOT_URLCONF`\ 을 =(``settings.py`` 안에 있는) ``mysite/urls.py``\ 를 가리키도록 설정 했습니다. + +:: ROOT_URLCONF = 'mysite.urls' -예제를 보겠습니다. ``mysite/urls.py``를 아래와 같이 수정 합니다.:: +예제를 보겠습니다. ``mysite/urls.py``\ 를 아래와 같이 수정 합니다.:: from django.conf.urls import patterns, include, url @@ -71,21 +73,25 @@ Django는 첫 번째 정규표현식을 시작으로, 일치하는 결과를 찾 url(r'^admin/', include(admin.site.urls)), ) -여기 까지의 내용을 설명하면. 누군가 웹 사이트에 "/polls/23/"이라는 요청을 하면, Django는 :setting:`ROOT_URLCONF` 설정이 가리키고 있기 때문에 위의 파이썬 모듈을 로드 할 것 입니다. 위의 파이썬 모듈은 ``urlpatterns``라는 이름을 가진 변수를 찾습니다. 그리고, 정규표현식들을 순서대로 순회 합니다. 위의 파이썬 모듈이 일치하는 정규표현식을 찾았을때 -- ``r'^polls/(?P\d+)/$'`` -- 위의 파이썬 모듈은 ``polls/views.py``에 있는 ``detail()`` 함수를 로드 합니다. 끝으로 파이썬 모듈은 아래와 같이 ``detail()`` 함수를 호출 합니다. +여기까지의 내용을 설명하면, 누군가 웹 사이트에 "/polls/23/"\ 이라는 요청을 하면, Django는 :setting:`ROOT_URLCONF` 설정이 가리키고 있기 때문에 위의 파이썬 모듈을 로드 할 것 입니다. 위의 파이썬 모듈은 ``urlpatterns``라는 이름을 가진 변수를 찾습니다. 그리고, 정규표현식들을 순서대로 순회 합니다. 위의 파이썬 모듈이 일치하는 정규표현식을 찾았을때 -- ``r'^polls/(?P\d+)/$'`` -- 위의 파이썬 모듈은 ``polls/views.py``에 있는 ``detail()`` 함수를 로드 합니다. 끝으로 파이썬 모듈은 아래와 같이 ``detail()`` 함수를 호출 합니다. + +:: detail(request=, poll_id='23') -``poll_id='23'``는 ``(?P\d+)``에서 온 것 입니다. 패턴 주위에 괄호()를 사용해서 그 패턴과 일치하는 텍스트를 "포"하고, 뷰 함수에게 인자로 보냅니다; ``?P``는 일치하는 패턴을 인식하는데 사용 할 이름을 정의 합니다. 그리고 ``\d+``는 숫자가 나와야 할 순서를 의미하는 정규표현식입니다.(역자 주: 정규착 표현식에서 \d는 0~9 사이의 숫자를 의미하고 +는 앞 문자가 1번 이상 나타나면 된다는 것을 의미 합니다. 따라서, 1개 이상의 숫자가 있으면 된다는 뜻입니다. +``poll_id='23'``\ 는 ``(?P\d+)``\ 에서 온 것 입니다. 패턴 주위에 괄호()를 사용해서 그 패턴과 일치하는 텍스트를 "포"하고, 뷰 함수에게 인자로 보냅니다; ``?P``는 일치하는 패턴을 인식하는데 사용 할 이름을 정의 합니다. 그리고 ``\d+``는 숫자가 나와야 할 순서를 의미하는 정규표현식입니다.(역자 주: 정규착 표현식에서 \d는 0~9 사이의 숫자를 의미하고 +는 앞 문자가 1번 이상 나타나면 된다는 것을 의미 합니다. 따라서, 1개 이상의 숫자가 있으면 된다는 뜻입니다. - URL 패턴들은 정규표현식이기 때문에, 무엇을 하든 제한이 없습니다. 그리고, 아래와 같은 악취미가 있지 않는 한 ``.php``같은 URL 부스러기 들을 붙일 필요가 없습니다 :: +URL 패턴들은 정규표현식이기 때문에, 무엇을 하든 제한이 없습니다. 그리고, 아래와 같은 악취미가 있지 않는 한 ``.php``\ 같은 URL 부스러기 들을 붙일 필요가 없습니다. + +:: (r'^polls/latest\.php$', 'polls.views.index'), 위 처럼, 하지마세요. 바보 같으니까요. -이런 정규표현식들은 GET, POST 파라미터들 또는 도메인 이름을 검색하지는 않는 다는 것을 기억하십시오. 예를 들어 ``http://www.example.com/myapp/``을 향한 요청에서, URLconf는 ``myapp/``만 찾을 것 입니다. ``http://www.example.com/myapp/?page=3``를 향한 요청에서, URLconf는 ``myapp/``만 찾을 것 입니다. +이런 정규표현식들은 GET, POST 파라미터들 또는 도메인 이름을 검색하지는 않는 다는 것을 기억하십시오. 예를 들어 ``http://www.example.com/myapp/``\ 을 향한 요청에서, URLconf는 ``myapp/``\ 만 찾을 것 입니다. ``http://www.example.com/myapp/?page=3``\ 를 향한 요청에서, URLconf는 ``myapp/``\ 만 찾을 것 입니다. -만약, 정규표현식에 대해 도움이 필요하면, `Wikipedia's entry`_ 그리고 :mod:`re` 모듈의 문서를 참고 하십시오. 또, Jeffrey Friedl 의 오라일리의 책 "Mastering Regular Expressions" 도 끝내줍니다. +만약, 정규표현식에 대해 도움이 필요하면, `Wikipedia's entry`_ 그리고 :mod:`re` 모듈의 문서를 참고하십시오. 또, Jeffrey Friedl 의 오라일리의 책 "Mastering Regular Expressions" 도 끝내줍니다. Finally, a performance note : 처음 URLconf 모듈이 로드 되었을때, 이 정규표현식들은 컴파일 되었습니다. 그래서, 매우 빠릅니다. @@ -102,28 +108,34 @@ Finally, a performance note : 처음 URLconf 모듈이 로드 되었을때, 이 python manage.py runserver -웹브라우져에서 "http://localhost:8000/polls/" 로 이동 하십시오. -당신은 유쾌하게 컬러링된 아래 메세지의 에러 페이지를 보게 될 것 입니다.:: +웹브라우저에서 "http://localhost:8000/polls/"\ 로 이동 하십시오. +당신은 유쾌하게 컬러링된 아래 메세지의 에러 페이지를 보게 될 것입니다. + +:: ViewDoesNotExist at /polls/ Could not import polls.views.index. View does not exist in module polls.views. -이 오류는 ``polls/views.py`` 모듈에 ``index()`` 함수를 작성한 적이 없기 때문에 발생 합니다. +이 오류는 ``polls/views.py`` 모듈에 ``index()`` 함수를 작성한 적이 없기 때문에 발생합니다. "/polls/23/", "/polls/23/results/" 그리고 "/polls/23/vote/" 도 시도해 보십시오. 오류 메세지들은 Django가 어떤 뷰에 접근 하려고 했는지 알려줍니다(그리고, 당신이 뷰들을 작성 하지 않았기 때문에 찾기에 실패 합니다). -첫 번째 뷰를 작성 합니다. ``polls/views.py``를 열어서 아래의 파이썬 코드를 입력 합니다.:: +첫 번째 뷰를 작성 합니다. ``polls/views.py``를 열어서 아래의 파이썬 코드를 입력 합니다. + +:: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the poll index.") -실제로 가능한 가장 간단한 뷰 입니다. 브라우저에서 "/polls/" 로 이동하면, 당신이 작성한 텍스트를 볼 수 있어야 합니다. +실제로 가능한 가장 간단한 뷰입니다. 브라우저에서 "/polls/" 로 이동하면, 당신이 작성한 텍스트를 볼 수 있어야 합니다. 뷰를 몇 개 더 추가해 봅니다. 이 뷰들은 인자를 가지기 때문에 조금씩 다릅니다. (기억하세요, URLconf에서 정규표현식으로 무엇이 '포착'되었든지 인자로 들어옵니다.) +:: + def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id) @@ -133,20 +145,21 @@ Finally, a performance note : 처음 URLconf 모듈이 로드 되었을때, 이 def vote(request, poll_id): return HttpResponse("You're voting on poll %s." % poll_id) -브라우저에서 "/polls/34/"를 둘러보세요. `detail()` 메소드를 실행하고, URL에 입력한 ID를 나타냅니다. "/polls/34/results/"과 "/polls/34/vote/"도 시도해 보세요. -- 이 URL들은 placeholder results와 투표 페이지 를 보여줍니다. +브라우저에서 "/polls/34/"\ 를 둘러보세요. `detail()` 메소드를 실행하고, URL에 입력한 ID를 나타냅니다. "/polls/34/results/"\ 과 "/polls/34/vote/"\ 도 시도해 보세요. -- 이 URL들은 placeholder results와 투표 페이지를 보여줍니다. 실제로 동작하는 뷰 작성 하기 ====================================== - 각각의 뷰는 둘 중에 하나를 수행합니다. 요청받은 페이지에 대한 컨텐츠를 가지고 있는 :class:`~django.http.HttpResponse` 객체를 반환 하거나 :exc:`~django.http.Http404` 같은 예외를 발생합니다. 나머지는 당신에게 달렸습니다. +각각의 뷰는 둘 중에 하나를 수행합니다. 요청받은 페이지에 대한 컨텐츠를 가지고 있는 :class:`~django.http.HttpResponse` 객체를 반환 하거나 :exc:`~django.http.Http404` 같은 예외를 발생합니다. 나머지는 당신에게 달렸습니다. 당신의 뷰는 데이터베이스에서 레코드들을 읽을수도, 아닐수도 있습니다. Django에 있는 것 같은 템플릿 시스템 --또는 서드 파티 파이썬 템플릿 시스템 -- 을 사용할수도, 안할수도 있습니다. PDF 파일을 생성하거나, XML을 출력하거나, ZIP파일을 생성하거나, 당신이 무엇을 원하든 간에 원하는 파이썬 라이브러리들을 사용 하십시오. -모든 Django가 필요한 것은 :class:`~django.http.HttpResponse` 입니다. 또는 예외 입니다. +모든 Django가 필요한 것은 :class:`~django.http.HttpResponse`\ 입니다. 또는 예외 입니다. -사용하기 편리하므로, 우리가 :doc:`Tutorial 1 `에서 다루었던 Django가 가지고 있는 데이터베이스 API를 사용해 봅시다. 날짜 순서로 정렬하고, 콤마로 나눈, 시스템에 있는 최근 5개의 투표 질문들을 보여주는``index()`` 뷰를 만들어봅시다. +사용하기 편리하므로, 우리가 :doc:`Tutorial 1 `\ 에서 다루었던 Django가 가지고 있는 데이터베이스 API를 사용해 봅시다. 날짜 순서로 정렬하고, 콤마로 나눈, 시스템에 있는 최근 5개의 투표 질문들을 보여주는``index()`` 뷰를 만들어봅시다. +:: from polls.models import Poll from django.http import HttpResponse @@ -155,8 +168,10 @@ PDF 파일을 생성하거나, XML을 출력하거나, ZIP파일을 생성하거 output = ', '.join([p.question for p in latest_poll_list]) return HttpResponse(output) -위의 코드에는 문제가 있습니다. 페이지 디자인을 뷰에 하드 코딩 했습니다. 만약 페이지가 보이는 형태를 변경 하려고 한다면, 파이썬 코드를 수정 해야 합니다. -그래서 디자인을 파이썬으로부터 분리하기 위해서 Django 템플릿 시스템을 이용합니다. +위의 코드에는 문제가 있습니다. 페이지 디자인을 뷰에 하드 코딩했습니다. 만약 페이지가 보이는 형태를 변경하려고 한다면, 파이썬 코드를 수정 해야 합니다. +그래서 디자인을 파이썬으로부터 분리하기 위해서 Django 템플릿 시스템을 이용합니다. + +:: from django.template import Context, loader from polls.models import Poll @@ -170,7 +185,7 @@ PDF 파일을 생성하거나, XML을 출력하거나, ZIP파일을 생성하거 }) return HttpResponse(t.render(c)) -위의 코드는 "polls/index.html" 템플릿을 로드하고 컨텍스트를 전달 합니다. +위의 코드는 "polls/index.html" 템플릿을 로드하고 컨텍스트를 전달합니다. 컨텍스트는 파이썬 객체들 이름을 가진 사전 매핑 템플릿 변수 입니다. 페이지를 새로고침 하십시오. 에러를 보게 될것 입니다:: @@ -178,11 +193,11 @@ PDF 파일을 생성하거나, XML을 출력하거나, ZIP파일을 생성하거 TemplateDoesNotExist at /polls/ polls/index.html -아. 아직 템플릿이 없군요. 첫 번째, 당신의 파일시스템 아무곳에나 Django가 접근 할 수 있는 곳에 디렉토리를 생성 하십시오. (Django runs as whatever user your +아. 아직 템플릿이 없군요. 첫 번째, 당신의 파일시스템 아무 곳에나 Django가 접근할 수 있는 곳에 디렉토리를 생성하십시오. (Django runs as whatever user your server runs.) 대신, 그 파일들은 문서 root에 넣지 마세요. 보안 문제가 있으므로, 디렉토리를 퍼블릭으로 만들지 않아야 합니다. 그리고, ``settings.py``의 :setting:`TEMPLATE_DIRS`를 수정해서, Django에게 어디서 템플릿들을 찾을 수 있는지 알려 주십시오. -- 자습서 2의 "Customize the admin look and feel" 섹션에서 한것 처럼 하면 됩니다. -위의 내용을 완료 했다면, ``polls`` 디렉토리를 템플릿 디렉토리에 생성 하십시오. +위의 내용을 완료 했다면, ``polls`` 디렉토리를 템플릿 디렉토리에 생성하십시오. 그 안에 ``index.html`` 파일을 생성하십시오. 우리의 ``loader.get_template('polls/index.html')`` 코드는 파일 시스템에 있는 "[template_directory]/polls/index.html" 과 매핑 된다는 것을 기억하십시오. 아래의 코드를 템플릿에 입력하십시오. @@ -206,6 +221,8 @@ server runs.) 대신, 그 파일들은 문서 root에 넣지 마세요. 보안 render_to_response()는 템플릿을 로드하고, 컨텍스트를 채우고, :class:`~django.http.HttpResponse` 객체를 렌더링된 템플릿의 결과와 함께 반환하기 위해 자주 사용하는 구문입니다. Django는 지름길을 제공 합니다. 전체 ``index()`` 뷰를 재작성했습니다. +:: + from django.shortcuts import render_to_response from polls.models import Poll @@ -213,7 +230,7 @@ render_to_response()는 템플릿을 로드하고, 컨텍스트를 채우고, :c latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list}) -모든 뷰에서 한 번만 위의 작업을 하면, 더이상 :mod:`~django.template.loader`, :class:`~django.template.Context` 그리고 :class:`~django.http.HttpResponse`를 불러올 필요가 없다는 것을 기억하십시오. +모든 뷰에서 한 번만 위의 작업을 하면, 더이상 :mod:`~django.template.loader`, :class:`~django.template.Context` 그리고 :class:`~django.http.HttpResponse`\ 를 불러올 필요가 없다는 것을 기억하십시오. :func:`~django.shortcuts.render_to_response` 함수는 템플릿 이름을 첫 번째 인자로, 선택 가능한 두 번째 인자로 사전을 갖습니다. :func:`~django.shortcuts.render_to_response` 함수는 주어진 컨텍스트와 함께 렌더링된 템플릿 객체의 :class:`~django.http.HttpResponse` 를 반환 합니다. @@ -242,7 +259,9 @@ render_to_response()는 템플릿을 로드하고, 컨텍스트를 채우고, :c 지름길: get_object_or_404() ------------------------------- -get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`를 사용기위해서 자주 사용하는 구문입니다. 객체가 없을 때는 :exc:`~django.http.Http404`를 띄웁니다. Django 는 지름길을 제공 합니다. ``detail()`` 뷰를 재작성 했습니다.:: +get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`\ 를 사용기위해서 자주 사용하는 구문입니다. 객체가 없을 때는 :exc:`~django.http.Http404`\ 를 띄웁니다. Django 는 지름길을 제공 합니다. ``detail()`` 뷰를 재작성 했습니다. + +:: from django.shortcuts import render_to_response, get_object_or_404 # ... @@ -250,7 +269,7 @@ get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`를 사용기 p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p}) -:func:`~django.shortcuts.get_object_or_404`함수는 Django 모델을 첫 번째 인자로 받고, :meth:`~django.db.models.query.QuerySet.get` 함수에서 전달된 임의의 숫자를 키워드 인자로 받습니다. 만약, 객체가 존재하지 않으면, :exc:`~django.http.Http404`를 띄웁니다. +:func:`~django.shortcuts.get_object_or_404` 함수는 Django 모델을 첫 번째 인자로 받고, :meth:`~django.db.models.query.QuerySet.get` 함수에서 전달된 임의의 숫자를 키워드 인자로 받습니다. 만약, 객체가 존재하지 않으면, :exc:`~django.http.Http404`\ 를 띄웁니다. .. 충고:: 철학 @@ -263,12 +282,12 @@ get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`를 사용기 그 이유는 모델 계층을 뷰 계층에 결합 하기 때문입니다. Django의 으뜸가는 디자인 목표중 하나는 느슨한 결합을 유지하는 것입니다. - 물론 :func:`~django.shortcuts.get_object_or_404`와 거의 똑같이 동작하는 :func:`~django.shortcuts.get_list_or_404` 함수도 있습니다. -- :meth:`~django.db.models.query.QuerySet.get` 대신 :meth:`~django.db.models.query.QuerySet.filter`를 사용하는 경우는 제외합니다. :func:`~django.shortcuts.get_list_or_404` 는 리스트가 비어 있을 경우에 :exc:`~django.http.Http404`를 띄웁니다. +물론 :func:`~django.shortcuts.get_object_or_404`와 거의 똑같이 동작하는 :func:`~django.shortcuts.get_list_or_404` 함수도 있습니다. -- :meth:`~django.db.models.query.QuerySet.get` 대신 :meth:`~django.db.models.query.QuerySet.filter`를 사용하는 경우는 제외합니다. :func:`~django.shortcuts.get_list_or_404` 는 리스트가 비어 있을 경우에 :exc:`~django.http.Http404`를 띄웁니다. 404 (page not found) 뷰 작성하기 ================================= - 뷰에서 :exc:`~django.http.Http404`를 일으키면, Django는 404 오류를 다루기로한 특별한 뷰를 로드 할 것 입니다. Django는 루트 URLconf(그리고 오직 루트 URLconf에서 ``handler404``를 설정해야 합니다. 이외의 위치에서는 모두 무시합니다.)에서 ``handler404`` python dotted syntax 내의 문자열 변수를 찾음으로써 404오류를 다루기로한 특별한 뷰를 찾을 것입니다. -- 같은 형태로 일반적인 URLconf 콜백들을 사용 합니다. 404 뷰 자체로는 특별한게 아무것도 없습니다. 일반적인 뷰일 뿐입니다. +뷰에서 :exc:`~django.http.Http404`를 일으키면, Django는 404 오류를 다루기로한 특별한 뷰를 로드 할 것 입니다. Django는 루트 URLconf(그리고 오직 루트 URLconf에서 ``handler404``를 설정해야 합니다. 이외의 위치에서는 모두 무시합니다.)에서 ``handler404`` python dotted syntax 내의 문자열 변수를 찾음으로써 404오류를 다루기로한 특별한 뷰를 찾을 것입니다. -- 같은 형태로 일반적인 URLconf 콜백들을 사용 합니다. 404 뷰 자체로는 특별한게 아무것도 없습니다. 일반적인 뷰일 뿐입니다. 일반적으로는 404 뷰들을 만드는데 신경쓸 필요가 없습니다. 만약 ``handler404``를 설정하지 않으면, 내장된 :func:`django.views.defaults.page_not_found`를 기본적으로 사용합니다. 이 경우에도 여전히 한 가지 할 일이 남아 있기는 합니다. ``404.html`` 템플릿을 root템플릿 디렉토리에 생성 해야 합니다. 기본적인 404 뷰는 그 템플릿을 모든 404 오류에 사용 할 것입니다. 만약 :setting:`DEBUG`를 ``False`` (in your settings module)로 설정 하거나, ``404.html`` 파일을 만들지 않으면, ``Http500``을 대신 띄웁니다. 그런 이유로 ``404.html``을 생성하는 것을 기억하십시오. @@ -301,10 +320,10 @@ get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`를 사용기 {% endfor %} - 템플릿 시스템은 변수 어트리뷰트들에 접근 하기 위해서 dot-lookup 구문을 사용 합니다. ``{{ poll.question }}``의 예제에서 보면, Django는 처음에 ``poll`` 객체에서 사전을 찾습니다. 찾기에 실패하면, 어트리뷰트를 조회 합니다. -- 이 경우에는 잘 동작 합니다. 만약, 어트리뷰트 조회에 실패하면, list-index 조회를 시도 합니다. +템플릿 시스템은 변수 어트리뷰트들에 접근 하기 위해서 dot-lookup 구문을 사용 합니다. ``{{ poll.question }}``\ 의 예제에서 보면, Django는 처음에 ``poll`` 객체에서 사전을 찾습니다. 찾기에 실패하면, 어트리뷰트를 조회 합니다. -- 이 경우에는 잘 동작 합니다. 만약, 어트리뷰트 조회에 실패하면, list-index 조회를 시도 합니다. :ttag:`{% for %}` 루프에서 메소드 호출이 발생합니다: -``poll.choice_set.all`` 은 파이썬 코드 ``poll.choice_set.all()``로 변환 합니다. 파이썬 코드 ``poll.choice_set.all()``는 선택한 객체들의 an iterable을 반환하고, :ttag:`{% for %}` 태그에서 사용하기 적당합니다. +``poll.choice_set.all`` 은 파이썬 코드 ``poll.choice_set.all()``로 변환 합니다. 파이썬 코드 ``poll.choice_set.all()``\ 는 선택한 객체들의 an iterable을 반환하고, :ttag:`{% for %}` 태그에서 사용하기 적당합니다. 템플릿에 대한 자세한 내용은 :doc:`template guide ` 를 보세요. @@ -313,6 +332,8 @@ URLconfs를 단순화 하기 뷰와 템플릿 시스템사이를 종횡무진 하기에는 시간이 좀 걸립니다. URLconf를 수정 하는 동안, 내부에 상당한 양의 불필요한 중복이 있다는 것을 알아차렸을 것입니다. +:: + urlpatterns = patterns('', url(r'^polls/$', 'polls.views.index'), url(r'^polls/(?P\d+)/$', 'polls.views.detail'), @@ -320,9 +341,11 @@ URLconfs를 단순화 하기 url(r'^polls/(?P\d+)/vote/$', 'polls.views.vote'), ) -다시말해 ``polls.views``가 모든 콜백에 있습니다. +다시말해 ``polls.views``\ 가 모든 콜백에 있습니다. -왜냐하면 공통적인 경우에, URLconf 프레임워크는 공통적인 prefixs들에 대한 지름길을 제공 합니다. 당신은 공통적인 prefixe들을 뽑아 낼수 있습니다. 그리고, 뽑아낸 prefixes들을 :func:`~django.conf.urls.patterns`에 아래와 같이 첫 번째 인자로 추가 할 수 있습니다. :: +왜냐하면 공통적인 경우에, URLconf 프레임워크는 공통적인 prefixs들에 대한 지름길을 제공 합니다. 당신은 공통적인 prefix들을 뽑아 낼수 있습니다. 그리고, 뽑아낸 prefix들을 :func:`~django.conf.urls.patterns`\ 에 아래와 같이 첫 번째 인자로 추가 할 수 있습니다. + +:: urlpatterns = patterns('polls.views', url(r'^polls/$', 'index'), @@ -331,10 +354,12 @@ URLconfs를 단순화 하기 url(r'^polls/(?P\d+)/vote/$', 'vote'), ) -이 방법은 이전의 포매팅과 기능적으로 일치 합니다. 더 깔끔합니다. +이 방법은 이전의 포매팅과 기능적으로 일치합니다. 더 깔끔합니다. + +일반적으로 URLconf의 모든 콜백에 하나의 애플리케이션을 위한 prefix를 적용하고 싶지 않다면, 여러 개의 :func:`~django.conf.urls.patterns`\ 를 연결 할 수 있습니다. +. ``mysite/urls.py`` 전체는 아래와 같습니다. -일반적으로 URLconf의 모든 콜백에 하나의 애플리케이션을 위한 prefix를 적용하고 싶지 않다면, 여러개의 :func:`~django.conf.urls.patterns`를 연결 할 수 있습니다. -. ``mysite/urls.py`` 전체는 아래와 같습니다. :: +:: from django.conf.urls import patterns, include, url @@ -355,13 +380,15 @@ URLconfs를 단순화 하기 URLconf의 결합도 낮추기 ======================= -하는 김에 우리는 Django 프로젝트 설정으로 부터 우리의 투표-앱 URL 들을 분리하는 시간을 가져야 합니다. Django 앱들은 플러그인 처럼 사용 할수 있도록 만들었습니다. -- 각각의 특정한 앱이 최소한의 수정으로 다른 Django installation 으로 이전 가능해야 합니다. +하는 김에 우리는 Django 프로젝트 설정으로 부터 우리의 투표-앱 URL 들을 분리하는 시간을 가져야 합니다. Django 앱들은 플러그인 처럼 사용 할수 있도록 만들었습니다. -- 각각의 특정한 앱이 최소한의 수정으로 다른 Django installation 으로 이전 가능해야 합니다. + +이 시점에서 투표 앱은 상당히 결합도가 낮습니다. ``python manage.py startapp``\ 가 생성한 엄격한 디렉토리 구조에 감사하기 바랍니다. 그렇나, 단 하나 URLconf가 Django 설정들과 결합되어 있습니다. -이 시점에서 투표 앱은 상당히 결합도가 낮습니다. ``python manage.py startapp``가 생성한 엄격한 디렉토리 구조에 감사하기 바랍니다. 그렇나, 단 하나 URLconf가 Django 설정들과 결합되어 있습니다. +``mysite/urls.py``\ 에 있는 URL들은 수정했습니다. 그러나, 앱의 URL 디자인은 Django installation이 아니라, 특정 앱 지향적입니다. -- 그래서 URL들을 앱 디렉토리 안으로 이동합니다. - ``mysite/urls.py``에 있는 URL들은 수정했습니다. 그러나, 앱의 URL 디자인은 Django installation이 아니라, 특정 앱 지향적입니다. -- 그래서 URL들을 앱 디렉토리 안으로 이동 합니다. +``mysite/urls.py`` 파일을 ``polls/urls.py``\ 로 복사 하십시오. 그리고, ``mysite/urls.py``\ 에서 투표-한정 URL들을 제거 하고, :func:`~django.conf.urls.include`를 그 자리에 추가 하도록 변경 합니다. -``mysite/urls.py`` 파일을 ``polls/urls.py``로 복사 하십시오. 그리고, ``mysite/urls.py``에서 투표-한정 URL들을 제거 하고, :func:`~django.conf.urls.include`를 그 자리에 추가 하도록 변경 합니다:: +:: from django.conf.urls import patterns, include, url @@ -373,12 +400,12 @@ URLconf의 결합도 낮추기 url(r'^admin/', include(admin.site.urls)), ) -:func:`~django.conf.urls.include`은 간단하게 다른 URLconf를 참조 합니다. +:func:`~django.conf.urls.include`\ 은 간단하게 다른 URLconf를 참조 합니다. 정규표현식은 ``$``(문자열의 끝과 일치하는 문자)를 가지지 않고, trailling slash를 가지는 점을 기억하십시오. 어디든지 Django가 :func:`~django.conf.urls.include` 함수를 만나면, 해당 시점에서 URL의 일치하는 부분을 잘라냅니다. 그리고, 남은 문자열을 추가 처리를 위해서 불러들인 URLconf로 전송 합니다. 사용자가 이 시스템에서 "/polls/34/"으로 이동하는 경우 무슨 일이 생기는지 보십시오: -* Django는 ``'^polls/'``에서 일치하는 것을 찾을것입니다. +* Django는 ``'^polls/'``\ 에서 일치하는 것을 찾을 것입니다. * 그리고나서, Django 는 일치하는 문자(``"polls/"``)를 벗겨 낼것 입니다. 남은 문자 -- ``"34/"`` --를 'polls.urls' URLconf로 추가 처리를 위해서 보냅니다. @@ -395,7 +422,7 @@ URLconf의 결합도 낮추기 url(r'^(?P\d+)/vote/$', 'vote'), ) -:func:`~django.conf.urls.include`와 URLconf의 결합도를 낮추는 아이디어는 URL들의 플러그인플레이를 쉽게 만들어 줍니다. 이제 투표들은 각자 URLconf를 가지고 있습니다. 투표들은 "/polls/" 밑에도 있을 수 있고, "/fun_polls/" 밑에도, "/content/polls/" 밑에도, 그리고 다른 어떠한 루트 경로 에도 있을 수 있습니다. 그리고 앱은 여전히 잘 동작 할 것 입니다. +:func:`~django.conf.urls.include`\ 와 URLconf의 결합도를 낮추는 아이디어는 URL들의 플러그인플레이를 쉽게 만들어 줍니다. 이제 투표들은 각자 URLconf를 가지고 있습니다. 투표들은 "/polls/" 밑에도 있을 수 있고, "/fun_polls/" 밑에도, "/content/polls/" 밑에도, 그리고 다른 어떠한 루트 경로 에도 있을 수 있습니다. 그리고 앱은 여전히 잘 동작 할 것 입니다. 모든 투표 앱들은 절대 경로가 아니라, 상대 경로를 사용 합니다. From f655eb7a42992e98b383072a1d712e1fb3444545 Mon Sep 17 00:00:00 2001 From: Yong Choi Date: Sat, 18 Aug 2012 09:37:47 +0900 Subject: [PATCH 034/128] Update intro/tutorial03.txt --- intro/tutorial03.txt | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/intro/tutorial03.txt b/intro/tutorial03.txt index b28fc31..7fa575e 100644 --- a/intro/tutorial03.txt +++ b/intro/tutorial03.txt @@ -1,5 +1,5 @@ ===================================== -Writing your first Django app, part 3 +첫 번째 Django 앱 만들기, part 3 ===================================== 이 자습서는 :doc:`Tutorial 2 `\ 의 마지막에 이어서 시작 합니다. 우리는 계속해서 "뷰"라고 하는 퍼블릭 인터페이스를 작성하는데 중점을 두고 웹-투표 애플리케이션을 계속 합니다. @@ -42,13 +42,14 @@ URL 디자인 하기 URL 구조를 디자인 하는 것은 뷰를 작성하는 첫 번째 단계입니다. URLconf라는 파이썬 모듈을 생성함으로써, URL구조를 디자인 할 수 있습니다. URLconfs는 Django가 주어진 URL을 주어진 파이썬 코드와 연결하는 방법 입니다. -사용자가 Django-powered 페이지를 요청 할 때, 시스템은 Python dotted syntax에 있는 문자열을 포함하는 :setting:'ROOT_URLCONF' 설정을 참고 합니다. Django 는 URLconf 모듈을 로드 합니다. 그리고, 아래와 같은 포맷의 튜플인 모듈-레벨 변수인 ``urlpatterns``를 검색 합니다. +사용자가 Django-powered 페이지를 요청 할 때, 시스템은 Python dotted syntax에 있는 문자열을 포함하는 :setting:'ROOT_URLCONF' 설정을 참고 합니다. Django 는 URLconf 모듈을 로드 합니다. 그리고, 아래와 같은 포맷의 튜플인 모듈-레벨 변수인 ``urlpatterns``\ 를 검색합니다. +:: (regular expression, Python callback function [, optional dictionary]) Django는 첫 번째 정규표현식을 시작으로, 일치하는 결과를 찾을 때 까지 요청 받은 URL을 각각의 정규표현식과 비교하면서 리스트 아래로 내려갑니다. - 일치하는 결과를 찾으면, Django는 파이썬 콜백 함수를 호출 합니다. 이 때, :class:`~django.http.HttpRequest` 객체를 첫 번째 인자로 하고, 정규표현식에서 찾은 임의의 값을 키워드 인자로 가집니다. 옵션으로 그 사전에서 임의의 키워드(튜플의 세 번째 아이템)를 가져다가 사용 합니다. +일치하는 결과를 찾으면, Django는 파이썬 콜백 함수를 호출 합니다. 이 때, :class:`~django.http.HttpRequest` 객체를 첫 번째 인자로 하고, 정규표현식에서 찾은 임의의 값을 키워드 인자로 가집니다. 옵션으로 그 사전에서 임의의 키워드(튜플의 세 번째 아이템)를 가져다가 사용 합니다. :class:`~django.http.HttpRequest` 객체에 대해서 자세히 알고 싶다면, :doc:`/ref/request-response`\ 를 참고 하세요. URLconfs 에 대해서 자세히 알고 싶다면, :doc:`/topics/http/urls`\ 를 참고 하세요. @@ -58,7 +59,9 @@ Django는 첫 번째 정규표현식을 시작으로, 일치하는 결과를 찾 ROOT_URLCONF = 'mysite.urls' -예제를 보겠습니다. ``mysite/urls.py``\ 를 아래와 같이 수정 합니다.:: +예제를 보겠습니다. ``mysite/urls.py``\ 를 아래와 같이 수정합니다. + +:: from django.conf.urls import patterns, include, url @@ -79,7 +82,7 @@ Django는 첫 번째 정규표현식을 시작으로, 일치하는 결과를 찾 detail(request=, poll_id='23') -``poll_id='23'``\ 는 ``(?P\d+)``\ 에서 온 것 입니다. 패턴 주위에 괄호()를 사용해서 그 패턴과 일치하는 텍스트를 "포"하고, 뷰 함수에게 인자로 보냅니다; ``?P``는 일치하는 패턴을 인식하는데 사용 할 이름을 정의 합니다. 그리고 ``\d+``는 숫자가 나와야 할 순서를 의미하는 정규표현식입니다.(역자 주: 정규착 표현식에서 \d는 0~9 사이의 숫자를 의미하고 +는 앞 문자가 1번 이상 나타나면 된다는 것을 의미 합니다. 따라서, 1개 이상의 숫자가 있으면 된다는 뜻입니다. +``poll_id='23'``\ 는 ``(?P\d+)``\ 에서 온 것 입니다. 패턴 주위에 괄호()를 사용해서 그 패턴과 일치하는 텍스트를 "포"하고, 뷰 함수에게 인자로 보냅니다; ``?P``\ 는 일치하는 패턴을 인식하는데 사용 할 이름을 정의 합니다. 그리고 ``\d+``\ 는 숫자가 나와야 할 순서를 의미하는 정규표현식입니다.(역자 주: 정규착 표현식에서 \d는 0~9 사이의 숫자를 의미하고 +는 앞 문자가 1번 이상 나타나면 된다는 것을 의미 합니다. 따라서, 1개 이상의 숫자가 있으면 된다는 뜻입니다. URL 패턴들은 정규표현식이기 때문에, 무엇을 하든 제한이 없습니다. 그리고, 아래와 같은 악취미가 있지 않는 한 ``.php``\ 같은 URL 부스러기 들을 붙일 필요가 없습니다. @@ -195,7 +198,7 @@ PDF 파일을 생성하거나, XML을 출력하거나, ZIP파일을 생성하거 아. 아직 템플릿이 없군요. 첫 번째, 당신의 파일시스템 아무 곳에나 Django가 접근할 수 있는 곳에 디렉토리를 생성하십시오. (Django runs as whatever user your server runs.) 대신, 그 파일들은 문서 root에 넣지 마세요. 보안 문제가 있으므로, 디렉토리를 퍼블릭으로 만들지 않아야 합니다. -그리고, ``settings.py``의 :setting:`TEMPLATE_DIRS`를 수정해서, Django에게 어디서 템플릿들을 찾을 수 있는지 알려 주십시오. -- 자습서 2의 "Customize the admin look and feel" 섹션에서 한것 처럼 하면 됩니다. +그리고, ``settings.py``\ 의 :setting:`TEMPLATE_DIRS`\ 를 수정해서, Django에게 어디서 템플릿들을 찾을 수 있는지 알려 주십시오. -- 자습서 2의 "Customize the admin look and feel" 섹션에서 한것 처럼 하면 됩니다. 위의 내용을 완료 했다면, ``polls`` 디렉토리를 템플릿 디렉토리에 생성하십시오. 그 안에 ``index.html`` 파일을 생성하십시오. 우리의 ``loader.get_template('polls/index.html')`` 코드는 파일 시스템에 있는 "[template_directory]/polls/index.html" 과 매핑 된다는 것을 기억하십시오. @@ -248,7 +251,7 @@ render_to_response()는 템플릿을 로드하고, 컨텍스트를 채우고, :c raise Http404 return render_to_response('polls/detail.html', {'poll': p}) -위의 코드에는 이전에 보지 못한 개념이 있습니다. 투표와 함께 요청받은 ID가 존재 하지 않으면 뷰가 :exc:`~django.http.Http404`예외를 띄웁니다. +위의 코드에는 이전에 보지 못한 개념이 있습니다. 투표와 함께 요청받은 ID가 존재 하지 않으면 뷰가 :exc:`~django.http.Http404` 예외를 띄웁니다. `polls/detail.html``에 무엇을 넣을지는 조금 나중에 고민 할 것 입니다. 그렇지만, 빠르게 예제를 동작하게 만들고 싶다면, 단지:: @@ -271,7 +274,7 @@ get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`\ 를 사용 :func:`~django.shortcuts.get_object_or_404` 함수는 Django 모델을 첫 번째 인자로 받고, :meth:`~django.db.models.query.QuerySet.get` 함수에서 전달된 임의의 숫자를 키워드 인자로 받습니다. 만약, 객체가 존재하지 않으면, :exc:`~django.http.Http404`\ 를 띄웁니다. -.. 충고:: 철학 +.. admonition:: 철학 왜 우리가 더 높은 레벨에서 :exc:`~django.core.exceptions.ObjectDoesNotExist`를 사용해서 자동으로 예외를 처리하는 대신 헬퍼 함수인 :func:`~django.shortcuts.get_object_or_404`를 사용 했을까요? @@ -289,8 +292,8 @@ get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`\ 를 사용 뷰에서 :exc:`~django.http.Http404`를 일으키면, Django는 404 오류를 다루기로한 특별한 뷰를 로드 할 것 입니다. Django는 루트 URLconf(그리고 오직 루트 URLconf에서 ``handler404``를 설정해야 합니다. 이외의 위치에서는 모두 무시합니다.)에서 ``handler404`` python dotted syntax 내의 문자열 변수를 찾음으로써 404오류를 다루기로한 특별한 뷰를 찾을 것입니다. -- 같은 형태로 일반적인 URLconf 콜백들을 사용 합니다. 404 뷰 자체로는 특별한게 아무것도 없습니다. 일반적인 뷰일 뿐입니다. -일반적으로는 404 뷰들을 만드는데 신경쓸 필요가 없습니다. 만약 ``handler404``를 설정하지 않으면, 내장된 :func:`django.views.defaults.page_not_found`를 기본적으로 사용합니다. 이 경우에도 여전히 한 가지 할 일이 남아 있기는 합니다. ``404.html`` 템플릿을 root템플릿 디렉토리에 생성 해야 합니다. 기본적인 404 뷰는 그 템플릿을 모든 404 오류에 사용 할 것입니다. 만약 :setting:`DEBUG`를 ``False`` (in your settings module)로 설정 하거나, ``404.html`` -파일을 만들지 않으면, ``Http500``을 대신 띄웁니다. 그런 이유로 ``404.html``을 생성하는 것을 기억하십시오. +일반적으로는 404 뷰들을 만드는데 신경쓸 필요가 없습니다. 만약 ``handler404``를 설정하지 않으면, 내장된 :func:`django.views.defaults.page_not_found`\ 를 기본적으로 사용합니다. 이 경우에도 여전히 한 가지 할 일이 남아 있기는 합니다. ``404.html`` 템플릿을 root템플릿 디렉토리에 생성 해야 합니다. 기본적인 404 뷰는 그 템플릿을 모든 404 오류에 사용 할 것입니다. 만약 :setting:`DEBUG`를 ``False`` (in your settings module)로 설정 하거나, ``404.html`` +파일을 만들지 않으면, ``Http500``\ 을 대신 띄웁니다. 그런 이유로 ``404.html``\ 을 생성하는 것을 기억하십시오. 404 뷰들에 대해서 몇 가지더 알아두어야 할 것이 있습니다. @@ -304,12 +307,12 @@ get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`\ 를 사용 500 (server error) 뷰 작성하기 =============================== -비슷하게, 루트 URLconf는 서버 오류인 경우에 호출하기 위한 뷰를 가리키는 ``handler500``을 정의 하고 있을 것 입니다. 서버 오류는 뷰 코드에서 런타임 에러가 있을때 발생합니다. +비슷하게, 루트 URLconf는 서버 오류인 경우에 호출하기 위한 뷰를 가리키는 ``handler500``\ 을 정의하고 있을 것입니다. 서버 오류는 뷰 코드에서 런타임 에러가 있을때 발생합니다. 템플릿 시스템 사용하기 ======================= -투표 어플리케이션의 ``detail()`` 뷰로 돌아가 보도록 합니다. ``poll``이 컨텍스트 변수로 주어졌을때, "polls/detail.html" 템플릿이 어떻게 되는지 보도록 합니다.: +투표 어플리케이션의 ``detail()`` 뷰로 돌아가 보도록 합니다. ``poll``\ 이 컨텍스트 변수로 주어졌을때, "polls/detail.html" 템플릿이 어떻게 되는지 보도록 합니다.: .. code-block:: html+django @@ -401,9 +404,9 @@ URLconf의 결합도 낮추기 ) :func:`~django.conf.urls.include`\ 은 간단하게 다른 URLconf를 참조 합니다. -정규표현식은 ``$``(문자열의 끝과 일치하는 문자)를 가지지 않고, trailling slash를 가지는 점을 기억하십시오. 어디든지 Django가 :func:`~django.conf.urls.include` 함수를 만나면, 해당 시점에서 URL의 일치하는 부분을 잘라냅니다. 그리고, 남은 문자열을 추가 처리를 위해서 불러들인 URLconf로 전송 합니다. +정규표현식은 ``$``\ (문자열의 끝과 일치하는 문자)를 가지지 않고, trailling slash를 가지는 점을 기억하십시오. 어디든지 Django가 :func:`~django.conf.urls.include` 함수를 만나면, 해당 시점에서 URL의 일치하는 부분을 잘라냅니다. 그리고, 남은 문자열을 추가 처리를 위해서 불러들인 URLconf로 전송 합니다. -사용자가 이 시스템에서 "/polls/34/"으로 이동하는 경우 무슨 일이 생기는지 보십시오: +사용자가 이 시스템에서 "/polls/34/"\ 로 이동하는 경우 무슨 일이 생기는지 보십시오. * Django는 ``'^polls/'``\ 에서 일치하는 것을 찾을 것입니다. @@ -411,7 +414,7 @@ URLconf의 결합도 낮추기 남은 문자 -- ``"34/"`` --를 'polls.urls' URLconf로 추가 처리를 위해서 보냅니다. - 이제, URLconf와 Django 설정의 결합도를 낮추었습니다. 우리는 개별 라인 맨 앞에 있는 "polls/"를 삭제하고, 관리자 사이트에 등록한 라인들을 삭제 함으로써 ``polls.urls``와 URLconf의 결합도를 낮추었습니다. ``polls/urls.py`` 파일은 지금 아래와 같아야 합니다. :: +이제, URLconf와 Django 설정의 결합도를 낮추었습니다. 우리는 개별 라인 맨 앞에 있는 "polls/"를 삭제하고, 관리자 사이트에 등록한 라인들을 삭제 함으로써 ``polls.urls``와 URLconf의 결합도를 낮추었습니다. ``polls/urls.py`` 파일은 지금 아래와 같아야 합니다. :: from django.conf.urls import patterns, include, url @@ -424,7 +427,7 @@ URLconf의 결합도 낮추기 :func:`~django.conf.urls.include`\ 와 URLconf의 결합도를 낮추는 아이디어는 URL들의 플러그인플레이를 쉽게 만들어 줍니다. 이제 투표들은 각자 URLconf를 가지고 있습니다. 투표들은 "/polls/" 밑에도 있을 수 있고, "/fun_polls/" 밑에도, "/content/polls/" 밑에도, 그리고 다른 어떠한 루트 경로 에도 있을 수 있습니다. 그리고 앱은 여전히 잘 동작 할 것 입니다. -모든 투표 앱들은 절대 경로가 아니라, 상대 경로를 사용 합니다. +모든 투표 앱들은 절대 경로가 아니라, 상대 경로를 사용합니다. - 뷰를 작성 하는 것에 익숙해 지면 단순한 폼 처리와 제너릭 뷰를 배우기 위해서 :doc:`part 4 of this tutorial -`를 읽어보십시오. +뷰를 작성 하는 것에 익숙해 지면 단순한 폼 처리와 제너릭 뷰를 배우기 위해서 :doc:`part 4 of this tutorial +`\ 를 읽어보십시오. From 0e75076ef8c814426103d49faa924e2b1fdca77f Mon Sep 17 00:00:00 2001 From: Yong Choi Date: Sat, 18 Aug 2012 09:50:04 +0900 Subject: [PATCH 035/128] Update intro/tutorial03.txt --- intro/tutorial03.txt | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/intro/tutorial03.txt b/intro/tutorial03.txt index 7fa575e..8811e11 100644 --- a/intro/tutorial03.txt +++ b/intro/tutorial03.txt @@ -163,6 +163,7 @@ PDF 파일을 생성하거나, XML을 출력하거나, ZIP파일을 생성하거 사용하기 편리하므로, 우리가 :doc:`Tutorial 1 `\ 에서 다루었던 Django가 가지고 있는 데이터베이스 API를 사용해 봅시다. 날짜 순서로 정렬하고, 콤마로 나눈, 시스템에 있는 최근 5개의 투표 질문들을 보여주는``index()`` 뷰를 만들어봅시다. :: + from polls.models import Poll from django.http import HttpResponse @@ -253,7 +254,9 @@ render_to_response()는 템플릿을 로드하고, 컨텍스트를 채우고, :c 위의 코드에는 이전에 보지 못한 개념이 있습니다. 투표와 함께 요청받은 ID가 존재 하지 않으면 뷰가 :exc:`~django.http.Http404` 예외를 띄웁니다. -`polls/detail.html``에 무엇을 넣을지는 조금 나중에 고민 할 것 입니다. 그렇지만, 빠르게 예제를 동작하게 만들고 싶다면, 단지:: +`polls/detail.html``\ 에 무엇을 넣을지는 조금 나중에 고민할 것입니다. 그렇지만, 빠르게 예제를 동작하게 만들고 싶다면, 단지 + +:: {{ poll }} @@ -262,7 +265,7 @@ render_to_response()는 템플릿을 로드하고, 컨텍스트를 채우고, :c 지름길: get_object_or_404() ------------------------------- -get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`\ 를 사용기위해서 자주 사용하는 구문입니다. 객체가 없을 때는 :exc:`~django.http.Http404`\ 를 띄웁니다. Django 는 지름길을 제공 합니다. ``detail()`` 뷰를 재작성 했습니다. +get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`\ 를 사용하기 위해서 자주 사용하는 구문입니다. 객체가 없을 때는 :exc:`~django.http.Http404`\ 를 띄웁니다. Django는 지름길을 제공합니다. ``detail()`` 뷰를 재작성했습니다. :: @@ -290,16 +293,14 @@ get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`\ 를 사용 404 (page not found) 뷰 작성하기 ================================= -뷰에서 :exc:`~django.http.Http404`를 일으키면, Django는 404 오류를 다루기로한 특별한 뷰를 로드 할 것 입니다. Django는 루트 URLconf(그리고 오직 루트 URLconf에서 ``handler404``를 설정해야 합니다. 이외의 위치에서는 모두 무시합니다.)에서 ``handler404`` python dotted syntax 내의 문자열 변수를 찾음으로써 404오류를 다루기로한 특별한 뷰를 찾을 것입니다. -- 같은 형태로 일반적인 URLconf 콜백들을 사용 합니다. 404 뷰 자체로는 특별한게 아무것도 없습니다. 일반적인 뷰일 뿐입니다. +뷰에서 :exc:`~django.http.Http404`\ 를 일으키면, Django는 404 오류를 다루기로 한 특별한 뷰를 로드할 것 입니다. Django는 루트 URLconf(그리고 오직 루트 URLconf에서 ``handler404``를 설정해야 합니다. 이외의 위치에서는 모두 무시합니다.)에서 ``handler404`` python dotted syntax 내의 문자열 변수를 찾음으로써 404오류를 다루기로한 특별한 뷰를 찾을 것입니다. -- 같은 형태로 일반적인 URLconf 콜백들을 사용 합니다. 404 뷰 자체로는 특별한게 아무것도 없습니다. 일반적인 뷰일 뿐입니다. -일반적으로는 404 뷰들을 만드는데 신경쓸 필요가 없습니다. 만약 ``handler404``를 설정하지 않으면, 내장된 :func:`django.views.defaults.page_not_found`\ 를 기본적으로 사용합니다. 이 경우에도 여전히 한 가지 할 일이 남아 있기는 합니다. ``404.html`` 템플릿을 root템플릿 디렉토리에 생성 해야 합니다. 기본적인 404 뷰는 그 템플릿을 모든 404 오류에 사용 할 것입니다. 만약 :setting:`DEBUG`를 ``False`` (in your settings module)로 설정 하거나, ``404.html`` +일반적으로는 404 뷰들을 만드는데 신경쓸 필요가 없습니다. 만약 ``handler404``\ 를 설정하지 않으면, 내장된 :func:`django.views.defaults.page_not_found`\ 를 기본적으로 사용합니다. 이 경우에도 여전히 한 가지 할 일이 남아 있기는 합니다. ``404.html`` 템플릿을 root템플릿 디렉토리에 생성 해야 합니다. 기본적인 404 뷰는 그 템플릿을 모든 404 오류에 사용 할 것입니다. 만약 :setting:`DEBUG`\ 를 ``False`` (in your settings module)로 설정 하거나, ``404.html`` 파일을 만들지 않으면, ``Http500``\ 을 대신 띄웁니다. 그런 이유로 ``404.html``\ 을 생성하는 것을 기억하십시오. 404 뷰들에 대해서 몇 가지더 알아두어야 할 것이 있습니다. -* :setting:`DEBUG`를 ``True``로 설정 했다면(설정 모듈 안에서) 404 뷰는 절대로 사용하지 않을 것입니다. (그리고 ``404.html`` 템플릿은 절대 렌더 되지 않습니다). 왜냐하면 traceback을 대신 표시하기 때문입니다. - - +* :setting:`DEBUG`\ 를 ``True``\ 로 설정 했다면(설정 모듈 안에서) 404 뷰는 절대로 사용하지 않을 것입니다. (그리고 ``404.html`` 템플릿은 절대 렌더 되지 않습니다). 왜냐하면 traceback을 대신 표시하기 때문입니다. * 404 뷰는 Django가 URLconf 내의 모든 정규표현식을 검색하고도, 일치하는 표현을 찾지 못했을 때도 호출합니다. @@ -312,7 +313,7 @@ get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`\ 를 사용 템플릿 시스템 사용하기 ======================= -투표 어플리케이션의 ``detail()`` 뷰로 돌아가 보도록 합니다. ``poll``\ 이 컨텍스트 변수로 주어졌을때, "polls/detail.html" 템플릿이 어떻게 되는지 보도록 합니다.: +투표 어플리케이션의 ``detail()`` 뷰로 돌아가 보도록 합니다. ``poll``\ 이 컨텍스트 변수로 주어졌을때, "polls/detail.html" 템플릿이 어떻게 되는지 보도록 합니다. .. code-block:: html+django @@ -389,7 +390,7 @@ URLconf의 결합도 낮추기 ``mysite/urls.py``\ 에 있는 URL들은 수정했습니다. 그러나, 앱의 URL 디자인은 Django installation이 아니라, 특정 앱 지향적입니다. -- 그래서 URL들을 앱 디렉토리 안으로 이동합니다. -``mysite/urls.py`` 파일을 ``polls/urls.py``\ 로 복사 하십시오. 그리고, ``mysite/urls.py``\ 에서 투표-한정 URL들을 제거 하고, :func:`~django.conf.urls.include`를 그 자리에 추가 하도록 변경 합니다. +``mysite/urls.py`` 파일을 ``polls/urls.py``\ 로 복사 하십시오. 그리고, ``mysite/urls.py``\ 에서 투표-한정 URL들을 제거 하고, :func:`~django.conf.urls.include`\ 를 그 자리에 추가하도록 변경합니다. :: From 4509018079cca89d0851de86f5d2200816d99d0e Mon Sep 17 00:00:00 2001 From: JIHO HEO Date: Sat, 18 Aug 2012 22:20:36 +0900 Subject: [PATCH 036/128] =?UTF-8?q?=EB=B2=88=EC=97=AD=EC=99=84=EB=A3=8C=20?= =?UTF-8?q?=EB=8B=A4=EC=8B=9C=20=EC=98=AC=EB=A6=BD=EB=8B=88=EB=8B=A4~?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- intro/tutorial01.txt | 518 +++++++++++++++---------------------------- 1 file changed, 176 insertions(+), 342 deletions(-) diff --git a/intro/tutorial01.txt b/intro/tutorial01.txt index 5402977..8a71a19 100644 --- a/intro/tutorial01.txt +++ b/intro/tutorial01.txt @@ -1,23 +1,23 @@ -===================================== +===================================== 첫번째 장고 앱 만들기! part1 ===================================== 예제로 배워봅시다. -이 자습서를 통하여, 우리는 기초적인 설문조사 애플리케이션을 만들어 나갈 것입니다. +우리는 이 자습서를 통하여, 기초적인 투표 애플리케이션을 만들어 나갈 것입니다. -이 애플리케이션은 두 부분으로 구성되어집니다. +이 애플리케이션은 두 부분으로 구성됩니다. -* 공개된 사이트는 사람들이 설문조사를 볼 수 있으며 설문조사에 투표 할 수 있는 곳 입니다. -* 어드민 사이트는 당신(관리자)이 설문조사에 대하여 추가, 수정, 삭제를 할 수 있는 곳 입니다. +* 공개된 사이트는 사람들이 투표내용을 볼 수 있으며 투표에에 참여 할 수 있습니다. +* 관리자 사이트는 당신(관리자)이 설문조사에 대하여 추가, 수정, 삭제를 할 수 있습니다. -우리는 이미 :doc:`Django 설치를 ` 완료 하였다고 가정합니다. 당신은 파이썬 인터프리터를 실행하여 ``import django``를 입력해 봄으로써 Django가 설치 되어 있는지 확인 할 수 있습니다. 만약 에러없이 실행된다면, Django 설치가 완료된 것입니다. +우리는 여러분이 이미 :doc:`Django 설치`를 완료 하였다고 가정하에 진행 하도록 하겠습니다. 여러분은 파이썬 인터프리터를 실행하여 ``import django``를 입력해 봄으로써 Django가 설치 되어 있는지 확인 할 수 있습니다. 만약 에러없이 실행된다면, Django 설치가 완료된 것입니다. .. admonition:: 도움말은 어디서 얻을 수 있나요?: - 만약 당신이 이 자습서를 따라하는 도중 문제가 발생 할 경우 + 만약 여러분이 이 자습서를 따라하는 도중 문제가 발생 할 경우 `django-users`__ 로 메시지를 보내 주시거나 또는 `#django on irc.freenode.net`__ 에서 - 당신에게 도움을 줄 다른 Django 사용자와 채팅을 할 수 있습니다. + 당신에게 도움을 줄 다른 Django 사용자와 채팅을 할 수 있습니다. __ http://groups.google.com/group/django-users __ irc://irc.freenode.net/django @@ -25,61 +25,49 @@ __ irc://irc.freenode.net/django 프로젝트 만들기 ================== -만약 당신이 지금 처음으로 Django를 사용 하는 것이라면, 당신은 몇가치 초기 설정에 신경을 써야 합니다. 즉, 당신은 Django :term:`project` 를 구축하는데 몇가지 자동 생성되는 코드를 필요로 합니다 -- Django의 인스턴스를 위한 세팅들(데이터베이스 설정을 포함), -Django의 특별한 옵션과 애플리캐이션의 특별한 설정들. +만약 여러분이 처음으로 Django를 사용 하는 것이라면, 여러분은 몇가지 초기 설정에 신경 써야 합니다. 즉, 여러분은 Django :term:`project` 를 구축하는데 몇가지 자동 생성되는 코드를 필요로 합니다 -- Django의 인스턴스를 위한 세팅들(데이터베이스 설정을 포함), Django의 특별한 옵션과 애플리캐이션의 특별한 설정들. -명령행에서 , ``cd`` 디렉토리 (코드가 생성될 디렉토리) 그리고 다음 명령어 실행: +명령행에서 , ``cd`` 디렉토리 (코드가 생성될 디렉토리)로 디렉토리 이동 후 다음 명령어 실행: .. code-block:: bash django-admin.py startproject mysite -이것은 현재 디렉토리에 ``mysite`` 라는 디렉토리를 생성합니다 . +이것은 현재 위치한 디렉토리에 ``mysite`` 라는 디렉토리를 생성합니다 . -.. admonition:: 스크립트의 이름은 배포 패키지에 따라 다를 수 있습니다 +.. admonition:: django-admim 스크립트의 이름은 배포 패키지에 따라 다를 수 있습니다 - 만약 당신이 리눅스 배포판 패키지 관리자를 이용하여 Django를 설치 하였다면 - (e.g. apt-get or yum) ``django-admin.py`` 파일의 이름을 - ``django-admin``로 변경 되었을 수도 있습니다. 당신은 이 문서에서 계속적으로 각 명령에 + 만약 여러분이 리눅스 배포판 패키지 관리자를 이용하여 Django를 설치 하였다면 + (e.g. apt-get or yum) ``django-admin.py`` 파일의 이름이 + ``django-admin``로 변경 되었을 수도 있습니다. 그럴 경우 여러분은 이 문서에서 계속적으로 각 명령에 ``.py`` 을 생략하여 사용 할 수 있습니다. .. admonition:: Mac OS X 권한 - 만약 당신이 Mac OS X를 사용 한다면, 당신은 ``django-admin.py startproject``를 실행 할 때 - "permission denied" 메시지를 볼 수 있을 것입니다.. 이것은 - OS X와 같은 유닉스 기반 시스템은, 프로그램을 실행하기 전에 해당 파일에 "executable(실행)" + 만약 여러분이 Mac OS X를 사용 하신다면, 여러분은 ``django-admin.py startproject``를 실행 할 때 + "permission denied" 메시지를 볼 수 있을 것입니다. OS X와 같은 유닉스 기반 시스템은, 프로그램을 실행하기 전에 해당 파일에 "executable(실행)" 표시를 해줘야 하기 때문입니다. 실생 표시를 하기 위해서는, 터미널 앱을 열고 :doc:`django-admin.py` 가 설치되어 있는 디렉토리로 이동합니다. (``cd``명령을 사용) - 그리고 - ``sudo chmod +x django-admin.py`` 명령어를 실행합니다. + 그리고 ``sudo chmod +x django-admin.py`` 명령어를 실행합니다. -.. note:: +.. 참고:: - You'll need to avoid naming projects after built-in Python or Django - components. In particular, this means you should avoid using names like - ``django`` (which will conflict with Django itself) or ``test`` (which - conflicts with a built-in Python package). + 여러분은 파이썬이나 Django 구성요소에 내장된 이름을 프로젝트 이름을 정하는 것을 피해야 합니다. 특히, + ``django`` (Django자체와 충돌 발생)나 ``test``(파이썬 패키지에 내장되어 있어 충돌이 발생)과 같은 이름사용을 주의해야 한다는 것 입니다. -:doc:`django-admin.py ` should be on your system path if you -installed Django via ``python setup.py``. If it's not on your path, you can find -it in ``site-packages/django/bin``, where ``site-packages`` is a directory -within your Python installation. Consider symlinking to :doc:`django-admin.py -` from some place on your path, such as -:file:`/usr/local/bin`. +:doc:`django-admin.py `는 여러분이 Django를 ``python setup.py`` 명령으로 설치를 하였다면 여러분의 시스템 경로에 존재 할 것입니다. 만약 찾을 수 없다면 여러분은 +``site-packages/django/bin`` 여기에서 찾을 수 있을 것 이고, ``site-packages`` 는 파이썬의 설치 경로입니다. +불편하다면 :doc:`django-admin.py ` 을 :file:`/usr/local/bin`로 심볼릭링크를 걸어 둘 것을 고려 해 볼 수 있습니다. -.. admonition:: Where should this code live? +.. admonition:: 어디에서 이 코드가 실행 되나요? - If your background is in PHP, you're probably used to putting code under the - Web server's document root (in a place such as ``/var/www``). With Django, - you don't do that. It's not a good idea to put any of this Python code - within your Web server's document root, because it risks the possibility - that people may be able to view your code over the Web. That's not good for - security. + 만약 여러분이 PHP개발 자라면, 아마도 여러분은 웹 서버의 document root 디렉토리(``/var/www``과 비슷한)에 코드를 Django와 같이 올리려 할 것 입니다. + 하지만 파이썬 코드를 웹 서버와 같이 올려 두는 것은 위험에 노출 될 가능 성이 있기 때문에 그렇게 하지 않는 편이 좋습니다. + 많은 사람들은 웹을 통하여 여러분의 코드를 볼 수 있고, 그럴 경우 보안상 좋지 않습니다. - Put your code in some directory **outside** of the document root, such as - :file:`/home/mycode`. + 여러분의 코드를 **document root 밖의 폴더**, 예를 들어 :file:`/home/mycode` 와 같은 폴더에 넣어 두는 것이 좋습니다. -Let's look at what :djadmin:`startproject` created:: +:djadmin:`startproject` 를 이용해서 만들어진 구조를 확인해 봅시다:: mysite/ manage.py @@ -89,50 +77,36 @@ Let's look at what :djadmin:`startproject` created:: urls.py wsgi.py -.. admonition:: Doesn't match what you see? +.. .. admonition:: 여러분이 보시는 것과 다른가요? - The default project layout recently changed. If you're seeing a "flat" - layout (with no inner :file:`mysite/` directory), you're probably using - a version of Django that doesn't match this tutorial version. You'll - want to either switch to the older tutorial or the newer Django version. + 최근에 기본적인 프로젝트 레이아웃이 변경이 되었습니다. 만약 여러분이 "flat"이 보인다면( :file:`mysite/` 디렉토리 안의), 여러분은 아마도 + 이 자습서와 다른 버전의 Django를 사용 하고 있는 것입니다. 이럴 경우 여러분은 예전 자습서로 공부를 하는 방법과, 새로운 Django버전을 설치하는 방법을 선택 할 수 있습니다. -These files are: +이러한 파일은: -* The outer :file:`mysite/` directory is just a container for your - project. Its name doesn't matter to Django; you can rename it to anything - you like. +* 밖에 있는 :file:`mysite/` 디렉토리는 여러분의 프로젝트의 컨테이너 역할을 하는 + 디렉토리 입니다. 이 이름은 Django에서 별로 중요하지 않습니다; 여러분이 원하한다면 어떠한 이름으로도 변경 할 수 있습니다. -* :file:`manage.py`: A command-line utility that lets you interact with this - Django project in various ways. You can read all the details about - :file:`manage.py` in :doc:`/ref/django-admin`. +* :file:`manage.py`: 명령 유틸리티를 이용하여 여러분은 다양한 방법으로 Django 프로젝트와 상호작용을 할 수 있습니다. + 여러분은 :doc:`/ref/django-admin` 에서 :file:`manage.py` 에 관한 더 많은 정보를 얻을 수 있습니다. -* The inner :file:`mysite/` directory is the actual Python package for your - project. Its name is the Python package name you'll need to use to import - anything inside it (e.g. ``import mysite.settings``). +* 안쪽 :file:`mysite/` 디렉토리는 여러분이 만든 실제 파이썬 패키지 입니다. 이 패키지 이름은여러분이 코드 안에서 import 할 때 사용 할 수 있습니다(e.g. ``import mysite.settings``). -* :file:`mysite/__init__.py`: An empty file that tells Python that this - directory should be considered a Python package. (Read `more about - packages`_ in the official Python docs if you're a Python beginner.) +* :file:`mysite/__init__.py`: 아무것도 없는 빈 파일인 이 파일은 파이썬에서 이 디렉토리가 파이썬 패키지라는 것을 알려줍니다. + (만약 여러분이 파이썬을 처음 공부하시는 분이라면 `more about packages`_ 에서 공식문서를 읽어 보시기 바랍니다.) -* :file:`mysite/settings.py`: Settings/configuration for this Django - project. :doc:`/topics/settings` will tell you all about how settings - work. +* :file:`mysite/settings.py`: Django에서 필요한 설정 및 구성을 하는 파일 입니다. :doc:`/topics/settings` 문서에서 여러분의 Django설정을 어떻게 해야 하는지 알려 줄 것입니다. -* :file:`mysite/urls.py`: The URL declarations for this Django project; a - "table of contents" of your Django-powered site. You can read more about - URLs in :doc:`/topics/http/urls`. +* :file:`mysite/urls.py`: Django 프로젝트에서 URL을 설정 합니다; Django site의 "목차(사이트 맵)"입니다. 여러분들은 :doc:`/topics/http/urls`에서 URL에 관한 더 많은 정보를 읽어 볼 수 있습니다. -* :file:`mysite/wsgi.py`: An entry-point for WSGI-compatible webservers to - serve your project. See :doc:`/howto/deployment/wsgi/index` for more details. +* :file:`mysite/wsgi.py`: 여러분의 프로젝트가 WSGI 호환 서버에서 서비스를 하기 위한 진입점 입니다. 자세한 사항은 :doc:`/howto/deployment/wsgi/index` 에서 확인 하세요. .. _more about packages: http://docs.python.org/tutorial/modules.html#packages -The development server +개발 서버 ---------------------- -Let's verify this worked. Change into the outer :file:`mysite` directory, if -you haven't already, and run the command ``python manage.py runserver``. You'll -see the following output on the command line:: +동작 하는 지 확인해 봅시다. 만약 여러분의 현재 위치가 밖깥쪽의 :file:`mysite` 디렉토로 가 아닐경우 그 위치로 이동합니다, 그리고 ``python manage.py runserver`` 명령어를 실행합니다. 이제 여러분은 명령행에서 다음과 같이 출력 되는 것을 볼 수 있을 것입니다:: Validating models... 0 errors found. @@ -141,178 +115,124 @@ see the following output on the command line:: Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. -You've started the Django development server, a lightweight Web server written -purely in Python. We've included this with Django so you can develop things -rapidly, without having to deal with configuring a production server -- such as -Apache -- until you're ready for production. +이제 여러분은 Django 개발 서버를 시작 했습니다. 이것은 경량 웹 서버로서 순수하게 파이썬으로 제작되었습니다. 우리는 여러분이 프로덕션 서버 -- Apache와 같은 -- 를 구축하지 않고 +서버가 준비되기 전까지 뭔가를 빨리 개발 할 수 있도록 이것을 Django에 포함 시켰습니다. -Now's a good time to note: DON'T use this server in anything resembling a -production environment. It's intended only for use while developing. (We're in -the business of making Web frameworks, not Web servers.) +중요사항!: 절때! 서비스 서버환경으로 사용하지 마십시오. 이 서버는 오직 개발하는 동안만 사용 하도록 계획된 것입니다. (우리의 목적은 웹 프레임워크를 만드는 것이지 웹서버를 만드는 것이 아닙니다.) -Now that the server's running, visit http://127.0.0.1:8000/ with your Web -browser. You'll see a "Welcome to Django" page, in pleasant, light-blue pastel. -It worked! +서버 동작을 확인 하기 위해서 웹 브라우저에서 http://127.0.0.1:8000/를 방문해 보세요. 여러분은 유쾌하고 라이트 블루 파스텔톤의 "Welcome to Django" 페이지를 볼 수 있을 것입니다. +성공! -.. admonition:: Changing the port +.. admonition:: 포트 변경하기 - By default, the :djadmin:`runserver` command starts the development server - on the internal IP at port 8000. + 기본적으로, :djadmin:`runserver` 명령어로 개발 서버를 시작 할 경우 내부IP에 8000번 포트를 사용합니다. - If you want to change the server's port, pass - it as a command-line argument. For instance, this command starts the server - on port 8080: + 여러분이 서버의 포토를 변경하기를 원한다면, 명령행에 인자를 사용 할 수 있습니다. 예를 들아 다음 명령어는 + 8080포트로 변경합니다: .. code-block:: bash python manage.py runserver 8080 - If you want to change the server's IP, pass it along with the port. So to - listen on all public IPs (useful if you want to show off your work on other - computers), use: + 여러분이 서버 아이피도 변경하길 원한다면 포트와 함께 전달 하면 됩니다. 그렇게 하면 모든 공용 IP에서 수신을 대기 할 수 있습니다.(여러분이 다른 컴퓨터에서 여러분의 사이트를 보여주길 원한다면 + 유용합니다), 사용법: .. code-block:: bash python manage.py runserver 0.0.0.0:8000 - Full docs for the development server can be found in the - :djadmin:`runserver` reference. + 개발 서버에 관한해서는 :djadmin:`runserver`에서 찾으실 수 있습니다. -Database setup +데이터베이스 설치 -------------- -Now, edit :file:`mysite/settings.py`. It's a normal Python module with -module-level variables representing Django settings. Change the -following keys in the :setting:`DATABASES` ``'default'`` item to match -your database connection settings. +이제, :file:`mysite/settings.py`파일을 수정해 봅시다. 이 파일은 Django 설정을 하는 모듈 수준의 변수를 가진 파이선의 표준 모듈입니다. 여러분의 데이터 베이스와 맞도록 :setting:`DATABASES` ``'default'`` 키를 수정 하세요. -* :setting:`ENGINE ` -- Either +* :setting:`ENGINE ` -- ``'django.db.backends.postgresql_psycopg2'``, - ``'django.db.backends.mysql'``, ``'django.db.backends.sqlite3'`` or - ``'django.db.backends.oracle'``. Other backends are :setting:`also available - `. + ``'django.db.backends.mysql'``, ``'django.db.backends.sqlite3'`` 또는 + ``'django.db.backends.oracle'``중 선택하세요. 다른 백엔드 또한 준비 되어 있습니다.( :setting:`also available `). -* :setting:`NAME` -- The name of your database. If you're using - SQLite, the database will be a file on your computer; in that - case, :setting:`NAME` should be the full absolute path, - including filename, of that file. If the file doesn't exist, it - will automatically be created when you synchronize the database - for the first time (see below). +* :setting:`NAME` -- 여러분의 데이터 베이스 이름 입니다. 만약 여러분이 SQLite를 사용한다면, 데이터베이스가 여러분의 컴퓨터에 있는 파일이 될 것입니다; + 그 경우, :setting:`NAME` 은 파일 명을 포함하는 절대 경로 가됩니다(full path). 만약 파일이 존재하지 않는다면, 여러분이 데이터베이스를 최초 싱크 할 때 자동으로 만들어 질 것입니다.(하단 참조). - When specifying the path, always use forward slashes, even on - Windows (e.g. ``C:/homes/user/mysite/sqlite3.db``). + 경로를 지정 할 경우 항상 슬래쉬 기호(/) 를 사용 해야 합니다. + 윈도우 에서도 말이죠(e.g. ``C:/homes/user/mysite/sqlite3.db``). -* :setting:`USER` -- Your database username (not used for SQLite). +* :setting:`USER` -- 데이터베이스 사용자이름(SQLite 에서는 사용하지 않습니다). -* :setting:`PASSWORD` -- Your database password (not used for - SQLite). +* :setting:`PASSWORD` -- 데이터베이스 암호(SQLite 에서는 사용하지 않습니다). -* :setting:`HOST` -- The host your database is on. Leave this as - an empty string if your database server is on the same physical - machine (not used for SQLite). +* :setting:`HOST` -- 데이터베이스가 있는 호스트데이터 베이스가 동일한 물리적 장치에 있다면 비어있는 문자열을 사용합니다. (SQLite 에서는 사용하지 않습니다). -If you're new to databases, we recommend simply using SQLite by setting -:setting:`ENGINE` to ``'django.db.backends.sqlite3'`` and :setting:`NAME` to -the place where you'd like to store the database. SQLite is included as part -of Python 2.5 and later, so you won't need to install anything else to support -your database. +만약 여러분이 새로운 데이터 베이스를 사용 하길 원하신다면, 쉽게 사용 가능 한 SQLite를 추천합니다. :setting:`ENGINE`에 ``'django.db.backends.sqlite3'`` 를 입력하고 :setting:`NAME` 에 데이터베이스 파일이 저장 될 경로를 입력 하시면 됩니다. SQLite는 파이썬 2.5 이상부터 포함되어 있어서 여러분은 데이터베이스 지원을 위해서 아무것도 설치 할 필요가 없습니다. -.. note:: +.. 참고:: - If you're using PostgreSQL or MySQL, make sure you've created a database by - this point. Do that with "``CREATE DATABASE database_name;``" within your - database's interactive prompt. + 여러분이 PostgreSQL나 MySQL을 사용 한다면, 데이터베이스가 만들어져 있는지 확인 해야 합니다. 만일 데이터베이스가 생성되어 있지 않다면 데이터베이스에 접속 가능한 프롬프트에서 "``CREATE DATABASE database_name;``"명령어를 이용하여 데이터베이스를 만들들 수 있습니다. - If you're using SQLite, you don't need to create anything beforehand - the - database file will be created automatically when it is needed. + 여러분이 SQLite을 사용 하신다면, 여러분은 아무것도 만들 필요가 없습니다 - 데이터베이스 파일이 필요 할 때 자동으로 생성됩니다. -While you're editing :file:`settings.py`, set :setting:`TIME_ZONE` to your -time zone. The default value is the Central time zone in the U.S. (Chicago). +여러분이 :file:`settings.py`을 수정 할 때, :setting:`TIME_ZONE` 을 여러분의 타임존에 맞게 수정하세요. 기본값은 미국 중부 시간입니다(시카고). -Also, note the :setting:`INSTALLED_APPS` setting toward the bottom of -the file. That holds the names of all Django applications that are -activated in this Django instance. Apps can be used in multiple projects, and -you can package and distribute them for use by others in their projects. +또한, 파일 제일 아래쪽에 있는 :setting:`INSTALLED_APPS` 을 확인하세요. 여기에는 Django 인스턴스에서 사용하는 모든 애플리케이션의 이름을 갖고 있습니다. 앱은 여러 프로젝트에서 사용 할 수 있고, 여러분은 다른 프로젝트에서 사용 가능하도록 패키지 하여 재 배포를 할 수 있습니다. -By default, :setting:`INSTALLED_APPS` contains the following apps, all of which -come with Django: +기본적으로, :setting:`INSTALLED_APPS` Djanog 프로젝트 생성시 다음과 같은 앱을 포함하고 있습니다: -* :mod:`django.contrib.auth` -- An authentication system. +* :mod:`django.contrib.auth` -- 인증시스템 -* :mod:`django.contrib.contenttypes` -- A framework for content types. +* :mod:`django.contrib.contenttypes` -- 컨텐츠타입 프레임워크. -* :mod:`django.contrib.sessions` -- A session framework. +* :mod:`django.contrib.sessions` -- 세션프레임워크 -* :mod:`django.contrib.sites` -- A framework for managing multiple sites - with one Django installation. +* :mod:`django.contrib.sites` -- 한번의 Django설치로 여러 사이트 관리를 위한 프레임워크. -* :mod:`django.contrib.messages` -- A messaging framework. +* :mod:`django.contrib.messages` -- 메시징 프레임워크 -* :mod:`django.contrib.staticfiles` -- A framework for managing - static files. +* :mod:`django.contrib.staticfiles` -- 정적파일을 관리하기 위한 프레임워크. -These applications are included by default as a convenience for the common case. +이 애플리케이션들은 기본적으로 Django사용에 있어 일반적인 케이스에 대한 편의를 제공하기 위해 포함되어 있습니다. -Each of these applications makes use of at least one database table, though, -so we need to create the tables in the database before we can use them. To do -that, run the following command: +각각의 애플리케이션은 적어도 하나의 데이터베이스 테이블을 사용하기 때문에 우리는 데이터베이스 테이블이 사용되기 전에 테이블을 만들어야 합니다. 그렇게 하려면 다음 명령어를 실행하세요: .. code-block:: bash python manage.py syncdb -The :djadmin:`syncdb` command looks at the :setting:`INSTALLED_APPS` setting and -creates any necessary database tables according to the database settings in your -:file:`settings.py` file. You'll see a message for each database table it -creates, and you'll get a prompt asking you if you'd like to create a superuser -account for the authentication system. Go ahead and do that. +:djadmin:`syncdb` 명령어는 :file:`settings.py` 파일에 있는 데이터베이스 설정에 따라 :setting:`INSTALLED_APPS` 에서 설정 되어 있는 앱을 확인하고 필요한 데이터베이스 테이블을 만듭니다. 여러분들은 각 데이터베이스 테이블이 생성 되는 메시지를 볼 수 있고, 인증시스템에서 여러분에게 관리자 계정 정보를 입력 하는 명령 프롬프트를 보여 줄 것입니다. 여기에서 관리자 계정 정보를 만들면 됩니다. -If you're interested, run the command-line client for your database and type -``\dt`` (PostgreSQL), ``SHOW TABLES;`` (MySQL), or ``.schema`` (SQLite) to -display the tables Django created. +만약 Django에서 생성한 데이터베이스의 테이블 목록을 보고 싶다면, 해당 데이터베이스에 접속 할 수 있는 클라이언트에서 다음 명령어중 해당 데이터베이스에 맞는 명령어를 입력하세요.(``\dt`` (PostgreSQL), ``SHOW TABLES;`` (MySQL), ``.schema`` (SQLite)). -.. admonition:: For the minimalists +.. admonition:: 미니멀리즘을 위해 - Like we said above, the default applications are included for the common - case, but not everybody needs them. If you don't need any or all of them, - feel free to comment-out or delete the appropriate line(s) from - :setting:`INSTALLED_APPS` before running :djadmin:`syncdb`. The - :djadmin:`syncdb` command will only create tables for apps in - :setting:`INSTALLED_APPS`. + 위에서 말했듯이, 기본 응용프로그램은 일반적인 케이스에 포함하지만, 모든사람이 다 필요로 하지 않습니다. 만약 여러분이 일부 또는 전부가 필요없다면, + :djadmin:`syncdb`명령은 오직 :setting:`INSTALLED_APPS` 안에 설정된 앱에 대해서만 테이블을 생성 하기때문에 + :djadmin:`syncdb`를 실행 하기 전에 자유롭게 :setting:`INSTALLED_APPS` 에서 주석 처리를 하거나 삭제 할 수 있습니다. .. _creating-models: -Creating models +모델 만들기 =============== -Now that your environment -- a "project" -- is set up, you're set to start -doing work. +이제 여러분들은 환경설정 --"프로젝트"-- 을 완료 하였습니다. 이제 작업을 시작 할 수 있습니다. -Each application you write in Django consists of a Python package, somewhere -on your `Python path`_, that follows a certain convention. Django comes with a -utility that automatically generates the basic directory structure of an app, -so you can focus on writing code rather than creating directories. +여러분이 작성한 각 어플리케이션은 Django에서 파이썬 패키지로 구성 되어 특정 규칙에 따라, `Python path`_ 어딘가에 존재합니다. Django는 자동으로 기본적인 디렉토리 구조를 생서하는 유틸리트를 포함하고 있어서,여러분은 디렉토리 구조를 생성 하는 것 보다 코드를 작성하는 것에 초점을 맞출 수 있게 해줍니다. -.. admonition:: Projects vs. apps +.. admonition:: 프로젝트 vs. 앱 - What's the difference between a project and an app? An app is a Web - application that does something -- e.g., a Weblog system, a database of - public records or a simple poll app. A project is a collection of - configuration and apps for a particular Web site. A project can contain - multiple apps. An app can be in multiple projects. + 프로젝트와 앱은 무엇이 다를까요?앱은 웹 어플리케이션의 기능입니다 -- e.g., 웹 블로그시스템,공공 기록의 데이터베이스 또는 간단한 투표 앱. + 프로젝트는 웹사이트에 대한 구성 및 특정 앱들의 집합입니다. 프로젝트는 다양한 앱을 포함하고 있습니다. + 앱은 다양한 프로젝트에서 사용 할 수 있습니다. -Your apps can live anywhere on your `Python path`_. In this tutorial, we'll -create our poll app right next to your :file:`manage.py` file so that it can be -imported as its own top-level module, rather than a submodule of ``mysite``. +여러분의 앱은 `Python path`_ 어딘가에 있습니다. 이 자습서에서 우리는 :file:`manage.py` 을 이용하여 투표앱을 만들 것입니다. 이것은 ``mysite``의 서브모듈보다도 더 중요한 모듈입니다. -To create your app, make sure you're in the same directory as :file:`manage.py` -and type this command: +여러분이 앱을 만들기 위해서는 :file:`manage.py`와 같은 디렉토리에서 다음과 같은 명령어를 입력 합니다: .. code-block:: bash python manage.py startapp polls -That'll create a directory :file:`polls`, which is laid out like this:: +이 명령어는 다음과 같은 구조를 갖는 :file:`polls`디렉토리를 만들 것입니다:: polls/ __init__.py @@ -320,24 +240,19 @@ That'll create a directory :file:`polls`, which is laid out like this:: tests.py views.py -This directory structure will house the poll application. +이 디렉토리 구조는 투표 어플리케이션을 수용 할 수 있습니다. -The first step in writing a database Web app in Django is to define your models --- essentially, your database layout, with additional metadata. +Django에서 데이터베이스 웹 앱 작성의 첫 단계는 데이터베이스 모델을 정의하는 것입니다. +-- 본질적으로 추가적인 메타데이터와 데이터베이스 레이아웃을 정의하는 작업입니다. -.. admonition:: Philosophy +.. admonition:: 철학 - A model is the single, definitive source of data about your data. It contains - the essential fields and behaviors of the data you're storing. Django follows - the :ref:`DRY Principle `. The goal is to define your data model in one - place and automatically derive things from it. + 모델은 여러분의 데이터에 대한 최종적인 소스입니다. 이것은 여러분의 데이터에 대한 기본적인 필드와 행동이 포함되어 있습니다. Django는 :ref:`DRY ` 원칙을 따릅니다. 이것의 목표는 여러분의 모델을 + 한 곳에서 정의하고 자동으로 결과를 생성해 내는 것입니다. -In our simple poll app, we'll create two models: polls and choices. A poll has -a question and a publication date. A choice has two fields: the text of the -choice and a vote tally. Each choice is associated with a poll. +우리의 간단한 투표 앱에서는 두개의 모델을 만들 것입니다: polls 그리고 choices. poll은 '질문'과 '발행일' 필드를 갖고 있습니다. choice는 두개의 필드를 갖고 있습니다: '선택지'와 '투표 집계'각 선택은 poll과 관련이 있습니다. -These concepts are represented by simple Python classes. Edit the -:file:`polls/models.py` file so it looks like this:: +이것의 개념은 간단한 파이썬 클래스로 표현이 됩니다. :file:`polls/models.py` 을 다음과 같이 수정하세요:: from django.db import models @@ -350,59 +265,39 @@ These concepts are represented by simple Python classes. Edit the choice = models.CharField(max_length=200) votes = models.IntegerField() -The code is straightforward. Each model is represented by a class that -subclasses :class:`django.db.models.Model`. Each model has a number of class -variables, each of which represents a database field in the model. - -Each field is represented by an instance of a :class:`~django.db.models.Field` -class -- e.g., :class:`~django.db.models.CharField` for character fields and -:class:`~django.db.models.DateTimeField` for datetimes. This tells Django what -type of data each field holds. - -The name of each :class:`~django.db.models.Field` instance (e.g. ``question`` or -``pub_date`` ) is the field's name, in machine-friendly format. You'll use this -value in your Python code, and your database will use it as the column name. - -You can use an optional first positional argument to a -:class:`~django.db.models.Field` to designate a human-readable name. That's used -in a couple of introspective parts of Django, and it doubles as documentation. -If this field isn't provided, Django will use the machine-readable name. In this -example, we've only defined a human-readable name for ``Poll.pub_date``. For all -other fields in this model, the field's machine-readable name will suffice as -its human-readable name. - -Some :class:`~django.db.models.Field` classes have required elements. -:class:`~django.db.models.CharField`, for example, requires that you give it a -:attr:`~django.db.models.Field.max_length`. That's used not only in the database -schema, but in validation, as we'll soon see. - -Finally, note a relationship is defined, using -:class:`~django.db.models.ForeignKey`. That tells Django each Choice is related -to a single Poll. Django supports all the common database relationships: -many-to-ones, many-to-manys and one-to-ones. +코드는 간단합니다. 각 모델은 :class:`django.db.models.Model`의 서브클래스로 표현됩니다. 각 모델은 몇개의 클래스 변수를 갖고 있고, 이것은 각각 데이터베이스 필드로 표현 됩니다. + +각 필드는 :class:`~django.db.models.Field` 클래스의 인스턴스로 표현됩니다. -- e.g., :class:`~django.db.models.CharField` 는 character 필드 그리고 :class:`~django.db.models.DateTimeField` 은 datetime 필드. 이것은 Django에게 데이터의 필드가 어떤 타입인지 알려줍니다. + +각 :class:`~django.db.models.Field` 인스턴스의 이름은(e.g. ``question`` 또는 ``pub_date`` )기계친화적인 필드이름 입니다. 여러분은 이것을 여러분의 파이썬 코드에서 사용하고, 데이터베이스는 필드 이름으로 사용합니다. + +여기에서 여러분은 선택적으로 :class:`~django.db.models.Field` 의 첫번째 인자를 사람이 읽을 수 있는 이름으로 지정 할 수 있습니다. 그것은 Django의 내부적으로 사용되고, 두가지로 설명 해 줍니다. +만약 이 필드를 제공하지 않는다면, Django는 기계가 읽을수 있는 이름만을 사용해야 합니다. 예제에서, 우리는 ``Poll.pub_date``에 대해서만 사람이 읽을 수 있는 이름을 정의 했습니다. 이 모델에서는 다른 모든 필드는 기계가 읽을 수 있는 이름도 충분히 사람이 읽을 수 있는 이름이기 때문입니다. + +일부 :class:`~django.db.models.Field` 클레스들은 필수 요소를 필요로 합니다. +예를 들어 :class:`~django.db.models.CharField`는 :attr:`~django.db.models.Field.max_length`를 필수로 필요합니다. 이것은 데이터베이스 스키마에서만 사용 하는 것이 아니라 데이터 검증에서도 사용 합니다. 우리는 그것을 곧 보게 될 것입니다. + +마지막으로, :class:`~django.db.models.ForeignKey`를 이용하여 릴레이션쉽을 정의 했습니다. 이것은 Choice가 하나의 Poll과 관계가 있다고 Django에게 알려줍니다. Django는 다음과 같은 공통의 데이터베이스 릴레이션쉽을 제공합니다: +many-to-ones, many-to-manys, one-to-ones. .. _`Python path`: http://docs.python.org/tutorial/modules.html#the-module-search-path -Activating models +모델 활성화 하기 ================= -That small bit of model code gives Django a lot of information. With it, Django -is able to: +이 작은 모델 코드는 Django에게 많은 정보를 전달합니다. 이것을 통해 Djanog는 다음과 같은 것을 할 수 있습니다.: -* Create a database schema (``CREATE TABLE`` statements) for this app. -* Create a Python database-access API for accessing Poll and Choice objects. +* 이 앱에서 필요로 하는 데이터베이스 스키마 생성 (``CREATE TABLE`` 문). +* Poll과 Choice객체에 접근 하기위한 데이터베이스 엑세스 API 생성. -But first we need to tell our project that the ``polls`` app is installed. +그 전에 우리는 우리의 프로젝트에게 ``polls`` 앱이 설치 되었다고 알려줘야 합니다. -.. admonition:: Philosophy +.. admonition:: 철학 - Django apps are "pluggable": You can use an app in multiple projects, and - you can distribute apps, because they don't have to be tied to a given - Django installation. + Django앱은 "플러그" 입니다: 여러분은 여러 프로젝트에서 앱을 사용 할 수 있으며, + 앱을 재배포 할 수 있습니다. 왜냐하면 앱들은 Django설치와 밀접하게 묶일 필요가 없기 때문입니다. -Edit the :file:`settings.py` file again, and change the -:setting:`INSTALLED_APPS` setting to include the string ``'polls'``. So -it'll look like this:: +:file:`settings.py` 파일에서 :setting:`INSTALLED_APPS` 에 ``'polls'``을 포함하도록 수정합니다. 그러면 다음과 같이 보일 것입니다:: INSTALLED_APPS = ( 'django.contrib.auth', @@ -418,15 +313,13 @@ it'll look like this:: 'polls', ) -Now Django knows to include the ``polls`` app. Let's run another -command: +이제 Django는 ``polls``앱이 포함되었다는 것을 알게 됩니다. 다음 명령어를 실행해 봅시다: .. code-block:: bash python manage.py sql polls -You should see something similar to the following (the ``CREATE TABLE`` SQL -statements for the polls app): +여러분은 다음과 비슷한 내용을 보실 수 있습니다.(투표 앱``CREATE TABLE`` SQL문): .. code-block:: sql @@ -444,99 +337,68 @@ statements for the polls app): ); COMMIT; -Note the following: +다음을 참고하세요: -* The exact output will vary depending on the database you are using. +* 정확한 출력은 사용중인 데이터베이스에 따라 달라집니다. -* Table names are automatically generated by combining the name of the app - (``polls``) and the lowercase name of the model -- ``poll`` and - ``choice``. (You can override this behavior.) +* 테이블 이름은 앱 이름(``polls``)과 소문자 모델이름 --``poll``, ``choice``과 합성되어 자동으로 생성됩니다.(여러분은 이동작을 재 정의 할 수 있습니다.) -* Primary keys (IDs) are added automatically. (You can override this, too.) +* Primary key는(IDs) 자동으로 추가됩니다. (여러분은 이것 또한 재정의 할 수 있습니다.) -* By convention, Django appends ``"_id"`` to the foreign key field name. - (Yes, you can override this, as well.) +* 관례상, Django는 외래키의 필드 이름에 ``"_id"`` 를 추가합니다.(맞습니다, 이것 또한 재정의가 가능합니다.) -* The foreign key relationship is made explicit by a ``REFERENCES`` - statement. +* 왜래키 릴레이션쉽은 ``REFERENCES`` 문으로 명시됩니다. -* It's tailored to the database you're using, so database-specific field - types such as ``auto_increment`` (MySQL), ``serial`` (PostgreSQL), or - ``integer primary key`` (SQLite) are handled for you automatically. Same - goes for quoting of field names -- e.g., using double quotes or single - quotes. The author of this tutorial runs PostgreSQL, so the example - output is in PostgreSQL syntax. +* 그것은 사용중인 데이터베이스에 맞게 ``auto_increment`` (MySQL), ``serial`` (PostgreSQL), ``integer primary key``(SQLite)등과 같이 필드 유형에 맞게 자동으로 사용됩니다. 같은 필드 이름의 인용을 위해 사용된다. -- e.g., 큰따옴표 또는 작은 따옴표. + 이 자습서의 저자는 PostgreSQL를 이용하여 실행 하였으므로, 예제의출력물 역시 PostgreSQL 문법에 따릅니다. -* The :djadmin:`sql` command doesn't actually run the SQL in your database - - it just prints it to the screen so that you can see what SQL Django thinks - is required. If you wanted to, you could copy and paste this SQL into your - database prompt. However, as we will see shortly, Django provides an - easier way of committing the SQL to the database. +* :djadmin:`sql` 명령어는 실제로 여러분의 데이터 베이스에 SQL문을 실행하지 않습니다. + 이것 단지 화면에 출력 해 주는 것입니다.이것은 여러분은 SQL Django 가 어떻게 생각하는지 알기 위해 필요합니다. 원한다면 이것을 복사하여 여러분의 데이터베이스 프롬프트에서 사용 할 수 있습니다. 그러나, 우리는 SQL을 Django에 맡겨버리는 쉬운 방법을 곧 보게 될 것입니다. -If you're interested, also run the following commands: +만약 여러분이 이것에 관심이 있다면 다음 명령어를 실행 하세요: -* :djadmin:`python manage.py validate ` -- Checks for any errors - in the construction of your models. +* :djadmin:`python manage.py validate ` -- 모델 구조에 오류가 있는지 확인 합니다. -* :djadmin:`python manage.py sqlcustom polls ` -- Outputs any - :ref:`custom SQL statements ` (such as table modifications or - constraints) that are defined for the application. +* :djadmin:`python manage.py sqlcustom polls ` -- 애플리케이션에 대한 :ref:`사용자 정의 SQL 문 ` (테이블 변경 또는 제약조건)을 출력합니다 -* :djadmin:`python manage.py sqlclear polls ` -- Outputs the - necessary ``DROP TABLE`` statements for this app, according to which - tables already exist in your database (if any). +* :djadmin:`python manage.py sqlclear polls ` -- 데이터베이스에 이미 테이블이 존재 하면 ``DROP TABLE`` 문을 출력합니다(있는경우). -* :djadmin:`python manage.py sqlindexes polls ` -- Outputs the - ``CREATE INDEX`` statements for this app. +* :djadmin:`python manage.py sqlindexes polls ` -- 이 앱에 해당하는 ``CREATE INDEX`` 문 출력. -* :djadmin:`python manage.py sqlall polls ` -- A combination of all - the SQL from the :djadmin:`sql`, :djadmin:`sqlcustom`, and - :djadmin:`sqlindexes` commands. +* :djadmin:`python manage.py sqlall polls ` -- :djadmin:`sql`, :djadmin:`sqlcustom`, :djadmin:`sqlindexes` 명령어의 모든 조합. -Looking at the output of those commands can help you understand what's actually -happening under the hood. +이러한 명령에 의해 출력된 내용을 살펴보면 여러분은 실제로 발생 할 내용에 대해 이해를 할 수 있을 것입니다. -Now, run :djadmin:`syncdb` again to create those model tables in your database: +이제, :djadmin:`syncdb` 를 다시 실행 하여 여러분의 데이터베이스에 모델 테이블을 만드세요: .. code-block:: bash python manage.py syncdb -The :djadmin:`syncdb` command runs the SQL from :djadmin:`sqlall` on your -database for all apps in :setting:`INSTALLED_APPS` that don't already exist in -your database. This creates all the tables, initial data and indexes for any -apps you've added to your project since the last time you ran syncdb. -:djadmin:`syncdb` can be called as often as you like, and it will only ever -create the tables that don't exist. +:djadmin:`syncdb` 명령은 :setting:`INSTALLED_APPS`있는 앱중 이미 데이터베이스에 존재하는 앱을 제외한 모든 앱에 대하여 :djadmin:`sqlall`를 실행 합니다. 이것은 여러분이 syncdb 명령을 마지막으로 실행한 이후에 일어난 모든 앱에 대한 테이블과 초기 데이터, 인덱스를 만듭니다. +:djadmin:`syncdb` 는 원할 때 마다 호출이 가능 하며, 이것은 오직 생성되지 않은 테이블에 대해서만 테이블을 생성합니다. -Read the :doc:`django-admin.py documentation ` for full -information on what the ``manage.py`` utility can do. + ``manage.py`` 유틸리티가 무엇을 할 수 있는지에 대한 정보는 :doc:`django-admin.py 문서 ` 를 읽어 보십시오. -Playing with the API +API와 놀기 ==================== -Now, let's hop into the interactive Python shell and play around with the free -API Django gives you. To invoke the Python shell, use this command: +이제, 대화식 파이썬 쉘을 이용하여 Django API를 갖고 놀 수 있습니다. 파이썬 쉘을 호출 하려면 다음 명령어를 입력하세요: .. code-block:: bash python manage.py shell -We're using this instead of simply typing "python", because :file:`manage.py` -sets the ``DJANGO_SETTINGS_MODULE`` environment variable, which gives Django -the Python import path to your :file:`settings.py` file. +:file:`manage.py` 파일 이 여러분의 :file:`settings.py`에서 Djanog에게 파이썬 가져오기 경로를 ``DJANGO_SETTINGS_MODULE`` 환경설정을 통해 제공 하기 때문에 우리는 단순히 "python"이라고 입력 하면 됩니다. -.. admonition:: Bypassing manage.py +.. admonition:: manage.py 건너뛰기 - If you'd rather not use :file:`manage.py`, no problem. Just set the - ``DJANGO_SETTINGS_MODULE`` environment variable to ``mysite.settings`` and - run ``python`` from the same directory :file:`manage.py` is in (or ensure - that directory is on the Python path, so that ``import mysite`` works). + 만약 :file:`manage.py`을 사용하지 않는다 해도 문제없습니다. 단지 ``mysite.settings`` 에 ``DJANGO_SETTINGS_MODULE`` 환경변수를 설정하고 + :file:`manage.py` 파일이 있는 같은 디렉토리에서 ``python``을 실행 하면됩니다. (또는 그 디렉토리가 파이썬 경로에 위치 하거나 ``import mysite`` 해야 사용 할 수 있습니다). - For more information on all of this, see the :doc:`django-admin.py - documentation `. + 더 많은 정보를 원단하면 :doc:`django-admin.py문서 `를 확인 하세요. -Once you're in the shell, explore the :doc:`database API `:: +일단 쉘에서 :doc:`database API `를 확인해 보세요:: >>> from polls.models import Poll, Choice # Import the model classes we just wrote. @@ -576,11 +438,7 @@ Once you're in the shell, explore the :doc:`database API `:: [] -Wait a minute. ```` is, utterly, an unhelpful representation -of this object. Let's fix that by editing the polls model (in the -``polls/models.py`` file) and adding a -:meth:`~django.db.models.Model.__unicode__` method to both ``Poll`` and -``Choice``:: +잠시만요. ````는 완전히 이 객체 자체를 표현 하지 객체의 내용을 표현 하지 않습니다. 우리는 polls 모델을 수정하여(``polls/models.py`` 파일) ``Poll`` 과``Choice``에 :meth:`~django.db.models.Model.__unicode__` 를 추가하여 원하는 내용을 표현 할 수 있습니다:: class Poll(models.Model): # ... @@ -592,33 +450,19 @@ of this object. Let's fix that by editing the polls model (in the def __unicode__(self): return self.choice -It's important to add :meth:`~django.db.models.Model.__unicode__` methods to -your models, not only for your own sanity when dealing with the interactive -prompt, but also because objects' representations are used throughout Django's -automatically-generated admin. +:meth:`~django.db.models.Model.__unicode__` 메소드를 추가 하는 것은 여러분의 모델에서 매우 중요합니다. 이것은 대화식 프롬프트에서 사용 할 때 뿐만 아니라,Django에서 자동 생성되는 관리자 화면에서 표현 할 때도 사용됩니다. -.. admonition:: Why :meth:`~django.db.models.Model.__unicode__` and not - :meth:`~django.db.models.Model.__str__`? +.. admonition:: 왜 :meth:`~django.db.models.Model.__unicode__` 은 되고 :meth:`~django.db.models.Model.__str__`은 안되나요? - If you're familiar with Python, you might be in the habit of adding - :meth:`~django.db.models.Model.__str__` methods to your classes, not - :meth:`~django.db.models.Model.__unicode__` methods. We use - :meth:`~django.db.models.Model.__unicode__` here because Django models deal - with Unicode by default. All data stored in your database is converted to - Unicode when it's returned. + 만약 여러분이 파이썬에 익숙한 경우,여러분은 :meth:`~django.db.models.Model.__unicode__` 메소드 대신 :meth:`~django.db.models.Model.__str__`를 추가하는 습관이 있을 수 있습니다. 우리가 + :meth:`~django.db.models.Model.__unicode__` 을 사용 하는 이유는 Django 모델에서는 기본적으로 유니코드를 사용하기로 약속 했기 때문입니다. 데이터가 반환될때 여러분의 데이터베이스에 있는 모든데이터는 + 유니코드로 변환되어 반환됩니다. - Django models have a default :meth:`~django.db.models.Model.__str__` method - that calls :meth:`~django.db.models.Model.__unicode__` and converts the - result to a UTF-8 bytestring. This means that ``unicode(p)`` will return a - Unicode string, and ``str(p)`` will return a normal string, with characters - encoded as UTF-8. + Django 모델은 기본적으로 :meth:`~django.db.models.Model.__str__` 메소드는 :meth:`~django.db.models.Model.__unicode__` 를 호출한 결과를 UTF-8 바이트 스트링으로 변환하여 보여줍니다. 이 말은 ``unicode(p)``는 유니코드 문자열을, ``str(p)`` 은 UTF-8로 변환된 기본 문자열을 반환 한다는 뜻 입니다. - If all of this is gibberish to you, just remember to add - :meth:`~django.db.models.Model.__unicode__` methods to your models. With any - luck, things should Just Work for you. + 이 모든것이 혼란스럽다면 모델에서 :meth:`~django.db.models.Model.__unicode__` 메소드만 사용 한 다는 것을 기억하세요. 운이 좋다면, 이 모든 것은 잘 동작 할 것입니다. -Note these are normal Python methods. Let's add a custom method, just for -demonstration:: +다음은 일반적인 파이썬 방법입니다. 데모를 위해 여기에 사용자 정의 메소드를 추가하세요.:: import datetime from django.utils import timezone @@ -628,14 +472,9 @@ demonstration:: def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) -Note the addition of ``import datetime`` and ``from django.utils import -timezone``, to reference Python's standard :mod:`datetime` module and Django's -time-zone-related utilities in :mod:`django.utils.timezone`, respectively. If -you aren't familiar with time zone handling in Python, you can learn more in -the :doc:`time zone support docs `. +참고로 추가한 ``import datetime``과 ``from django.utils import timezone``은 각각 파이썬의 표준 메소드인 :mod:`datetime` 과 Django의 time-zone-related 유틸리테에 들어있는 :mod:`django.utils.timezone`을 참조하세요. 여러분이 파이썬 시간 처리에 대해 익수하지 않은경우, 여러분은 :doc:`time zone support docs `에서 배울 수 있습니다. -Save these changes and start a new Python interactive shell by running -``python manage.py shell`` again:: +저장 후 ``python manage.py shell`` 이용하여 새로운 파이썬 대화형 쉘을 실행하세요:: >>> from polls.models import Poll, Choice @@ -709,11 +548,6 @@ Save these changes and start a new Python interactive shell by running >>> c = p.choice_set.filter(choice__startswith='Just hacking') >>> c.delete() -For more information on model relations, see :doc:`Accessing related objects -`. For more on how to use double underscores to perform -field lookups via the API, see :ref:`Field lookups `. For -full details on the database API, see our :doc:`Database API reference -`. +모델관계에 대한 자세한 사항은 :doc:`Accessing related objects `을 확인 하세요. API에서 이중밑줄(__)을 어떻게 사용 하는지에 대한 자세한 사항은 :ref:`Field lookups `에서 확인하세요. 데이터베이스 API에대한 자세한 사항은 :doc:`Database API reference `에서 확인하세요. -When you're comfortable with the API, read :doc:`part 2 of this tutorial -` to get Django's automatic admin working. \ No newline at end of file +이제 여러분이 API를 익숙하게 사용 하신다면, :doc:`part 2 of this tutorial `로 가서 Django에서 자동으로 생성되는 관리자에 대하여 확인하세요. From edcdd38a290da23b362ff37e96f653463e325623 Mon Sep 17 00:00:00 2001 From: Yong Choi Date: Sun, 19 Aug 2012 04:03:53 +0900 Subject: [PATCH 037/128] Update intro/tutorial01.txt --- intro/tutorial01.txt | 106 +++++++++++++++++++++++-------------------- 1 file changed, 58 insertions(+), 48 deletions(-) diff --git a/intro/tutorial01.txt b/intro/tutorial01.txt index 8a71a19..887708f 100644 --- a/intro/tutorial01.txt +++ b/intro/tutorial01.txt @@ -1,5 +1,5 @@ -===================================== -첫번째 장고 앱 만들기! part1 +===================================== +첫 번째 Django 앱 만들기! part1 ===================================== 예제로 배워봅시다. @@ -11,12 +11,12 @@ * 공개된 사이트는 사람들이 투표내용을 볼 수 있으며 투표에에 참여 할 수 있습니다. * 관리자 사이트는 당신(관리자)이 설문조사에 대하여 추가, 수정, 삭제를 할 수 있습니다. -우리는 여러분이 이미 :doc:`Django 설치`를 완료 하였다고 가정하에 진행 하도록 하겠습니다. 여러분은 파이썬 인터프리터를 실행하여 ``import django``를 입력해 봄으로써 Django가 설치 되어 있는지 확인 할 수 있습니다. 만약 에러없이 실행된다면, Django 설치가 완료된 것입니다. +우리는 여러분이 이미 :doc:`Django 설치`\ 를 완료 하였다고 가정하에 진행 하도록 하겠습니다. 여러분은 파이썬 인터프리터를 실행하여 ``import django``\ 를 입력해 봄으로써 Django가 설치되어 있는지 확인할 수 있습니다. 만약 에러 없이 실행된다면, Django 설치가 완료된 것입니다. .. admonition:: 도움말은 어디서 얻을 수 있나요?: 만약 여러분이 이 자습서를 따라하는 도중 문제가 발생 할 경우 - `django-users`__ 로 메시지를 보내 주시거나 또는 `#django on irc.freenode.net`__ 에서 + `django-users`__\ 로 메시지를 보내 주시거나 또는 `#django on irc.freenode.net`__\ 에서 당신에게 도움을 줄 다른 Django 사용자와 채팅을 할 수 있습니다. __ http://groups.google.com/group/django-users @@ -25,7 +25,7 @@ __ irc://irc.freenode.net/django 프로젝트 만들기 ================== -만약 여러분이 처음으로 Django를 사용 하는 것이라면, 여러분은 몇가지 초기 설정에 신경 써야 합니다. 즉, 여러분은 Django :term:`project` 를 구축하는데 몇가지 자동 생성되는 코드를 필요로 합니다 -- Django의 인스턴스를 위한 세팅들(데이터베이스 설정을 포함), Django의 특별한 옵션과 애플리캐이션의 특별한 설정들. +만약 여러분이 처음으로 Django를 사용 하는 것이라면, 여러분은 몇가지 초기 설정에 신경 써야 합니다. 즉, 여러분은 Django :term:`project` 를 구축하는데 몇가지 자동 생성되는 코드를 필요로 합니다 -- Django의 인스턴스를 위한 세팅들(데이터베이스 설정을 포함), Django의 특별한 옵션과 애플리케이션의 특별한 설정들. 명령행에서 , ``cd`` 디렉토리 (코드가 생성될 디렉토리)로 디렉토리 이동 후 다음 명령어 실행: @@ -44,10 +44,10 @@ __ irc://irc.freenode.net/django .. admonition:: Mac OS X 권한 - 만약 여러분이 Mac OS X를 사용 하신다면, 여러분은 ``django-admin.py startproject``를 실행 할 때 + 만약 여러분이 Mac OS X를 사용 하신다면, 여러분은 ``django-admin.py startproject``\ 를 실행할 때 "permission denied" 메시지를 볼 수 있을 것입니다. OS X와 같은 유닉스 기반 시스템은, 프로그램을 실행하기 전에 해당 파일에 "executable(실행)" - 표시를 해줘야 하기 때문입니다. 실생 표시를 하기 위해서는, 터미널 앱을 열고 - :doc:`django-admin.py` 가 설치되어 있는 디렉토리로 이동합니다. (``cd``명령을 사용) + 표시를 해줘야 하기 때문입니다. 실행 표시를 하기 위해서는, 터미널 앱을 열고 + :doc:`django-admin.py`\ 가 설치되어 있는 디렉토리로 이동합니다. (``cd``명령을 사용) 그리고 ``sudo chmod +x django-admin.py`` 명령어를 실행합니다. .. 참고:: @@ -57,11 +57,11 @@ __ irc://irc.freenode.net/django :doc:`django-admin.py `는 여러분이 Django를 ``python setup.py`` 명령으로 설치를 하였다면 여러분의 시스템 경로에 존재 할 것입니다. 만약 찾을 수 없다면 여러분은 ``site-packages/django/bin`` 여기에서 찾을 수 있을 것 이고, ``site-packages`` 는 파이썬의 설치 경로입니다. -불편하다면 :doc:`django-admin.py ` 을 :file:`/usr/local/bin`로 심볼릭링크를 걸어 둘 것을 고려 해 볼 수 있습니다. +불편하다면 :doc:`django-admin.py ` 을 :file:`/usr/local/bin`\ 로 심볼릭링크를 걸어두는 것을 고려해 볼 수 있습니다. .. admonition:: 어디에서 이 코드가 실행 되나요? - 만약 여러분이 PHP개발 자라면, 아마도 여러분은 웹 서버의 document root 디렉토리(``/var/www``과 비슷한)에 코드를 Django와 같이 올리려 할 것 입니다. + 만약 여러분이 PHP개발 자라면, 아마도 여러분은 웹 서버의 document root 디렉토리(``/var/www``\ 과 비슷한)에 코드를 Django와 같이 올리려 할 것 입니다. 하지만 파이썬 코드를 웹 서버와 같이 올려 두는 것은 위험에 노출 될 가능 성이 있기 때문에 그렇게 하지 않는 편이 좋습니다. 많은 사람들은 웹을 통하여 여러분의 코드를 볼 수 있고, 그럴 경우 보안상 좋지 않습니다. @@ -97,7 +97,7 @@ __ irc://irc.freenode.net/django * :file:`mysite/settings.py`: Django에서 필요한 설정 및 구성을 하는 파일 입니다. :doc:`/topics/settings` 문서에서 여러분의 Django설정을 어떻게 해야 하는지 알려 줄 것입니다. -* :file:`mysite/urls.py`: Django 프로젝트에서 URL을 설정 합니다; Django site의 "목차(사이트 맵)"입니다. 여러분들은 :doc:`/topics/http/urls`에서 URL에 관한 더 많은 정보를 읽어 볼 수 있습니다. +* :file:`mysite/urls.py`: Django 프로젝트에서 URL을 설정 합니다; Django site의 "목차(사이트 맵)"입니다. 여러분들은 :doc:`/topics/http/urls`\ 에서 URL에 관한 더 많은 정보를 읽어 볼 수 있습니다. * :file:`mysite/wsgi.py`: 여러분의 프로젝트가 WSGI 호환 서버에서 서비스를 하기 위한 진입점 입니다. 자세한 사항은 :doc:`/howto/deployment/wsgi/index` 에서 확인 하세요. @@ -106,7 +106,7 @@ __ irc://irc.freenode.net/django 개발 서버 ---------------------- -동작 하는 지 확인해 봅시다. 만약 여러분의 현재 위치가 밖깥쪽의 :file:`mysite` 디렉토로 가 아닐경우 그 위치로 이동합니다, 그리고 ``python manage.py runserver`` 명령어를 실행합니다. 이제 여러분은 명령행에서 다음과 같이 출력 되는 것을 볼 수 있을 것입니다:: +동작하는지 확인해 봅시다. 만약 여러분의 현재 위치가 밖깥쪽의 :file:`mysite` 디렉토리가 아닐경우 그 위치로 이동합니다, 그리고 ``python manage.py runserver`` 명령어를 실행합니다. 이제 여러분은 명령행에서 다음과 같이 출력 되는 것을 볼 수 있을 것입니다:: Validating models... 0 errors found. @@ -118,7 +118,7 @@ __ irc://irc.freenode.net/django 이제 여러분은 Django 개발 서버를 시작 했습니다. 이것은 경량 웹 서버로서 순수하게 파이썬으로 제작되었습니다. 우리는 여러분이 프로덕션 서버 -- Apache와 같은 -- 를 구축하지 않고 서버가 준비되기 전까지 뭔가를 빨리 개발 할 수 있도록 이것을 Django에 포함 시켰습니다. -중요사항!: 절때! 서비스 서버환경으로 사용하지 마십시오. 이 서버는 오직 개발하는 동안만 사용 하도록 계획된 것입니다. (우리의 목적은 웹 프레임워크를 만드는 것이지 웹서버를 만드는 것이 아닙니다.) +중요사항: 절대 서비스 서버환경으로 사용하지 마십시오. 이 서버는 오직 개발하는 동안만 사용 하도록 계획된 것입니다. (우리의 목적은 웹 프레임워크를 만드는 것이지 웹서버를 만드는 것이 아닙니다.) 서버 동작을 확인 하기 위해서 웹 브라우저에서 http://127.0.0.1:8000/를 방문해 보세요. 여러분은 유쾌하고 라이트 블루 파스텔톤의 "Welcome to Django" 페이지를 볼 수 있을 것입니다. 성공! @@ -141,17 +141,17 @@ __ irc://irc.freenode.net/django python manage.py runserver 0.0.0.0:8000 - 개발 서버에 관한해서는 :djadmin:`runserver`에서 찾으실 수 있습니다. + 개발 서버에 관해서는 :djadmin:`runserver`\ 에서 찾으실 수 있습니다. 데이터베이스 설치 -------------- -이제, :file:`mysite/settings.py`파일을 수정해 봅시다. 이 파일은 Django 설정을 하는 모듈 수준의 변수를 가진 파이선의 표준 모듈입니다. 여러분의 데이터 베이스와 맞도록 :setting:`DATABASES` ``'default'`` 키를 수정 하세요. +이제, :file:`mysite/settings.py` 파일을 수정해 봅시다. 이 파일은 Django 설정을 하는 모듈 수준의 변수를 가진 파이선의 표준 모듈입니다. 여러분의 데이터 베이스와 맞도록 :setting:`DATABASES` ``'default'`` 키를 수정 하세요. * :setting:`ENGINE ` -- ``'django.db.backends.postgresql_psycopg2'``, ``'django.db.backends.mysql'``, ``'django.db.backends.sqlite3'`` 또는 - ``'django.db.backends.oracle'``중 선택하세요. 다른 백엔드 또한 준비 되어 있습니다.( :setting:`also available `). + ``'django.db.backends.oracle'`` 중 선택하세요. 다른 백엔드 또한 준비 되어 있습니다.( :setting:`also available `). * :setting:`NAME` -- 여러분의 데이터 베이스 이름 입니다. 만약 여러분이 SQLite를 사용한다면, 데이터베이스가 여러분의 컴퓨터에 있는 파일이 될 것입니다; 그 경우, :setting:`NAME` 은 파일 명을 포함하는 절대 경로 가됩니다(full path). 만약 파일이 존재하지 않는다면, 여러분이 데이터베이스를 최초 싱크 할 때 자동으로 만들어 질 것입니다.(하단 참조). @@ -173,9 +173,9 @@ __ irc://irc.freenode.net/django 여러분이 SQLite을 사용 하신다면, 여러분은 아무것도 만들 필요가 없습니다 - 데이터베이스 파일이 필요 할 때 자동으로 생성됩니다. -여러분이 :file:`settings.py`을 수정 할 때, :setting:`TIME_ZONE` 을 여러분의 타임존에 맞게 수정하세요. 기본값은 미국 중부 시간입니다(시카고). +여러분이 :file:`settings.py`\ 을 수정 할 때, :setting:`TIME_ZONE`\ 을 여러분의 타임존에 맞게 수정하세요. 기본값은 미국 중부 시간입니다(시카고). -또한, 파일 제일 아래쪽에 있는 :setting:`INSTALLED_APPS` 을 확인하세요. 여기에는 Django 인스턴스에서 사용하는 모든 애플리케이션의 이름을 갖고 있습니다. 앱은 여러 프로젝트에서 사용 할 수 있고, 여러분은 다른 프로젝트에서 사용 가능하도록 패키지 하여 재 배포를 할 수 있습니다. +또한, 파일 제일 아래쪽에 있는 :setting:`INSTALLED_APPS`\ 을 확인하세요. 여기에는 Django 인스턴스에서 사용하는 모든 애플리케이션의 이름을 갖고 있습니다. 앱은 여러 프로젝트에서 사용 할 수 있고, 여러분은 다른 프로젝트에서 사용 가능하도록 패키지 하여 재 배포를 할 수 있습니다. 기본적으로, :setting:`INSTALLED_APPS` Djanog 프로젝트 생성시 다음과 같은 앱을 포함하고 있습니다: @@ -206,8 +206,8 @@ __ irc://irc.freenode.net/django .. admonition:: 미니멀리즘을 위해 위에서 말했듯이, 기본 응용프로그램은 일반적인 케이스에 포함하지만, 모든사람이 다 필요로 하지 않습니다. 만약 여러분이 일부 또는 전부가 필요없다면, - :djadmin:`syncdb`명령은 오직 :setting:`INSTALLED_APPS` 안에 설정된 앱에 대해서만 테이블을 생성 하기때문에 - :djadmin:`syncdb`를 실행 하기 전에 자유롭게 :setting:`INSTALLED_APPS` 에서 주석 처리를 하거나 삭제 할 수 있습니다. + :djadmin:`syncdb` 명령은 오직 :setting:`INSTALLED_APPS` 안에 설정된 앱에 대해서만 테이블을 생성 하기때문에 + :djadmin:`syncdb`를 실행 하기 전에 자유롭게 :setting:`INSTALLED_APPS`\ 에서 주석 처리를 하거나 삭제 할 수 있습니다. .. _creating-models: @@ -224,15 +224,15 @@ __ irc://irc.freenode.net/django 프로젝트는 웹사이트에 대한 구성 및 특정 앱들의 집합입니다. 프로젝트는 다양한 앱을 포함하고 있습니다. 앱은 다양한 프로젝트에서 사용 할 수 있습니다. -여러분의 앱은 `Python path`_ 어딘가에 있습니다. 이 자습서에서 우리는 :file:`manage.py` 을 이용하여 투표앱을 만들 것입니다. 이것은 ``mysite``의 서브모듈보다도 더 중요한 모듈입니다. +여러분의 앱은 `Python path`_ 어딘가에 있습니다. 이 자습서에서 우리는 :file:`manage.py`\ 을 이용하여 투표앱을 만들 것입니다. 이것은 ``mysite``\ 의 서브모듈보다도 더 중요한 모듈입니다. -여러분이 앱을 만들기 위해서는 :file:`manage.py`와 같은 디렉토리에서 다음과 같은 명령어를 입력 합니다: +여러분이 앱을 만들기 위해서는 :file:`manage.py`\ 와 같은 디렉토리에서 다음과 같은 명령어를 입력 합니다: .. code-block:: bash python manage.py startapp polls -이 명령어는 다음과 같은 구조를 갖는 :file:`polls`디렉토리를 만들 것입니다:: +이 명령어는 다음과 같은 구조를 갖는 :file:`polls` 디렉토리를 만들 것입니다:: polls/ __init__.py @@ -274,10 +274,10 @@ Django에서 데이터베이스 웹 앱 작성의 첫 단계는 데이터베이 여기에서 여러분은 선택적으로 :class:`~django.db.models.Field` 의 첫번째 인자를 사람이 읽을 수 있는 이름으로 지정 할 수 있습니다. 그것은 Django의 내부적으로 사용되고, 두가지로 설명 해 줍니다. 만약 이 필드를 제공하지 않는다면, Django는 기계가 읽을수 있는 이름만을 사용해야 합니다. 예제에서, 우리는 ``Poll.pub_date``에 대해서만 사람이 읽을 수 있는 이름을 정의 했습니다. 이 모델에서는 다른 모든 필드는 기계가 읽을 수 있는 이름도 충분히 사람이 읽을 수 있는 이름이기 때문입니다. -일부 :class:`~django.db.models.Field` 클레스들은 필수 요소를 필요로 합니다. -예를 들어 :class:`~django.db.models.CharField`는 :attr:`~django.db.models.Field.max_length`를 필수로 필요합니다. 이것은 데이터베이스 스키마에서만 사용 하는 것이 아니라 데이터 검증에서도 사용 합니다. 우리는 그것을 곧 보게 될 것입니다. +일부 :class:`~django.db.models.Field` 클래스들은 필수 요소를 필요로 합니다. +예를 들어 :class:`~django.db.models.CharField`\ 는 :attr:`~django.db.models.Field.max_length`\ 를 필수로 필요합니다. 이것은 데이터베이스 스키마에서만 사용 하는 것이 아니라 데이터 검증에서도 사용 합니다. 우리는 그것을 곧 보게 될 것입니다. -마지막으로, :class:`~django.db.models.ForeignKey`를 이용하여 릴레이션쉽을 정의 했습니다. 이것은 Choice가 하나의 Poll과 관계가 있다고 Django에게 알려줍니다. Django는 다음과 같은 공통의 데이터베이스 릴레이션쉽을 제공합니다: +마지막으로, :class:`~django.db.models.ForeignKey`\ 를 이용하여 릴레이션쉽을 정의 했습니다. 이것은 Choice가 하나의 Poll과 관계가 있다고 Django에게 알려줍니다. Django는 다음과 같은 공통의 데이터베이스 릴레이션쉽을 제공합니다: many-to-ones, many-to-manys, one-to-ones. .. _`Python path`: http://docs.python.org/tutorial/modules.html#the-module-search-path @@ -297,7 +297,9 @@ many-to-ones, many-to-manys, one-to-ones. Django앱은 "플러그" 입니다: 여러분은 여러 프로젝트에서 앱을 사용 할 수 있으며, 앱을 재배포 할 수 있습니다. 왜냐하면 앱들은 Django설치와 밀접하게 묶일 필요가 없기 때문입니다. -:file:`settings.py` 파일에서 :setting:`INSTALLED_APPS` 에 ``'polls'``을 포함하도록 수정합니다. 그러면 다음과 같이 보일 것입니다:: +:file:`settings.py` 파일에서 :setting:`INSTALLED_APPS`\ 에 ``'polls'``\ 을 포함하도록 수정합니다. 그러면 다음과 같이 보일 것입니다. + +:: INSTALLED_APPS = ( 'django.contrib.auth', @@ -313,7 +315,7 @@ many-to-ones, many-to-manys, one-to-ones. 'polls', ) -이제 Django는 ``polls``앱이 포함되었다는 것을 알게 됩니다. 다음 명령어를 실행해 봅시다: +이제 Django는 ``polls`` 앱이 포함되었다는 것을 알게 됩니다. 다음 명령어를 실행해 봅시다: .. code-block:: bash @@ -349,7 +351,7 @@ many-to-ones, many-to-manys, one-to-ones. * 왜래키 릴레이션쉽은 ``REFERENCES`` 문으로 명시됩니다. -* 그것은 사용중인 데이터베이스에 맞게 ``auto_increment`` (MySQL), ``serial`` (PostgreSQL), ``integer primary key``(SQLite)등과 같이 필드 유형에 맞게 자동으로 사용됩니다. 같은 필드 이름의 인용을 위해 사용된다. -- e.g., 큰따옴표 또는 작은 따옴표. +* 그것은 사용중인 데이터베이스에 맞게 ``auto_increment`` (MySQL), ``serial`` (PostgreSQL), ``integer primary key``(SQLite) 등과 같이 필드 유형에 맞게 자동으로 사용됩니다. 같은 필드 이름의 인용을 위해 사용된다. -- e.g., 큰따옴표 또는 작은 따옴표. 이 자습서의 저자는 PostgreSQL를 이용하여 실행 하였으므로, 예제의출력물 역시 PostgreSQL 문법에 따릅니다. * :djadmin:`sql` 명령어는 실제로 여러분의 데이터 베이스에 SQL문을 실행하지 않습니다. @@ -375,10 +377,10 @@ many-to-ones, many-to-manys, one-to-ones. python manage.py syncdb -:djadmin:`syncdb` 명령은 :setting:`INSTALLED_APPS`있는 앱중 이미 데이터베이스에 존재하는 앱을 제외한 모든 앱에 대하여 :djadmin:`sqlall`를 실행 합니다. 이것은 여러분이 syncdb 명령을 마지막으로 실행한 이후에 일어난 모든 앱에 대한 테이블과 초기 데이터, 인덱스를 만듭니다. -:djadmin:`syncdb` 는 원할 때 마다 호출이 가능 하며, 이것은 오직 생성되지 않은 테이블에 대해서만 테이블을 생성합니다. +:djadmin:`syncdb` 명령은 :setting:`INSTALLED_APPS` 있는 앱중 이미 데이터베이스에 존재하는 앱을 제외한 모든 앱에 대하여 :djadmin:`sqlall`\ 를 실행 합니다. 이것은 여러분이 syncdb 명령을 마지막으로 실행한 이후에 일어난 모든 앱에 대한 테이블과 초기 데이터, 인덱스를 만듭니다. +:djadmin:`syncdb` 는 원할 때 마다 호출이 가능하며, 이것은 오직 생성되지 않은 테이블에 대해서만 테이블을 생성합니다. - ``manage.py`` 유틸리티가 무엇을 할 수 있는지에 대한 정보는 :doc:`django-admin.py 문서 ` 를 읽어 보십시오. +``manage.py`` 유틸리티가 무엇을 할 수 있는지에 대한 정보는 :doc:`django-admin.py 문서 `\ 를 읽어 보십시오. API와 놀기 ==================== @@ -393,12 +395,14 @@ API와 놀기 .. admonition:: manage.py 건너뛰기 - 만약 :file:`manage.py`을 사용하지 않는다 해도 문제없습니다. 단지 ``mysite.settings`` 에 ``DJANGO_SETTINGS_MODULE`` 환경변수를 설정하고 - :file:`manage.py` 파일이 있는 같은 디렉토리에서 ``python``을 실행 하면됩니다. (또는 그 디렉토리가 파이썬 경로에 위치 하거나 ``import mysite`` 해야 사용 할 수 있습니다). + 만약 :file:`manage.py`\ 를 사용하지 않는다 해도 문제없습니다. 단지 ``mysite.settings``\ 에 ``DJANGO_SETTINGS_MODULE`` 환경변수를 설정하고 + :file:`manage.py` 파일이 있는 같은 디렉토리에서 ``python``\ 을 실행 하면됩니다. (또는 그 디렉토리가 파이썬 경로에 위치 하거나 ``import mysite`` 해야 사용 할 수 있습니다). + + 더 많은 정보를 원한다면 :doc:`django-admin.py문서 `\ 를 확인하세요. - 더 많은 정보를 원단하면 :doc:`django-admin.py문서 `를 확인 하세요. +일단 쉘에서 :doc:`database API `\ 를 확인해 보세요. -일단 쉘에서 :doc:`database API `를 확인해 보세요:: +:: >>> from polls.models import Poll, Choice # Import the model classes we just wrote. @@ -438,7 +442,9 @@ API와 놀기 [] -잠시만요. ````는 완전히 이 객체 자체를 표현 하지 객체의 내용을 표현 하지 않습니다. 우리는 polls 모델을 수정하여(``polls/models.py`` 파일) ``Poll`` 과``Choice``에 :meth:`~django.db.models.Model.__unicode__` 를 추가하여 원하는 내용을 표현 할 수 있습니다:: +잠시만요. ````\ 는 완전히 이 객체 자체를 표현 하지 객체의 내용을 표현 하지 않습니다. 우리는 polls 모델을 수정하여(``polls/models.py`` 파일) ``Poll``\ 과``Choice``\ 에 :meth:`~django.db.models.Model.__unicode__`\ 를 추가하여 원하는 내용을 표현 할 수 있습니다. + +:: class Poll(models.Model): # ... @@ -450,19 +456,21 @@ API와 놀기 def __unicode__(self): return self.choice -:meth:`~django.db.models.Model.__unicode__` 메소드를 추가 하는 것은 여러분의 모델에서 매우 중요합니다. 이것은 대화식 프롬프트에서 사용 할 때 뿐만 아니라,Django에서 자동 생성되는 관리자 화면에서 표현 할 때도 사용됩니다. +:meth:`~django.db.models.Model.__unicode__` 메소드를 추가 하는 것은 여러분의 모델에서 매우 중요합니다. 이것은 대화식 프롬프트에서 사용 할 때 뿐만 아니라, Django에서 자동 생성되는 관리자 화면에서 표현 할 때도 사용됩니다. -.. admonition:: 왜 :meth:`~django.db.models.Model.__unicode__` 은 되고 :meth:`~django.db.models.Model.__str__`은 안되나요? +.. admonition:: 왜 :meth:`~django.db.models.Model.__unicode__` 은 되고 :meth:`~django.db.models.Model.__str__`\ 은 안되나요? - 만약 여러분이 파이썬에 익숙한 경우,여러분은 :meth:`~django.db.models.Model.__unicode__` 메소드 대신 :meth:`~django.db.models.Model.__str__`를 추가하는 습관이 있을 수 있습니다. 우리가 - :meth:`~django.db.models.Model.__unicode__` 을 사용 하는 이유는 Django 모델에서는 기본적으로 유니코드를 사용하기로 약속 했기 때문입니다. 데이터가 반환될때 여러분의 데이터베이스에 있는 모든데이터는 + 만약 여러분이 파이썬에 익숙한 경우,여러분은 :meth:`~django.db.models.Model.__unicode__` 메소드 대신 :meth:`~django.db.models.Model.__str__`\ 를 추가하는 습관이 있을 수 있습니다. 우리가 + :meth:`~django.db.models.Model.__unicode__`\ 을 사용 하는 이유는 Django 모델에서는 기본적으로 유니코드를 사용하기로 약속 했기 때문입니다. 데이터가 반환될때 여러분의 데이터베이스에 있는 모든 데이터는 유니코드로 변환되어 반환됩니다. - Django 모델은 기본적으로 :meth:`~django.db.models.Model.__str__` 메소드는 :meth:`~django.db.models.Model.__unicode__` 를 호출한 결과를 UTF-8 바이트 스트링으로 변환하여 보여줍니다. 이 말은 ``unicode(p)``는 유니코드 문자열을, ``str(p)`` 은 UTF-8로 변환된 기본 문자열을 반환 한다는 뜻 입니다. + Django 모델은 기본적으로 :meth:`~django.db.models.Model.__str__` 메소드는 :meth:`~django.db.models.Model.__unicode__`\ 를 호출한 결과를 UTF-8 바이트 스트링으로 변환하여 보여줍니다. 이 말은 ``unicode(p)``\ 는 유니코드 문자열을, ``str(p)``\ 은 UTF-8로 변환된 기본 문자열을 반환한다는 뜻입니다. + + 이 모든것이 혼란스럽다면 모델에서 :meth:`~django.db.models.Model.__unicode__` 메소드만 사용한다는 것을 기억하세요. 운이 좋다면, 이 모든 것은 잘 동작할 것입니다. - 이 모든것이 혼란스럽다면 모델에서 :meth:`~django.db.models.Model.__unicode__` 메소드만 사용 한 다는 것을 기억하세요. 운이 좋다면, 이 모든 것은 잘 동작 할 것입니다. +다음은 일반적인 파이썬 방법입니다. 데모를 위해 여기에 사용자 정의 메소드를 추가하세요. -다음은 일반적인 파이썬 방법입니다. 데모를 위해 여기에 사용자 정의 메소드를 추가하세요.:: +:: import datetime from django.utils import timezone @@ -472,9 +480,11 @@ API와 놀기 def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) -참고로 추가한 ``import datetime``과 ``from django.utils import timezone``은 각각 파이썬의 표준 메소드인 :mod:`datetime` 과 Django의 time-zone-related 유틸리테에 들어있는 :mod:`django.utils.timezone`을 참조하세요. 여러분이 파이썬 시간 처리에 대해 익수하지 않은경우, 여러분은 :doc:`time zone support docs `에서 배울 수 있습니다. +참고로 추가한 ``import datetime``\ 과 ``from django.utils import timezone``\ 은 각각 파이썬의 표준 메소드인 :mod:`datetime` 과 Django의 time-zone-related 유틸리테에 들어있는 :mod:`django.utils.timezone`을 참조하세요. 여러분이 파이썬 시간 처리에 대해 익수하지 않은경우, 여러분은 :doc:`time zone support docs `\ 에서 배울 수 있습니다. + +저장 후 ``python manage.py shell`` 이용하여 새로운 파이썬 대화형 쉘을 실행하세요. -저장 후 ``python manage.py shell`` 이용하여 새로운 파이썬 대화형 쉘을 실행하세요:: +:: >>> from polls.models import Poll, Choice @@ -548,6 +558,6 @@ API와 놀기 >>> c = p.choice_set.filter(choice__startswith='Just hacking') >>> c.delete() -모델관계에 대한 자세한 사항은 :doc:`Accessing related objects `을 확인 하세요. API에서 이중밑줄(__)을 어떻게 사용 하는지에 대한 자세한 사항은 :ref:`Field lookups `에서 확인하세요. 데이터베이스 API에대한 자세한 사항은 :doc:`Database API reference `에서 확인하세요. +모델관계에 대한 자세한 사항은 :doc:`Accessing related objects `\ 을 확인 하세요. API에서 이중밑줄(__)을 어떻게 사용 하는지에 대한 자세한 사항은 :ref:`Field lookups `에서 확인하세요. 데이터베이스 API에대한 자세한 사항은 :doc:`Database API reference `\ 에서 확인하세요. -이제 여러분이 API를 익숙하게 사용 하신다면, :doc:`part 2 of this tutorial `로 가서 Django에서 자동으로 생성되는 관리자에 대하여 확인하세요. +이제 여러분이 API를 익숙하게 사용 하신다면, :doc:`part 2 of this tutorial `\ 로 가서 Django에서 자동으로 생성되는 관리자에 대하여 확인하세요. From c959363f48f5f8e817c5ef779c0e636a4f731128 Mon Sep 17 00:00:00 2001 From: Yong Choi Date: Sun, 19 Aug 2012 04:14:27 +0900 Subject: [PATCH 038/128] Update intro/tutorial01.txt --- intro/tutorial01.txt | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/intro/tutorial01.txt b/intro/tutorial01.txt index 887708f..1820691 100644 --- a/intro/tutorial01.txt +++ b/intro/tutorial01.txt @@ -13,7 +13,7 @@ 우리는 여러분이 이미 :doc:`Django 설치`\ 를 완료 하였다고 가정하에 진행 하도록 하겠습니다. 여러분은 파이썬 인터프리터를 실행하여 ``import django``\ 를 입력해 봄으로써 Django가 설치되어 있는지 확인할 수 있습니다. 만약 에러 없이 실행된다면, Django 설치가 완료된 것입니다. -.. admonition:: 도움말은 어디서 얻을 수 있나요?: +.. admonition:: 도움말은 어디서 얻을 수 있나요? 만약 여러분이 이 자습서를 따라하는 도중 문제가 발생 할 경우 `django-users`__\ 로 메시지를 보내 주시거나 또는 `#django on irc.freenode.net`__\ 에서 @@ -39,7 +39,7 @@ __ irc://irc.freenode.net/django 만약 여러분이 리눅스 배포판 패키지 관리자를 이용하여 Django를 설치 하였다면 (e.g. apt-get or yum) ``django-admin.py`` 파일의 이름이 - ``django-admin``로 변경 되었을 수도 있습니다. 그럴 경우 여러분은 이 문서에서 계속적으로 각 명령에 + ``django-admin``\ 로 변경 되었을 수도 있습니다. 그럴 경우 여러분은 이 문서에서 계속적으로 각 명령에 ``.py`` 을 생략하여 사용 할 수 있습니다. .. admonition:: Mac OS X 권한 @@ -55,8 +55,8 @@ __ irc://irc.freenode.net/django 여러분은 파이썬이나 Django 구성요소에 내장된 이름을 프로젝트 이름을 정하는 것을 피해야 합니다. 특히, ``django`` (Django자체와 충돌 발생)나 ``test``(파이썬 패키지에 내장되어 있어 충돌이 발생)과 같은 이름사용을 주의해야 한다는 것 입니다. -:doc:`django-admin.py `는 여러분이 Django를 ``python setup.py`` 명령으로 설치를 하였다면 여러분의 시스템 경로에 존재 할 것입니다. 만약 찾을 수 없다면 여러분은 -``site-packages/django/bin`` 여기에서 찾을 수 있을 것 이고, ``site-packages`` 는 파이썬의 설치 경로입니다. +:doc:`django-admin.py `\ 는 여러분이 Django를 ``python setup.py`` 명령으로 설치를 하였다면 여러분의 시스템 경로에 존재 할 것입니다. 만약 찾을 수 없다면 여러분은 +``site-packages/django/bin`` 여기에서 찾을 수 있을 것 이고, ``site-packages``\ 는 파이썬의 설치 경로입니다. 불편하다면 :doc:`django-admin.py ` 을 :file:`/usr/local/bin`\ 로 심볼릭링크를 걸어두는 것을 고려해 볼 수 있습니다. .. admonition:: 어디에서 이 코드가 실행 되나요? @@ -120,7 +120,7 @@ __ irc://irc.freenode.net/django 중요사항: 절대 서비스 서버환경으로 사용하지 마십시오. 이 서버는 오직 개발하는 동안만 사용 하도록 계획된 것입니다. (우리의 목적은 웹 프레임워크를 만드는 것이지 웹서버를 만드는 것이 아닙니다.) -서버 동작을 확인 하기 위해서 웹 브라우저에서 http://127.0.0.1:8000/를 방문해 보세요. 여러분은 유쾌하고 라이트 블루 파스텔톤의 "Welcome to Django" 페이지를 볼 수 있을 것입니다. +서버 동작을 확인 하기 위해서 웹 브라우저에서 http://127.0.0.1:8000/\ 를 방문해 보세요. 여러분은 유쾌하고 라이트 블루 파스텔톤의 "Welcome to Django" 페이지를 볼 수 있을 것입니다. 성공! .. admonition:: 포트 변경하기 @@ -165,7 +165,7 @@ __ irc://irc.freenode.net/django * :setting:`HOST` -- 데이터베이스가 있는 호스트데이터 베이스가 동일한 물리적 장치에 있다면 비어있는 문자열을 사용합니다. (SQLite 에서는 사용하지 않습니다). -만약 여러분이 새로운 데이터 베이스를 사용 하길 원하신다면, 쉽게 사용 가능 한 SQLite를 추천합니다. :setting:`ENGINE`에 ``'django.db.backends.sqlite3'`` 를 입력하고 :setting:`NAME` 에 데이터베이스 파일이 저장 될 경로를 입력 하시면 됩니다. SQLite는 파이썬 2.5 이상부터 포함되어 있어서 여러분은 데이터베이스 지원을 위해서 아무것도 설치 할 필요가 없습니다. +만약 여러분이 새로운 데이터 베이스를 사용 하길 원하신다면, 쉽게 사용 가능 한 SQLite를 추천합니다. :setting:`ENGINE`\ 에 ``'django.db.backends.sqlite3'``\ 를 입력하고 :setting:`NAME`\ 에 데이터베이스 파일이 저장될 경로를 입력하시면 됩니다. SQLite는 파이썬 2.5 이상부터 포함되어 있어서 여러분은 데이터베이스 지원을 위해서 아무것도 설치할 필요가 없습니다. .. 참고:: @@ -207,7 +207,7 @@ __ irc://irc.freenode.net/django 위에서 말했듯이, 기본 응용프로그램은 일반적인 케이스에 포함하지만, 모든사람이 다 필요로 하지 않습니다. 만약 여러분이 일부 또는 전부가 필요없다면, :djadmin:`syncdb` 명령은 오직 :setting:`INSTALLED_APPS` 안에 설정된 앱에 대해서만 테이블을 생성 하기때문에 - :djadmin:`syncdb`를 실행 하기 전에 자유롭게 :setting:`INSTALLED_APPS`\ 에서 주석 처리를 하거나 삭제 할 수 있습니다. + :djadmin:`syncdb`\ 를 실행 하기 전에 자유롭게 :setting:`INSTALLED_APPS`\ 에서 주석 처리를 하거나 삭제 할 수 있습니다. .. _creating-models: @@ -272,7 +272,7 @@ Django에서 데이터베이스 웹 앱 작성의 첫 단계는 데이터베이 각 :class:`~django.db.models.Field` 인스턴스의 이름은(e.g. ``question`` 또는 ``pub_date`` )기계친화적인 필드이름 입니다. 여러분은 이것을 여러분의 파이썬 코드에서 사용하고, 데이터베이스는 필드 이름으로 사용합니다. 여기에서 여러분은 선택적으로 :class:`~django.db.models.Field` 의 첫번째 인자를 사람이 읽을 수 있는 이름으로 지정 할 수 있습니다. 그것은 Django의 내부적으로 사용되고, 두가지로 설명 해 줍니다. -만약 이 필드를 제공하지 않는다면, Django는 기계가 읽을수 있는 이름만을 사용해야 합니다. 예제에서, 우리는 ``Poll.pub_date``에 대해서만 사람이 읽을 수 있는 이름을 정의 했습니다. 이 모델에서는 다른 모든 필드는 기계가 읽을 수 있는 이름도 충분히 사람이 읽을 수 있는 이름이기 때문입니다. +만약 이 필드를 제공하지 않는다면, Django는 기계가 읽을수 있는 이름만을 사용해야 합니다. 예제에서, 우리는 ``Poll.pub_date``\ 에 대해서만 사람이 읽을 수 있는 이름을 정의 했습니다. 이 모델에서는 다른 모든 필드는 기계가 읽을 수 있는 이름도 충분히 사람이 읽을 수 있는 이름이기 때문입니다. 일부 :class:`~django.db.models.Field` 클래스들은 필수 요소를 필요로 합니다. 예를 들어 :class:`~django.db.models.CharField`\ 는 :attr:`~django.db.models.Field.max_length`\ 를 필수로 필요합니다. 이것은 데이터베이스 스키마에서만 사용 하는 것이 아니라 데이터 검증에서도 사용 합니다. 우리는 그것을 곧 보게 될 것입니다. @@ -343,7 +343,7 @@ many-to-ones, many-to-manys, one-to-ones. * 정확한 출력은 사용중인 데이터베이스에 따라 달라집니다. -* 테이블 이름은 앱 이름(``polls``)과 소문자 모델이름 --``poll``, ``choice``과 합성되어 자동으로 생성됩니다.(여러분은 이동작을 재 정의 할 수 있습니다.) +* 테이블 이름은 앱 이름(``polls``)과 소문자 모델이름 --``poll``, ``choice``\ 과 합성되어 자동으로 생성됩니다.(여러분은 이동작을 재 정의 할 수 있습니다.) * Primary key는(IDs) 자동으로 추가됩니다. (여러분은 이것 또한 재정의 할 수 있습니다.) @@ -351,7 +351,7 @@ many-to-ones, many-to-manys, one-to-ones. * 왜래키 릴레이션쉽은 ``REFERENCES`` 문으로 명시됩니다. -* 그것은 사용중인 데이터베이스에 맞게 ``auto_increment`` (MySQL), ``serial`` (PostgreSQL), ``integer primary key``(SQLite) 등과 같이 필드 유형에 맞게 자동으로 사용됩니다. 같은 필드 이름의 인용을 위해 사용된다. -- e.g., 큰따옴표 또는 작은 따옴표. +* 그것은 사용중인 데이터베이스에 맞게 ``auto_increment`` (MySQL), ``serial`` (PostgreSQL), ``integer primary key`` (SQLite) 등과 같이 필드 유형에 맞게 자동으로 사용됩니다. 같은 필드 이름의 인용을 위해 사용된다. -- e.g., 큰따옴표 또는 작은 따옴표. 이 자습서의 저자는 PostgreSQL를 이용하여 실행 하였으므로, 예제의출력물 역시 PostgreSQL 문법에 따릅니다. * :djadmin:`sql` 명령어는 실제로 여러분의 데이터 베이스에 SQL문을 실행하지 않습니다. @@ -391,7 +391,7 @@ API와 놀기 python manage.py shell -:file:`manage.py` 파일 이 여러분의 :file:`settings.py`에서 Djanog에게 파이썬 가져오기 경로를 ``DJANGO_SETTINGS_MODULE`` 환경설정을 통해 제공 하기 때문에 우리는 단순히 "python"이라고 입력 하면 됩니다. +:file:`manage.py` 파일 이 여러분의 :file:`settings.py`\ 에서 Djanog에게 파이썬 가져오기 경로를 ``DJANGO_SETTINGS_MODULE`` 환경설정을 통해 제공 하기 때문에 우리는 단순히 "python"이라고 입력 하면 됩니다. .. admonition:: manage.py 건너뛰기 @@ -442,7 +442,7 @@ API와 놀기 [] -잠시만요. ````\ 는 완전히 이 객체 자체를 표현 하지 객체의 내용을 표현 하지 않습니다. 우리는 polls 모델을 수정하여(``polls/models.py`` 파일) ``Poll``\ 과``Choice``\ 에 :meth:`~django.db.models.Model.__unicode__`\ 를 추가하여 원하는 내용을 표현 할 수 있습니다. +잠시만요. ````\ 는 완전히 이 객체 자체를 표현 하지 객체의 내용을 표현 하지 않습니다. 우리는 polls 모델을 수정하여(``polls/models.py`` 파일) ``Poll``\ 과 ``Choice``\ 에 :meth:`~django.db.models.Model.__unicode__`\ 를 추가하여 원하는 내용을 표현 할 수 있습니다. :: @@ -480,7 +480,7 @@ API와 놀기 def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) -참고로 추가한 ``import datetime``\ 과 ``from django.utils import timezone``\ 은 각각 파이썬의 표준 메소드인 :mod:`datetime` 과 Django의 time-zone-related 유틸리테에 들어있는 :mod:`django.utils.timezone`을 참조하세요. 여러분이 파이썬 시간 처리에 대해 익수하지 않은경우, 여러분은 :doc:`time zone support docs `\ 에서 배울 수 있습니다. +참고로 추가한 ``import datetime``\ 과 ``from django.utils import timezone``\ 은 각각 파이썬의 표준 메소드인 :mod:`datetime` 과 Django의 time-zone-related 유틸리테에 들어있는 :mod:`django.utils.timezone`\ 을 참조하세요. 여러분이 파이썬 시간 처리에 대해 익숙하지 않은경우, 여러분은 :doc:`time zone support docs `\ 에서 배울 수 있습니다. 저장 후 ``python manage.py shell`` 이용하여 새로운 파이썬 대화형 쉘을 실행하세요. From caae0dcb1ac5e8f3b27b656665bbcfe0a7a00f3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A0=95=EC=84=B1=ED=83=9C?= Date: Wed, 22 Aug 2012 13:33:42 +0900 Subject: [PATCH 039/128] Update intro/tutorial04.txt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문맥에 맞게 문장 수정 -다, -입니다. 이런 식으로 변경 --- intro/tutorial04.txt | 136 +++++++++++++++++++++---------------------- 1 file changed, 68 insertions(+), 68 deletions(-) diff --git a/intro/tutorial04.txt b/intro/tutorial04.txt index 93ec9ce..d934e76 100644 --- a/intro/tutorial04.txt +++ b/intro/tutorial04.txt @@ -2,12 +2,12 @@ 첫번째 장고 앱 만들기! part 4 ==================================== -본 자습서는 :doc:`Tutorial 3 `\ 에 이어서 계속 됩니다. 우리는 웹 설문조사 어플리케이션을 만들고 있고, 우리 코드의 양을 줄이고, 간단한 폼처리를 하는데 초점을 맞출 것 입니다. +본 자습서는 :doc:`Tutorial 3 `\ 에 이어서 계속 됩니다. 우리는 웹 설문조사 어플리케이션을 만들고 있는 중이죠, 이 장에서는 우리 코드의 양을 줄이고, 간단한 폼처리를 하는데 집중할 것입니다. 간단한 폼 사용하기. =================== -HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조사 세부 템플릿을 수정하자: +HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조사 세부 템플릿을 수정합시다: .. code-block:: html+django @@ -26,27 +26,27 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 간략하게 설명하면: -* 위의 템플릿은 각 설문 선택지의 라디오버튼을 표시한다. 각 라디오 버튼의 - ``value``\ 는 연결된 설문조사 선택지의 ID이다. 각 라디오 버튼의 ``name`` - 은 ``"choice"``\ 이다. 이것은, 누군가 라디오버튼중 하나를 선택하고, - 폼을 제출하면, 폼은 POST 자료 ``choice=3``\ 를 전송한다는 것을 의미한다. - 이것이 HTML Forms 101(역자주: HTML FORMS의 기본)이다. +* 위의 템플릿은 각 설문 선택지의 라디오버튼을 표시합니다. 각 라디오 버튼의 + ``value``\ 는 연결된 설문조사 선택지의 ID입니다. 각 라디오 버튼의 ``name`` + 은 ``"choice"``\ 입니다. 이것은, 누군가 라디오버튼중 하나를 선택하고, + 폼을 제출하면, 폼은 POST 자료 ``choice=3``\ 를 전송한다는 것을 의미합니다. + 이것이 HTML Forms 101(역자주: HTML FORMS의 기본)이죠. * 우리는 폼의 ``action``\ 을 ``/polls/{{ poll.id }}/vote/``\ 로 지정하고, - ``method="post"``\ 로 지정했다. 이 폼을 제출하는 행위가 서버측 자료를 변경할 + ``method="post"``\ 로 지정했습다. 이 폼을 제출하는 행위가 서버측 자료를 변경할 수 있기 때문에 ``method="post"``\ 를 사용하는 것은 (혹은 반대로 ``method="get"``) - 매우 중요하다. 서버측 자료를 변경할 폼을 만들때는, 항상 ``method="post"``\ 을 - 사용하라. 이 정보는 장고에 특정한 정보가 아니다; 단지 좋은 웹 개발 관례일 뿐이다. + 매우 중요합니다. 서버측 자료를 변경할 폼을 만들때는, 항상 ``method="post"``\ 을 + 사용하세요. 이 정보는 장고에 특정한 정보가 아닙니다; 단지 좋은 웹 개발 관례일 뿐입니다. -* ``forloop.counter``\ 는 :ttag:`for` 태그가 반복을 한 횟 수를 나타낸다. +* ``forloop.counter``\ 는 :ttag:`for` 태그가 반복을 한 횟 수를 나타냅니다. * 우리는 POST 폼(자료를 수정하는 효과를 가진)을 만들고 있으므로, 사이트 간 요청 위조 - (Cross Site Request Forgeries)에 대해 고민해야한다.고맙게도, 장고는 - 사이트 간 요청 위조(CSRF)에 대해 보호하기위한 사용하기 쉬운 시스템을 가지고 있기 때문에, - 너무 심각하게 고민할 필요가 없다. 간단히 말하면, 내부 URL들을 향하는 모든 POST 폼은 - 템플릿 태그 :ttag:`{% csrf_token %}`\ 을 사용해야한다. + (Cross Site Request Forgeries)에 대해 고민해야합니다.고맙게도, 장고는 + 사이트 간 요청 위조(CSRF)에 대항하기위한 사용하기 쉬운 시스템을 가지고 있기 때문에, + 너무 심각하게 고민할 필요가 없습니다. 간단히 말하면, 내부 URL들을 향하는 모든 POST 폼에 + 템플릿 태그 :ttag:`{% csrf_token %}`\ 을 사용하면됩니다. -:ttag:`{% csrf_token %}` 태그는 템플릿 문법에서 평범하게 접근이 불가능한 요청(request) 개체로부터의 정보를 필요로 한다. 이부분을 적용하기 위해, 다음과 같은 작은 조정이 ``detail`` 뷰에 필요하다 :: +:ttag:`{% csrf_token %}` 태그는 템플릿 문법에서 접근이 불가능한 요청(request) 개체로부터의 정보를 필요로 합니다. 이부분을 적용하기 위해, 다음과 같은 작은 조정이 ``detail`` 뷰에 필요합니다 :: from django.template import RequestContext # ... @@ -55,13 +55,13 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 return render_to_response('polls/detail.html', {'poll': p}, context_instance=RequestContext(request)) -이것이 작동하는 것에 대한 자세한 내용은 :ref:`RequestContext ` 부분의 문서를 참고하라. +이것이 작동하는 것에 대한 자세한 내용은 :ref:`RequestContext ` 부분의 문서를 참고하시면됩니다. -이제 전송된 자료를 다룰 장고 뷰를 만들고, 그것을 가지고 무엇인가를 해보자. :doc:`자습서 3 `\ 에서 설문조사 어플리케이션을 위해 아래에 나와있는 코드를 포함하는 URLconf를 만들었었다. :: +이제 전송된 자료를 다룰 장고 뷰를 만들고, 그것을 가지고 무엇인가를 해봅시다. :doc:`자습서 3 `\ 에서 설문조사 어플리케이션을 위해 아래에 나와있는 코드를 포함하는 URLconf를 만들었습니다. :: (r'^(?P\d+)/vote/$', 'vote'), -또, 우리는 ``vote()``\ 더미의 실행 함수를 만들었다. 실제 버전을 만들어보자. ``polls/views.py``\ 에 다음을 추가하자:: +또, 우리는 ``vote()``\ 를 가상으로 만들었습니다. 실제로 구현을 해봅시다. ``polls/views.py``\ 에 다음을 추가합시다:: from django.shortcuts import get_object_or_404, render_to_response from django.http import HttpResponseRedirect, HttpResponse @@ -87,53 +87,53 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 # 자료가 두 번 전송되는 경우를 막아준다. return HttpResponseRedirect(reverse('polls.views.results', args=(p.id,))) -위 코드는 이 자습서에서 아직 다루지 않은 몇 가지를 포함하고 있다: +위 코드는 이 자습서에서 아직 다루지 않은 몇 가지를 포함하고 있습다: * :attr:`request.POST ` 는 키로 전송된 자료에 - 접근할 수 있도록 해주는 사전과 같은 객체이다. 이 경우에서 ``request.POST['choice']``\ 는 - 선택된 설문지의 ID를 문자열로 반환한다. :attr:`request.POST `\ 의 값은 항상 문자열들이다. + 접근할 수 있도록 해주는 사전과 같은 객체입니다. 이 경우에서 ``request.POST['choice']``\ 는 + 선택된 설문지의 ID를 문자열로 반환합다. :attr:`request.POST `\ 의 값은 항상 문자열들입다. Django는 같은 방법으로 GET 자료에 접근하기 위해 :attr:`request.GET `\ 를 - 제공한다. 그러나 POST 요청으로만 자료가 수정되게하기 위해서, 우리는 + 제공합다. 그러나 POST 요청으로만 자료가 수정되게하기 위해서, 우리는 명시적으로 코드에 :attr:`request.POST `\ 를 사용하고 있다. * 만약 POST 자료에 ``choice``\ 가 없으면, ``request.POST['choice']``\ - 는 :exc:`KeyError`\ 를 일으킨다. 위의 코드는 :exc:`KeyError`\ 를 체크하고, ``choice``\ 가 주어지지 않은 경우에는 - 설문조사 양식을 다시보여준다. + 는 :exc:`KeyError`\ 가 일어납니다. 위의 코드는 :exc:`KeyError`\ 를 체크하고, ``choice``\ 가 주어지지 않은 경우에는 + 설문조사 양식을 다시보여줍니다. * 설문지의 수가 증가한 이후에, 코드는 평범한 :class:`~django.http.HttpResponse` 보다는 - :class:`~django.http.HttpResponseRedirect`\ 를 반환한다 :class:`~django.http.HttpResponseRedirect`\ 는 하나의 인수를 받는다: - 사용자가 재전송할 URL. (이 경우에 우리가 URL을 + :class:`~django.http.HttpResponseRedirect`\ 를 반환하고, :class:`~django.http.HttpResponseRedirect`\ 는 하나의 인수를 받습니다: + 그 인수는 사용자가 재전송할 URL 입니다. (이 경우에 우리가 URL을 어떻게 구성하는지 다음 항목을 보라). 위 소스안의 주석내용대로, POST 자료를 성공적으로 처리한 후에는 항상 - :class:`~django.http.HttpResponseRedirect`\ 를 반환해야한다. 이것은 - 장고에만 특정한 팁이 아니다. 좋은 웹 개발관례일 뿐이다. + :class:`~django.http.HttpResponseRedirect`\ 를 반환해야합니다. 이것은 + 장고에만 특정한 팁이 아닙니다. 좋은 웹 개발관례일 뿐이죠. * 우리는 이 예제에서 :class:`~django.http.HttpResponseRedirect` 생성자 안의 - :func:`~django.core.urlresolvers.reverse` 함수를 사용하고 있다. - 이 함수는 함수에서 URL을 하드코딩하는 행위를 안하게 도와준다. - 제어를 전달하기 원하는 뷰의 이름을 제공하고, URL패턴의 변수부분이 그 뷰를 가리킨다. - 이 경우에, URLconf를 사용하여 우리는 자습서 3에서 설정하였다. - 아래와 같은 문자열을 반환할 것이다. + :func:`~django.core.urlresolvers.reverse` 함수를 사용하고 있습니다. + 이 함수는 함수에서 URL을 하드코딩하는 행위를 안하게 도와줍다. + 제어를 전달하기 원하는 뷰의 이름을 제공하고, URL패턴의 변수부분이 그 뷰를 가리킵니다. + 이 경우에, URLconf를 사용하여 우리는 자습서 3에서 설정하였습다. + 아래와 같은 문자열을 반환할 것입니다. :: '/polls/3/results/' - ... ``3``\ 은 ``p.id``\ 의 값이다. 이 리다이렉트된 URL은 마지막 페이지를 보여주기위해 ``'results'`` 뷰를 호출한다. 뷰 이름(풀네임)을 사용해야한다는 것을 주의하라(접두사를 포함하여) . + ... ``3``\ 은 ``p.id``\ 의 값이다. 이 리다이렉트된 URL은 마지막 페이지를 보여주기위해 ``'results'`` 뷰를 호출합다. 뷰 이름(풀네임)을 사용해야한다는 것을 주의하세요(접두사를 포함하여) . -자습서 3에서 언급했듯이, ``request``\ 는 :class:`~django.http.HttpRequest`\ 개체이다. :class:`~django.http.HttpRequest` 개체에 대해 더 알고 싶다면 :doc:`request and response documentation `\ 을 참고하라. +자습서 3에서 언급했듯이, ``request``\ 는 :class:`~django.http.HttpRequest`\ 개체입니다. :class:`~django.http.HttpRequest` 개체에 대해 더 알고 싶다면 :doc:`request and response documentation `\ 을 참고하세요. -어떤 이가 설문조사에 설문을 하고난 뒤에는, ``vote()`` 뷰는 설문조사 결과 페이지로 리다이렉트한다. 그 뷰를 작성해보자 :: +어떤 이가 설문조사에 설문을 하고난 뒤에는, ``vote()`` 뷰는 설문조사 결과 페이지로 리다이렉트합니다. 그 뷰를 작성해봅시다 :: def results(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/results.html', {'poll': p}) -이것은 :doc:`Tutorial 3`\ 의 ``detail()`` 뷰와 거의 동일하다. 다른점은 템플릿 이름밖에 없다. 우리는 후에 이 쓸데없는 것들을 수정할 것이다.(역자주:쓸데없는 것이라고 한 이유는 위 파일이 필요없어지기 때문입니다.) +이것은 :doc:`Tutorial 3`\ 의 ``detail()`` 뷰와 거의 동일합니다. 다른점은 템플릿 이름밖에 없습니다. 우리는 후에 이 쓸데없는 것들을 수정할 것입니다.(역자주:쓸데없는 것이라고 한 이유는 위 파일이 필요없어지기 때문입니다.) -이제, ``results.html`` 템플릿을 만들자: +이제, ``results.html`` 템플릿을 만듭시다: .. code-block:: html+django @@ -147,19 +147,19 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 Vote again? -이제, 웹 브라우저에서 ``/polls/1/`` 페이지로 가자, 그리고 설문조사를 해보자. 당신이 설문조사를 할 때마다 값이 반영된 결과페이지를 볼것이다. 만약 당신이 설문지를 선택하지 않고 폼을 전송했다면, 에러메시지를 보게될 것이다. +이제, 웹 브라우저에서 ``/polls/1/`` 페이지로 가봅시다, 그리고 설문조사를 해보세요. 당신이 설문조사를 할 때마다 값이 반영된 결과페이지를 볼 수 있을 것입니다. 만약 당신이 설문지를 선택하지 않고 폼을 전송했다면, 에러메시지를 보게될 것입니다. 제네릭 뷰 사용하기 : 적은 코드가 더 좋음 ====================================== ``detail()`` ( :doc:`자습서 3 `\ 에서의) 과 ``results()`` -뷰는 매우 비슷하다. -- 그리고, 위에서 언급한 것 처럼 장황하다. 설문 목록들을 보여주는 ``index()`` 뷰(이것도 자습서 3에서)도 마찬가지이다. +뷰는 매우 비슷했습니다. -- 그리고, 위에서 언급한 것 처럼 장황합니다. 설문 목록들을 보여주는 ``index()`` 뷰(이것도 자습서 3에서)도 마찬가지입니다. -이 뷰들은 기본적인 웹 개발의 일반적인 케이스들:(URL로 전달된 매개변수로부터 데이터베이스에서 자료를 얻고, 템플릿을 불러오며, 처리된 템플릿을 반환하는)을 제공한다. 이것들이 매우 일반적인 것들이기 때문에, 장고는 "제네릭 뷰" 시스템이라 불리는 지름길을 제공한다. +이 뷰들은 기본적인 웹 개발의 일반적인 케이스들:(URL로 전달된 매개변수를 이용해서 데이터베이스에서 자료를 얻고, 템플릿을 불러오며, 처리된 템플릿을 반환하는)을 제공합니다. 이것들이 매우 일반적인 것들이기 때문에, 장고는 "제네릭 뷰" 시스템이라 불리는 지름길을 제공한다. -앱을 쓰기위해 파이썬 코드를 쓸 필요가 없을 정도로 제네릭 뷰는 일반적인(역자주-중복되고, 장황한) 패턴들을 제거한다. +앱을 만들기위해 파이썬 코드를 쓸 필요가 없을 정도로 제네릭 뷰는 일반적인(역자주-중복되고, 장황한) 패턴들을 제거합니다. -제네릭 뷰 시스템을 사용해서 우리의 설문조사 앱을 바꿔보자. 그리고 우리의 코드를 삭제할 수도 있다. 변환하기에는 몇 단계를 거쳐야 한다. 우리는: +제네릭 뷰 시스템을 사용해서 우리의 설문조사 앱을 바꿔봅시다. 그리고 이미 만든 우리의 코드를 삭제할 수도 있습니다. 제네릭 뷰로 변환하기에는 몇 단계를 거쳐야 합니다. 우리는: 1. URLconf를 변환한다. @@ -167,7 +167,7 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 3. 새로운 뷰들을 위해 URL 다루기를 수정한다. -자세한 내용을 읽어보라. +자세한 내용을 읽어보세요. .. admonition:: 왜 코드 섞기(code-shuffle)(역자주:코드를 이렇게 저렇게 수정하는 것)인가? @@ -177,9 +177,9 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 지금까지 핵심개념들을 배우기위해 의도적으로 "힘든 방법으로", 뷰 작성하기에 초점을 맞춰왔다. - 계산기를 사용하기전에 기본적인 산수를 알아야하지 않겠는가. + 계산기를 사용하기전에 기본적인 산수 정도는 알아야하지 않겠는가. -먼저, ``polls/urls.py``\ 의 URLconf를 보자. 지금까지의 자습서 내용대로라면 아래와 같은 내용이 보일것이다. :: +먼저, ``polls/urls.py``\ 의 URLconf를 봅시다. 지금까지의 자습서 내용대로라면 아래와 같은 내용이 보일것입니다. :: from django.conf.urls import patterns, include, url @@ -190,7 +190,7 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 url(r'^(?P\d+)/vote/$', 'vote'), ) -아래와 같이 변경하라:: +아래와 같이 변경하세요:: from django.conf.urls import patterns, include, url from django.views.generic import DetailView, ListView @@ -214,45 +214,45 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 url(r'^(?P\d+)/vote/$', 'polls.views.vote'), ) -여기에서 제네릭 뷰 두 개를 사용하고 있다: +여기에서 제네릭 뷰 두 개를 사용하고 있습니다: :class:`~django.views.generic.list.ListView` 와 -:class:`~django.views.generic.detail.DetailView`. 이 두 개의 뷰들은 각각, "개체들의 목록을 보여주기" 와 "개체의 특정한 형식에 맞춘 세부 페이지 보여주기" 란 개념을 가지고 있다. +:class:`~django.views.generic.detail.DetailView`. 이 두 개의 뷰들은 각각, "개체들의 목록을 보여주기" 와 "개체의 특정한 형식에 맞춘 세부 페이지 보여주기" 란 개념을 가지고 있습니다. -* 각 제네릭 뷰는 제네릭 뷰가 어떤 모델에 작용할지 알아야한다 - .. 그것은 ``model`` 파라미터를 사용하여 제공된다. +* 각 제네릭 뷰는 제네릭 뷰가 어떤 모델에 작용할지 알아야합니다 + .. 그것은 ``model`` 파라미터를 사용하여 제공합니다. * :class:`~django.views.generic.list.DetailView` 제네릭 뷰는 URL에서 가져온 기본 키 값(``"pk"``\ 라 불리는)을 받을 준비를 - 하고 있다. 그래서 우리는 ``poll_id``\ 를 ``pk``\ 로 변경했다. + 하고 있습니다. 그래서 우리는 ``poll_id``\ 를 ``pk``\ 로 변경했습니다. -* 우리는 results 뷰에 ``poll_results``\ 란 이름을 추가했다, - 그렇게 하면 URL 이후에 오는 변수를 참조할 수 있게 된다.( +* 우리는 results 뷰에 ``poll_results``\ 란 이름을 추가했습니다, + 그렇게 하면 URL 이후에 오는 변수를 참조할 수 있게 되죠.( 이것에 관한 정보는 :ref:`naming URL patterns - ` 문서를 보라). 또 우리는 여기에서 :mod:`django.conf.urls`\ 의 - :func:`~django.conf.urls.url` 함수를 사용했다. 이와같은 패턴 이름을 제공하는 경우에 - :func:`~django.conf.urls.url`\ 사용은 좋은 습관이다. + ` 문서를 참고하세요). 또 :mod:`django.conf.urls`\ 의 + :func:`~django.conf.urls.url` 함수를 사용했습니다. 이와같은 패턴 이름을 제공하는 경우에 + :func:`~django.conf.urls.url`\ 사용은 좋은 습관입니다. -기본적으로 :class:`~django.views.generic.list.DetailView` 제네릭 뷰는 ``/_detail.html``\ 이라 불리는 템플릿을 사용한다. -우리는 ``"polls/poll_detail.html"`` 템플릿을 사용할 것이다. 자동생성되는 기본 템플릿 이름 대신에 특정한 템릿 이름을 사용하여 장고에게 전달하기 위해 ``template_name`` 를 사용한다. 또한 우리는 ``results`` 리스트 뷰를 위해 ``template_name``\ 를 지정해야한다 -- 비록 둘 다 같은 :class:`~django.views.generic.list.DetailView`\ 이긴 하지만. 이것은 results 뷰와 detail 뷰가 달리 표현되는 것을 보장한다. +기본적으로 :class:`~django.views.generic.list.DetailView` 제네릭 뷰는 ``/_detail.html``\ 이라 불리는 템플릿을 사용합니다. +우리는 ``"polls/poll_detail.html"`` 템플릿을 사용할 것입니다. 자동생성되는 기본 템플릿 이름 대신에 특정한 템릿 이름을 사용하여 장고에게 전달하기 위해서는 ``template_name`` 를 사용해야 합니다. 그래서 ``results`` 리스트 뷰를 위해 ``template_name``\ 를 지정했습니다 -- 비록 둘 다 같은 :class:`~django.views.generic.list.DetailView`\ 이긴 하지만. 이렇게하면 results 뷰와 detail 뷰를 다르게 표현할 수 있죠. -비슷하게, 기존 ``"polls/index.html"`` 테플릿을 사용하기위해 ``template_name``\ 을 사용해서 :class:`~django.views.generic.list.ListView`\ 에 전달한다. +비슷하게, 기존 ``"polls/index.html"`` 테플릿을 사용하기위해 ``template_name``\ 을 사용해서 :class:`~django.views.generic.list.ListView`\ 에 전달합니다. -이전 자습서에서, 탬플릿은 ``poll`` 과 ``latest_poll_list``\의 컨텍스트 변수를 포함한 컨텍스트가 제공되었다. DetailView를 위해 ``poll`` 변수는 자동으로 제공되었다 -- 장고 모델(``Poll``)을 사용했기때문에, 장고는 컨텍스트 변수를 위한 적당한 이름을 정할 수 있다. 그러나, ListView를 위해 , 자동적으로 생성되는 컨텍스트 변수는 ``poll_list``\ 이다. ``latest_poll_list``\ 를 대신 지정해서 사용하기 위해 ``context_object_name``\ 을 재정의하라.다른 방법으로, 새로운 기본 컨텍스트 변수들과 매치되는 당신만으로 템프릿으로 바꿀 수 있다. -- 그러나 단지 Django에게 당신이 원하는 변수를 전달하는 것이 훨씬 쉽다. +이전 자습서에서, 탬플릿에는 ``poll`` 과 ``latest_poll_list``\의 컨텍스트 변수를 포함한 컨텍스트가 제공되었습니다. DetailView를 위한 ``poll`` 변수는 자동으로 제공됩니다 -- Django 모델(``Poll``)을 사용하고 있기 때문에, 장고는 컨텍스트 변수에 대한 적절한 이름을 확인할 수 있습니다. 그러나, ListView를 위해, 자동적으로 생성되는 컨텍스트 변수는 ``poll_list``\ 입니다. ``poll_list`` 대신 사용하고 싶은 ``latest_poll_list``\ 를 ``context_object_name``\ 옵션에 지정하시면 됩니다. 다른 방법으로, 새로운 기본 컨텍스트 변수들과 매치되는 당신만으로 템프릿으로 바꿀 수 있습니다. -- 그러나 Django에게 당신이 원하는 변수를 전달하는 것이 훨씬 쉽습니다.(역자주:context_object_name를 지정하는 것이 훨씬 쉽다는 말입니다.) -이제 ``polls/views.py``\ 파일에서 ``index()``, ``detail()`` 그리고 ``results()`` 뷰들을 지울 수 있다.그 뷰들은 더이상 필요지 않다-- 그 뷰들은 제대릭 뷰로 대체된다. +이제 ``polls/views.py``\ 파일에서 ``index()``, ``detail()`` 그리고 ``results()`` 뷰들을 지울 수 있습니다. 그 뷰들은 더이상 필요하지 않습니다.-- 그 뷰들이 제대릭 뷰로 대체된 것입니다. -마지막으로 해야 할 것은 제네릭 뷰들의 사용을 처리하는 URL 다루기를 수정하는 것이다. 위의 vote 뷰에서, 우리의 URL들을 하드코딩하는 것을 피하기 위해 :func:`~django.core.urlresolvers.reverse` 함수를 사용했다. 이제 우린 generic view로 전환을 했으니. :func:`~django.core.urlresolvers.reverse` 함수가 새로운 generic view를 호출하도록 바꿀 필요가 있다. 우리는 더이상 view 함수를 쉽게 사용할 수 없다 -- 제네릭 뷰들은여러번 사용하거나, 사용되어질 수 있다 --그러나 우리는 우리에게 주어진 이름을 사용할 수 있다 :: +마지막으로 해야 할 것은 제네릭 뷰들의 사용을 처리하는 URL 다루기를 수정하는 것입니다. 위의 vote 뷰에서, 우리의 URL들을 하드코딩하는 것을 피하기 위해 :func:`~django.core.urlresolvers.reverse` 함수를 사용했습니다. 이제 우린 generic view로 전환을 했으니. :func:`~django.core.urlresolvers.reverse` 함수가 새로운 generic view를 호출하도록 바꿔야합니다. 더이상 우리는 단순히 view 함수를 사용할 수 없습니다 -- 제네릭 뷰들은여러번 사용하거나, 사용되어질 수 있다 --그러나 우리는 우리에게 주어진 이름을 사용할 수 있다 (역자주: 뷰를 삭제했으므로 사용할 수 없다는 말이고, 대신에 ``name``을 지정하여 제네릭 뷰를 사용할 수 있다는 말입니다.):: return HttpResponseRedirect(reverse('poll_results', args=(p.id,))) -서버를 실행하고, 제레릭 뷰를 기반으로하는 새로운 설문조사 앱을 사용해보자. +서버를 실행하고, 제레릭 뷰를 기반으로하는 새로운 설문조사 앱을 사용해봅시다. -제네릭 뷰에 대한 자세한 내용은, :doc:`generic views documentation ` 문서를 보라. +제네릭 뷰에 대한 자세한 내용은, :doc:`generic views documentation ` 문서를 보세요. 곧 올것들 =========== -당분간 이 자습서는 여기에서 끝난다. 이 자습서가 앞으로 다룰 내용들이다 : +당분간 이 자습서는 여기에서 끝납니다. 이 자습서가 앞으로 다룰 내용들입니다 : * 진보된 폼 처리 * RSS 프레임워크 사용하기 @@ -261,4 +261,4 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 * 진보된 관리자 기능: 권한 * 진보된 관리자 기능: 사용자 정의 자바스크립트 -그 동안, :doc:`where to go from here `\ 에서 몇몇 부분들을 살펴볼 수 있다. \ No newline at end of file +그 동안, :doc:`where to go from here `\ 에서 몇몇 부분들을 살펴볼 수 있습니다. \ No newline at end of file From 960809c3c8f35c42a0a73f563499a81c90a5bd15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A0=95=EC=84=B1=ED=83=9C?= Date: Wed, 22 Aug 2012 22:47:17 +0900 Subject: [PATCH 040/128] Update intro/tutorial03.txt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ROOT_URLCONF = 'mysite.urls' 부분 스핑크스 태그?? 수정 --- intro/tutorial03.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/intro/tutorial03.txt b/intro/tutorial03.txt index 8811e11..8f53ffa 100644 --- a/intro/tutorial03.txt +++ b/intro/tutorial03.txt @@ -45,6 +45,7 @@ URL 구조를 디자인 하는 것은 뷰를 작성하는 첫 번째 단계입 사용자가 Django-powered 페이지를 요청 할 때, 시스템은 Python dotted syntax에 있는 문자열을 포함하는 :setting:'ROOT_URLCONF' 설정을 참고 합니다. Django 는 URLconf 모듈을 로드 합니다. 그리고, 아래와 같은 포맷의 튜플인 모듈-레벨 변수인 ``urlpatterns``\ 를 검색합니다. :: + (regular expression, Python callback function [, optional dictionary]) Django는 첫 번째 정규표현식을 시작으로, 일치하는 결과를 찾을 때 까지 요청 받은 URL을 각각의 정규표현식과 비교하면서 리스트 아래로 내려갑니다. From 66e3c76fc2a151f092321e78582ae5b5ba099573 Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Thu, 23 Aug 2012 00:03:56 +0900 Subject: [PATCH 041/128] =?UTF-8?q?intro/whatsnext=20=EB=B2=88=EC=97=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- intro/whatsnext.txt | 388 +++++++++++++++++--------------------------- 1 file changed, 151 insertions(+), 237 deletions(-) diff --git a/intro/whatsnext.txt b/intro/whatsnext.txt index b45b0c8..fdca3ca 100644 --- a/intro/whatsnext.txt +++ b/intro/whatsnext.txt @@ -1,237 +1,151 @@ -================= -What to read next -================= - -So you've read all the :doc:`introductory material ` and have -decided you'd like to keep using Django. We've only just scratched the surface -with this intro (in fact, if you've read every single word you've still read -less than 10% of the overall documentation). - -So what's next? - -Well, we've always been big fans of learning by doing. At this point you should -know enough to start a project of your own and start fooling around. As you need -to learn new tricks, come back to the documentation. - -We've put a lot of effort into making Django's documentation useful, easy to -read and as complete as possible. The rest of this document explains more about -how the documentation works so that you can get the most out of it. - -(Yes, this is documentation about documentation. Rest assured we have no plans -to write a document about how to read the document about documentation.) - -Finding documentation -===================== - -Django's got a *lot* of documentation -- almost 200,000 words -- so finding what -you need can sometimes be tricky. A few good places to start are the :ref:`search` -and the :ref:`genindex`. - -Or you can just browse around! - -How the documentation is organized -================================== - -Django's main documentation is broken up into "chunks" designed to fill -different needs: - -* The :doc:`introductory material ` is designed for people new - to Django -- or to Web development in general. It doesn't cover anything - in depth, but instead gives a high-level overview of how developing in - Django "feels". - -* The :doc:`topic guides `, on the other hand, dive deep into - individual parts of Django. There are complete guides to Django's - :doc:`model system `, :doc:`template engine - `, :doc:`forms framework `, and much - more. - - This is probably where you'll want to spend most of your time; if you work - your way through these guides you should come out knowing pretty much - everything there is to know about Django. - -* Web development is often broad, not deep -- problems span many domains. - We've written a set of :doc:`how-to guides ` that answer - common "How do I ...?" questions. Here you'll find information about - :doc:`generating PDFs with Django `, :doc:`writing - custom template tags `, and more. - - Answers to really common questions can also be found in the :doc:`FAQ - `. - -* The guides and how-to's don't cover every single class, function, and - method available in Django -- that would be overwhelming when you're - trying to learn. Instead, details about individual classes, functions, - methods, and modules are kept in the :doc:`reference `. This is - where you'll turn to find the details of a particular function or - whathaveyou. - -* Finally, there's some "specialized" documentation not usually relevant to - most developers. This includes the :doc:`release notes `, - :doc:`documentation of obsolete features `, - :doc:`internals documentation ` for those who want to add - code to Django itself, and a :doc:`few other things that simply don't fit - elsewhere `. - - -How documentation is updated -============================ - -Just as the Django code base is developed and improved on a daily basis, our -documentation is consistently improving. We improve documentation for several -reasons: - -* To make content fixes, such as grammar/typo corrections. - -* To add information and/or examples to existing sections that need to be - expanded. - -* To document Django features that aren't yet documented. (The list of - such features is shrinking but exists nonetheless.) - -* To add documentation for new features as new features get added, or as - Django APIs or behaviors change. - -Django's documentation is kept in the same source control system as its code. It -lives in the `django/trunk/docs`_ directory of our Subversion repository. Each -document online is a separate text file in the repository. - -.. _django/trunk/docs: https://code.djangoproject.com/browser/django/trunk/docs - -Where to get it -=============== - -You can read Django documentation in several ways. They are, in order of -preference: - -On the Web ----------- - -The most recent version of the Django documentation lives at -http://docs.djangoproject.com/en/dev/. These HTML pages are generated -automatically from the text files in source control. That means they reflect the -"latest and greatest" in Django -- they include the very latest corrections and -additions, and they discuss the latest Django features, which may only be -available to users of the Django development version. (See "Differences between -versions" below.) - -We encourage you to help improve the docs by submitting changes, corrections and -suggestions in the `ticket system`_. The Django developers actively monitor the -ticket system and use your feedback to improve the documentation for everybody. - -Note, however, that tickets should explicitly relate to the documentation, -rather than asking broad tech-support questions. If you need help with your -particular Django setup, try the `django-users mailing list`_ or the `#django -IRC channel`_ instead. - -.. _ticket system: https://code.djangoproject.com/simpleticket?component=Documentation -.. _django-users mailing list: http://groups.google.com/group/django-users -.. _#django IRC channel: irc://irc.freenode.net/django - -In plain text -------------- - -For offline reading, or just for convenience, you can read the Django -documentation in plain text. - -If you're using an official release of Django, note that the zipped package -(tarball) of the code includes a ``docs/`` directory, which contains all the -documentation for that release. - -If you're using the development version of Django (aka the Subversion "trunk"), -note that the ``docs/`` directory contains all of the documentation. You can -``svn update`` it, just as you ``svn update`` the Python code, in order to get -the latest changes. - -You can check out the latest Django documentation from Subversion using this -shell command: - -.. code-block:: bash - - $ svn co https://code.djangoproject.com/svn/django/trunk/docs/ django_docs - -One low-tech way of taking advantage of the text documentation is by using the -Unix ``grep`` utility to search for a phrase in all of the documentation. For -example, this will show you each mention of the phrase "max_length" in any -Django document: - -.. code-block:: bash - - $ grep -r max_length /path/to/django/docs/ - -As HTML, locally ----------------- - -You can get a local copy of the HTML documentation following a few easy steps: - -* Django's documentation uses a system called Sphinx__ to convert from - plain text to HTML. You'll need to install Sphinx by either downloading - and installing the package from the Sphinx Web site, or with ``pip``: - - .. code-block:: bash - - $ sudo pip install Sphinx - -* Then, just use the included ``Makefile`` to turn the documentation into - HTML: - - .. code-block:: bash - - $ cd path/to/django/docs - $ make html - - You'll need `GNU Make`__ installed for this. - - If you're on Windows you can alternatively use the included batch file: - - .. code-block:: bat - - cd path\to\django\docs - make.bat html - -* The HTML documentation will be placed in ``docs/_build/html``. - -.. note:: - - Generation of the Django documentation will work with Sphinx version 0.6 - or newer, but we recommend going straight to Sphinx 1.0.2 or newer. - -__ http://sphinx.pocoo.org/ -__ http://www.gnu.org/software/make/ - -Differences between versions -============================ - -As previously mentioned, the text documentation in our Subversion repository -contains the "latest and greatest" changes and additions. These changes often -include documentation of new features added in the Django development version --- the Subversion ("trunk") version of Django. For that reason, it's worth -pointing out our policy on keeping straight the documentation for various -versions of the framework. - -We follow this policy: - -* The primary documentation on djangoproject.com is an HTML version of the - latest docs in Subversion. These docs always correspond to the latest - official Django release, plus whatever features we've added/changed in - the framework *since* the latest release. - -* As we add features to Django's development version, we try to update the - documentation in the same Subversion commit transaction. - -* To distinguish feature changes/additions in the docs, we use the phrase: - "New in version X.Y", being X.Y the next release version (hence, the one - being developed). - -* Documentation for a particular Django release is frozen once the version - has been released officially. It remains a snapshot of the docs as of the - moment of the release. We will make exceptions to this rule in - the case of retroactive security updates or other such retroactive - changes. Once documentation is frozen, we add a note to the top of each - frozen document that says "These docs are frozen for Django version XXX" - and links to the current version of that document. - -* The `main documentation Web page`_ includes links to documentation for - all previous versions. - -.. _main documentation Web page: http://docs.djangoproject.com/en/dev/ +================= +더 읽을 거리 +================= + +:doc:`소개 자료 `\ 를 모두 읽고 Django를 사용하기로 하셨군요. 우리는 겉핡기를 했을 뿐입니다(사실, 그걸 다 읽었다고 해도 전체 문서의 십분의 일도 읽지 못한 셈입니다). + +자 그럼 다음은 무엇이 있을까요. + +지금까지는 항상 무언가를 직접 행하면서 배워왔습니다. 이제부터는 스스로 프로젝트를 할 수 있을 만큼 지식을 쌓아나가야 합니다. 새로운 트릭을 배우고 싶다면 문서를 읽는 수고를 들일 필요가 있습니다. + +우리는 Django의 문서를 유용하면서도 가능한 읽기 쉽도록 만들기 위해 많은 노력을 기울였습니다. 이 문서의 나머지 부분은 어떻게 문서를 최대한 활용할 수 있는지를 설명합니다. + +(네, 이것은 문서에 대한 문서입니다. 읽는 방법에 대한 문서를 쓸 계획은 없으니 안심하세요.) + +문서 찾기 +===================== + +Django에는 -- 거의 이십만 개의 단어로 이루어진 -- *많은* 문서가 있기 때문에 때로는 필요한 것을 찾기가 힘들 수도 있습니다. :ref:`search`\ 나 :ref:`genindex`\ 에서 시작하는 것도 좋은 방법입니다. + +그냥 둘러보셔도 좋구요! + +문서 구성 방식 +================================== + +Django의 주요 문서는 필요에 따라 몇몇 "덩어리"로 나뉘어져 있습니다. + +* doc:`소개 자료 `\ 는 Django 또는 일반적인 웹 개발을 처음 접하는 사람들을 위해 만들었습니다. 깊은 내용을 다루지는 않지만, 그 대신에 Django의 "느낌"이 나게끔 개발할 수 있도록 높은 수준에서의 개요를 제공합니다. + +* 한편 :doc:`주제별 안내서 `\ 는, Django의 각 부분을 심도있게 탐구합니다. Django의 :doc:`모델 시스템 `, :doc:`템플릿 엔진 `, :doc:`폼 프레임워크 ` 등 각각의 주제에 대한 완전한 안내서입니다. + + 이것은 아마 당신이 시간 대부분을 보내고자 할 것입니다. 이 안내서를 통해 방법을 알고자한다면 Django 대해 알아야 할 거의 모든 것이 나와 있습니다. + +* 웹 개발은 깊이 있지 않지만 대개 광범위합니다 -- 문제는 많은 영역에 놓여있습니다. 우리는 :doc:`하우투 가이드 `\ 를 일반적인 "~을 어떻게 할까? 하는 질문의 답으로 글을 썼습니다. 여러분은 :doc:`Django에서 PDF 생성하기 `\ 와 :doc:`커스텀 템플릿 태그 작성법 ` 등의 정보를 찾아볼 수 있을 것입니다. + + 일반적인 질문에 대한 답변도 :doc:`FAQ `\ 에서 또한 찾을 수 있을 것입니다. + +* 이 안내서나 하우투는 Django에서 사용 가능한 모든 싱글 클래스, 함수, 메소드를 포함하지 않습니다. 그것은 당신이 Django를 배우려고 할때 많은 부분을 차지할 것입니다. 대신, 각 클래스, 함수, 메서드 및 모듈에 대한 자세한 내용은 :doc:`참조 `\ 를 유지합니다. 이것은 당신은 특정한 기능이나 whathaveyou의 세부 정보를 찾는 것 가능한 곳입니다. + +* 마지막으로, 일반적으로 대부분의 개발자와 관련이 없는 "특수한" 문서들이 존재합니다. :doc:`릴리즈 노트 `, :doc:`오래된 기능의 문서 `, :doc:`내부 문서 `와 같이 Django 자체에 코드를 추가하려는 사람들에게 필요한 문서도 있고, :doc:`특정한 범주에 묶기 어려운 기타 문서들 `\ 도 있습니다. + + +문서는 어떻게 업데이트되는가 +============================ + +Django의 코드 기반이 하루하루 개발되고 개선되는 것처럼, 문서도 지속적으로 개선이 이루어집니다. 우리는 다음과 같은 몇 가지의 이유로 문서를 개선해나갑니다. + +* 문법 오류 또는 오탈자와 같은 내용상의 수정을 위해. + +* 보충이 필요한 기존 섹션에 정보 및 예제를 추가하기 위해. + +* 아직 문서화되지 않은 Django 기능을 문서화하기 위해.(목록이 점점 줄어들고 있기는 하지만 여전히 남아있습니다.) + +* 새로운 Django API 나 적용이 바뀌었을때 새로운 기능을 문서에 추가. + +Django의 문서는 코드와 동일한 소스 제어 시스템에 보관합니다. 그것은 서브버전 저장소의 `django/trunk/docs`_ 디렉토리에 있습니다. 각 온라인 문서는 저장소에 별도로 존재하는 텍스트 파일입니다. + +.. _django/trunk/docs: https://code.djangoproject.com/browser/django/trunk/docs + +구할 수 있는 곳 +=============== + +Django 문서는 다음과 같은 다양한 방법을 통해 구해서 읽을 수 있습니다. + +웹에서 +---------- + +Django 문서의 가장 최신 버전은 http://docs.djangoproject.com/en/dev/\ 에 있습니다. 이런 HTML 페이지는 소스 컨트롤 내 텍스트 파일에서 자동으로 생성됩니다. 그것은 Django 내에서 "최신과 최고"를 반영되었다는 의미입니다 -- 그것은 가장 최신의 수정이나 추가, Django 개발 버전 사용자가 최신 Django 기능 토론합니다. (아래의 "버전 간의 차이점" 참조.) + +우리는 당신이 '티켓 시스템'\ 에서 변경, 수정 및 제안을 제출하여 문서를 개선하는 도움되는 것을 권장합니다. Django 개발자들이 적극적으로 티켓 시스템을 모니터링하고 모든 사람에 대한 문서를 개선하기 위해 당신의 피드백을 사용합니다. + +그러나 그 티켓은 광범위한 기술 지원 질문보다는 명시적으로 문서와 관련있을 것임에 주의하세요. 당신은 특정 Django 설정에 도움이 필요한 경우 티켓보다는 `django-users 메일링 리스트`_ 또는 `#django IRC 채널`_\ 을 활용하시기 바랍니다. + +.. _티켓 시스템: https://code.djangoproject.com/simpleticket?component=Documentation +.. _django-users 메일링 리스트: http://groups.google.com/group/django-users +.. _#django IRC 채널: irc://irc.freenode.net/django + +일반적인 텍스트 +------------- + +오프라인으로 읽기 위해서나, 혹은 단순히 편의상 일반 텍스트로 Django 문서를 읽을 수 있습니다. + +당신은 Django의 공식 릴리즈를 사용하는 경우, 코드에 포함된 ``docs/`` 디렉토리의 압축된 패키지(tarball), 이것은 해당 릴리즈에 대한 모든 문서를 포함합니다. + +당신이 Django의 개발 버전을 사용한다면(즉, 서브버전 "trunk"), ``docs/`` 디렉토리에 모든 문서가 있습니다. 당신은 최신의 변경 사항을 얻기 위해 ``svn update`` 를 할수 있고 마찬가지로 파이썬 코드에서 ``svn update`` 할 수 있습니다. + +당신은 이 쉘 명령을 사용하여 서브버전으로 부터 최신의 Django 문서를 확인할 수 있습니다. + +.. code-block:: bash + + $ svn co https://code.djangoproject.com/svn/django/trunk/docs/ django_docs + +텍스트 문서를 활용하는 낮은 기술은 모든 문서에서 구문 검색을 위해 유닉스의 ``grep`` 유틸리티를 사용하는 것입니다. 예를 들어, 이것은 당신에게 어떤 Django 문서에서 구문 "MAX_LENGTH"의 각 언급을 보여줍니다. + +.. code-block:: bash + + $ grep -r max_length /path/to/django/docs/ + +로컬 HTML로 +---------------- + +당신은 몇가지 간단한 단계를 거쳐 HTML 문서를 로컬에 가져올 수 있습니다. + +* Django 설명서는 HTML로 일반 텍스트로 변환하는 Sphinx__\ 라는 시스템을 사용합니다. 당신은 Sphinx 웹 사이트에서 또는 ``pip``\ 으로 패키지를 다운로드하고 설치하여 Sphinx를 설치해야 합니다. + + .. code-block:: bash + + $ sudo pip install Sphinx + +그후, HTML에서 문서를 바꾸기 위한 포함된 ``Makefile``\ 을 사용하면 됩니다. + + .. code-block:: bash + + $ cd path/to/django/docs + $ make html + + 이것을 위해 `GNU Make`__\ 를 설치할 필요가 있습니다. + + 만약 당신이 윈도우즈상에 있다면 포함된 배치(batch) 파일을 사용할 수 있습니다. + + .. code-block:: bat + + cd path\to\django\docs + make.bat html + +* HTML 문서는 ``docs/_build/html``\ 에 위치하게 될 것입니다. + +.. note:: + + Django 문서의 생성은 Sphinx 버전 0.6 이상에서 작동하기는 하지만, 우리는 Sphinx 1.0.2 이상 버전으로 곧장 가는 것을 추천합니다. + +__ http://sphinx.pocoo.org/ +__ http://www.gnu.org/software/make/ + +버전 간의 차이점 +============================ + +앞서 이야기 했듯이, 우리의 서브버전 저장소의 텍스트 문서는 "최신 그리고 최고" 변경 및 추가를 포함하고 있습니다. 이러한 변경은 가끔 Django 개발 버전에 새로운 기능 추가의 문서를 포함합니다. -- Django의 서브버전 ("trunk") 버전. 그러한 연유로, 다양한 버전의 프레임워크를 위해 올바른 문서를 지키는 일에 대한 우리의 정책을 짚고 넘어가도록 하겠습니다. + +우리의 정책은 다음과 같습니다. + +* djangoproject.com에 대한 주요 문서의 서브버전에서 최신 문서의 HTML 버전입니다. 이 문서는 항상 최신 공식 Django 릴리스와 어떤 기능의 최신 릴리스 *이후* 프레임워크에 추가/변경 사항을 일치시킵니다. + +* 우리는 Django의 개발 버전에 기능을 추가하기 때문에, 우리는 같은 서브버전에 커밋 트랜잭션의 문서를 업데이트하려고 합니다. + +* 문서의 기능 변경 및 추가 사항을 구분하기 위해 "New in version X.Y"와 같은 구문를 사용하며, X.Y는 다음 릴리즈 버전이 됩니다(즉, 현재 개발 중입니다). + +* 특정 Django 릴리즈 문서는 버전이 공식적으로 릴리즈 되고 나면 동결됩니다. 이 릴리스 시점의 문서의 스냅샷이 남습니다. 우리는 소급하여 보안 업데이트하거나 다른 소급 변경의 경우에는 이 규칙에 대한 예외를 적용할 것입니다. 일단 문서가 동결되고, 우리는 "이 문서는 Django 버전 XXX에 의해 동결되었다"와 해당 문서의 현재 버전에 링크 각 동결 문서의 상단에 메모를 추가합니다. + +* `메인 문서 웹 페이지`_\ 는 모든 이전 버전의 문서에 대한 링크를 포함합니다. + +.. _메인 문서 웹 페이지: http://docs.djangoproject.com/en/dev/ From ed7c49a4c0576e495561b4bc51b624d2cd1cb895 Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Thu, 23 Aug 2012 09:54:41 +0900 Subject: [PATCH 042/128] =?UTF-8?q?intro/whatsnext=20=EA=B5=90=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- intro/whatsnext.txt | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/intro/whatsnext.txt b/intro/whatsnext.txt index fdca3ca..48377fe 100644 --- a/intro/whatsnext.txt +++ b/intro/whatsnext.txt @@ -24,19 +24,19 @@ Django에는 -- 거의 이십만 개의 단어로 이루어진 -- *많은* 문 Django의 주요 문서는 필요에 따라 몇몇 "덩어리"로 나뉘어져 있습니다. -* doc:`소개 자료 `\ 는 Django 또는 일반적인 웹 개발을 처음 접하는 사람들을 위해 만들었습니다. 깊은 내용을 다루지는 않지만, 그 대신에 Django의 "느낌"이 나게끔 개발할 수 있도록 높은 수준에서의 개요를 제공합니다. +* :doc:`소개 자료 `\ 는 Django 또는 일반적인 웹 개발을 처음 접하는 사람들을 위해 만들었습니다. 깊은 내용을 다루지는 않지만, 그 대신에 Django의 "느낌"이 나게끔 개발할 수 있도록 높은 수준에서의 개요를 제공합니다. * 한편 :doc:`주제별 안내서 `\ 는, Django의 각 부분을 심도있게 탐구합니다. Django의 :doc:`모델 시스템 `, :doc:`템플릿 엔진 `, :doc:`폼 프레임워크 ` 등 각각의 주제에 대한 완전한 안내서입니다. 이것은 아마 당신이 시간 대부분을 보내고자 할 것입니다. 이 안내서를 통해 방법을 알고자한다면 Django 대해 알아야 할 거의 모든 것이 나와 있습니다. -* 웹 개발은 깊이 있지 않지만 대개 광범위합니다 -- 문제는 많은 영역에 놓여있습니다. 우리는 :doc:`하우투 가이드 `\ 를 일반적인 "~을 어떻게 할까? 하는 질문의 답으로 글을 썼습니다. 여러분은 :doc:`Django에서 PDF 생성하기 `\ 와 :doc:`커스텀 템플릿 태그 작성법 ` 등의 정보를 찾아볼 수 있을 것입니다. +* 웹 개발은 깊이 있지 않지만 대개 광범위합니다 -- 문제는 많은 영역에 놓여있습니다. 우리는 :doc:`하우투 가이드 `\ 를 일반적인 "~을 어떻게 할까?" 하는 질문의 답으로 글을 썼습니다. 여러분은 :doc:`Django에서 PDF 생성하기 `\ 와 :doc:`맞춤 템플릿 태그 작성법 ` 등의 정보를 찾아볼 수 있을 것입니다. - 일반적인 질문에 대한 답변도 :doc:`FAQ `\ 에서 또한 찾을 수 있을 것입니다. + 일반적인 질문에 대한 답변도 :doc:`FAQ `\ 에서 찾을 수 있을 것입니다. -* 이 안내서나 하우투는 Django에서 사용 가능한 모든 싱글 클래스, 함수, 메소드를 포함하지 않습니다. 그것은 당신이 Django를 배우려고 할때 많은 부분을 차지할 것입니다. 대신, 각 클래스, 함수, 메서드 및 모듈에 대한 자세한 내용은 :doc:`참조 `\ 를 유지합니다. 이것은 당신은 특정한 기능이나 whathaveyou의 세부 정보를 찾는 것 가능한 곳입니다. +* 이 안내서나 하우투는 Django에서 사용 가능한 모든 클래스, 함수, 메소드를 하나하나 다루지는 않습니다. 그것은 당신이 Django를 배우려고 할때 많은 부분을 차지할 것입니다. 대신, 각 클래스, 함수, 메서드 및 모듈에 대한 자세한 내용은 :doc:`참조 `\ 에 있습니다. 그곳에서 특정한 기능에 대한 세부 정보를 찾을 수 있습니다. -* 마지막으로, 일반적으로 대부분의 개발자와 관련이 없는 "특수한" 문서들이 존재합니다. :doc:`릴리즈 노트 `, :doc:`오래된 기능의 문서 `, :doc:`내부 문서 `와 같이 Django 자체에 코드를 추가하려는 사람들에게 필요한 문서도 있고, :doc:`특정한 범주에 묶기 어려운 기타 문서들 `\ 도 있습니다. +* 마지막으로, 일반적으로 대부분의 개발자와 관련이 없는 "특수한" 문서들이 존재합니다. :doc:`릴리즈 노트 `, :doc:`쓸모 없는 기능에 대한 문서 `, :doc:`내부 문서 `와 같이 Django 자체에 코드를 추가하려는 사람들에게 필요한 문서도 있고, :doc:`특정한 범주에 묶기 어려운 기타 문서들 `\ 도 있습니다. 문서는 어떻게 업데이트되는가 @@ -126,7 +126,7 @@ Django 문서의 가장 최신 버전은 http://docs.djangoproject.com/en/dev/\ .. note:: - Django 문서의 생성은 Sphinx 버전 0.6 이상에서 작동하기는 하지만, 우리는 Sphinx 1.0.2 이상 버전으로 곧장 가는 것을 추천합니다. + Django 문서의 생성은 Sphinx 버전 0.6 이상에서 작동하기는 하지만, 우리는 Sphinx 1.0.2 이상 버전으로 곧장 가는 것을 권장합니다. __ http://sphinx.pocoo.org/ __ http://www.gnu.org/software/make/ From 3fc10fc4878af1945ca777d2f3139f687f0f1e07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A0=95=EC=84=B1=ED=83=9C?= Date: Thu, 23 Aug 2012 13:27:16 +0900 Subject: [PATCH 043/128] Update intro/tutorial04.txt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 교정 --- intro/tutorial04.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/intro/tutorial04.txt b/intro/tutorial04.txt index d934e76..3866e0a 100644 --- a/intro/tutorial04.txt +++ b/intro/tutorial04.txt @@ -233,15 +233,15 @@ HTML ```` 요소를 포함하고 있는 앞 장에서 사용한 설문조 :func:`~django.conf.urls.url`\ 사용은 좋은 습관입니다. 기본적으로 :class:`~django.views.generic.list.DetailView` 제네릭 뷰는 ``/_detail.html``\ 이라 불리는 템플릿을 사용합니다. -우리는 ``"polls/poll_detail.html"`` 템플릿을 사용할 것입니다. 자동생성되는 기본 템플릿 이름 대신에 특정한 템릿 이름을 사용하여 장고에게 전달하기 위해서는 ``template_name`` 를 사용해야 합니다. 그래서 ``results`` 리스트 뷰를 위해 ``template_name``\ 를 지정했습니다 -- 비록 둘 다 같은 :class:`~django.views.generic.list.DetailView`\ 이긴 하지만. 이렇게하면 results 뷰와 detail 뷰를 다르게 표현할 수 있죠. +우리는 ``"polls/poll_detail.html"`` 템플릿을 사용할 것입니다. 자동생성되는 기본 템플릿 이름 대신에 특정한 템플릿 이름을 사용하여 장고에게 전달하기 위해서는 ``template_name`` 를 사용해야 합니다. 그래서 ``results`` 리스트 뷰를 위해 ``template_name``\ 를 지정했습니다 -- 비록 둘 다 같은 :class:`~django.views.generic.list.DetailView`\ 이긴 하지만. 이렇게하면 results 뷰와 detail 뷰를 다르게 표현할 수 있죠. 비슷하게, 기존 ``"polls/index.html"`` 테플릿을 사용하기위해 ``template_name``\ 을 사용해서 :class:`~django.views.generic.list.ListView`\ 에 전달합니다. -이전 자습서에서, 탬플릿에는 ``poll`` 과 ``latest_poll_list``\의 컨텍스트 변수를 포함한 컨텍스트가 제공되었습니다. DetailView를 위한 ``poll`` 변수는 자동으로 제공됩니다 -- Django 모델(``Poll``)을 사용하고 있기 때문에, 장고는 컨텍스트 변수에 대한 적절한 이름을 확인할 수 있습니다. 그러나, ListView를 위해, 자동적으로 생성되는 컨텍스트 변수는 ``poll_list``\ 입니다. ``poll_list`` 대신 사용하고 싶은 ``latest_poll_list``\ 를 ``context_object_name``\ 옵션에 지정하시면 됩니다. 다른 방법으로, 새로운 기본 컨텍스트 변수들과 매치되는 당신만으로 템프릿으로 바꿀 수 있습니다. -- 그러나 Django에게 당신이 원하는 변수를 전달하는 것이 훨씬 쉽습니다.(역자주:context_object_name를 지정하는 것이 훨씬 쉽다는 말입니다.) +이전 자습서에서, 탬플릿에는 ``poll`` 과 ``latest_poll_list``\의 컨텍스트 변수를 포함한 컨텍스트가 제공되었습니다. DetailView를 위한 ``poll`` 변수는 자동으로 제공됩니다 -- Django 모델(``Poll``)을 사용하고 있기 때문에, 장고는 컨텍스트 변수에 대한 적절한 이름을 확인할 수 있습니다. 그러나, ListView를 위해, 자동적으로 생성되는 컨텍스트 변수는 ``poll_list``\ 입니다. ``poll_list`` 대신 사용하고 싶은 ``latest_poll_list``\ 를 ``context_object_name``\ 옵션에 지정하시면 됩니다. 다른 방법으로, 새로운 기본 컨텍스트 변수들과 매치되는 당신만으로 템플릿으로 바꿀 수 있습니다. -- 그러나 Django에게 당신이 원하는 변수를 전달하는 것이 훨씬 쉽습니다.(역자주:context_object_name를 지정하는 것이 훨씬 쉽다는 말입니다.) 이제 ``polls/views.py``\ 파일에서 ``index()``, ``detail()`` 그리고 ``results()`` 뷰들을 지울 수 있습니다. 그 뷰들은 더이상 필요하지 않습니다.-- 그 뷰들이 제대릭 뷰로 대체된 것입니다. -마지막으로 해야 할 것은 제네릭 뷰들의 사용을 처리하는 URL 다루기를 수정하는 것입니다. 위의 vote 뷰에서, 우리의 URL들을 하드코딩하는 것을 피하기 위해 :func:`~django.core.urlresolvers.reverse` 함수를 사용했습니다. 이제 우린 generic view로 전환을 했으니. :func:`~django.core.urlresolvers.reverse` 함수가 새로운 generic view를 호출하도록 바꿔야합니다. 더이상 우리는 단순히 view 함수를 사용할 수 없습니다 -- 제네릭 뷰들은여러번 사용하거나, 사용되어질 수 있다 --그러나 우리는 우리에게 주어진 이름을 사용할 수 있다 (역자주: 뷰를 삭제했으므로 사용할 수 없다는 말이고, 대신에 ``name``을 지정하여 제네릭 뷰를 사용할 수 있다는 말입니다.):: +마지막으로 해야 할 것은 제네릭 뷰들의 사용을 처리하는 URL 다루기를 수정하는 것입니다. 위의 vote 뷰에서, 우리의 URL들을 하드코딩하는 것을 피하기 위해 :func:`~django.core.urlresolvers.reverse` 함수를 사용했습니다. 이제 우린 generic view로 전환을 했으니. :func:`~django.core.urlresolvers.reverse` 함수가 새로운 generic view를 호출하도록 바꿔야합니다. 더이상 우리는 단순히 view 함수를 사용할 수 없습니다 -- 제네릭 뷰들은 여러번 사용하거나, 사용되어질 수 있다 --그러나 우리는 우리에게 주어진 이름을 사용할 수 있다 (역자주: 뷰를 삭제했으므로 사용할 수 없다는 말이고, 대신에 ``name``\ 을 지정하여 제네릭 뷰를 사용할 수 있다는 말입니다.):: return HttpResponseRedirect(reverse('poll_results', args=(p.id,))) From 1dbe014328d170c6b461aae57ea42df287437516 Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Fri, 24 Aug 2012 20:01:53 +0900 Subject: [PATCH 044/128] =?UTF-8?q?intro/install=20=EC=9D=B8=EC=BD=94?= =?UTF-8?q?=EB=94=A9=20=EC=98=A4=EB=A5=98=20=ED=95=B4=EA=B2=B0=20=EB=B0=8F?= =?UTF-8?q?=20=EA=B5=90=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- intro/install.txt | 71 +++++++++++++++++++---------------------------- 1 file changed, 29 insertions(+), 42 deletions(-) diff --git a/intro/install.txt b/intro/install.txt index d023b19..1d0b6ee 100644 --- a/intro/install.txt +++ b/intro/install.txt @@ -1,86 +1,73 @@ - ġ ȳ -=================== +빠른 설치 안내 +=================== -Django ϱ ؼ ġ ʿմϴ. 츮 :doc:` ġ Ϻ ̵ ` ϰ , ȳ ϰ ּ ġ ʿ մϴ. +Django를 사용하기 위해선 설치가 필요합니다. 여기서는 소개를 위해 필요한 최소한의 설치 방법을 간단히 안내합니다. 자세한 설치 방법에 대해서는 :doc:`설치 완벽 안내서 `\ 를 참조하세요. -̽ ġϱ +파이썬 설치하기 -------------- -Django ̽ ӿũ, Django ̽ ʿ մϴ. ̽ 2.5 ~ 2.7 մϴ.(̽ 3.0 ȣȯ ʱ⿡, -Django ̽ 3.0 ϴ; ̽ 3.0 ڼ Ȯ ּ. :doc:`Django FAQ -`) ̽ 淮 ̽ SQLite_ ϰ ֱ⿡, ͵̽ ʿ ʽϴ. +Django는 파이썬 웹 프레임워크이므로, 파이썬을 필요로 합니다. Django에서는 파이썬 2.5 ~ 2.7 버전을 사용하며, 해당 버전의 파이썬에는 경량 데이터 베이스인 SQLite_\ 이 포함되어 있기에, 데이터데이스에 대한 설정이 따로 필요하지 않습니다.(파이썬 3.0과의 하위 호환성이 보장되지 않기에, Django에서는 파이썬 3.0을 사용할 수 없습니다. 파이썬 3.0 버전 지원에 대한 좀 더 자세한 사항은 :doc:`Django FAQ `\ 를 참고하세요.) -.. _sqlite Ʈ ֽϴ. http://sqlite.org/ +.. _sqlite: http://sqlite.org/ -̽ Ʈ ֽϴ. http://www.python.org. Mac OS X Ѵٸ, ̹ ġǾ ֽϴ. +파이썬은 http://www.python.org\ 에서 구할 수 있습니다. 만약 Mac OS X나 리눅스를 사용한다면, 이미 설치되어 있을 수도 있습니다. -.. ::Jython Django +.. admonition:: Django on Jython - Jython_ (ڹ ÷ Python) Ѵٸ -  ߰ ġ ʿմϴ. :doc:`/howto/jython` ڼ ֽϴ. + 만약 Jython_\ (자바 플랫폼을 위해 구현된 Python)을 사용한다면 몇 가지 추가 설치가 필요합니다. :doc:`/howto/jython`\ 를 참고하세요. -.. _jython Ʈ Դϴ. http://www.jython.org/ +.. _jython: http://www.jython.org/ -̽ Ȯϰ ġ Ǿ ִٸ, 'python' ɾ Է , ǥð Դϴ. +파이썬이 설치되어 있는지는, 쉘에서 ``python`` 명령어를 입력하여 다음과 같이 표시되는 것으로 확인할 수 있습니다. Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> - ̽ +데이터베이스 설정 ----------------- -̽ 2.5 ̻ ġǾ ִٸ ʾƵ ˴ϴ. +파이썬 2.5 버전 이상이 설치되어 있다면 이 부분을 건너뛰어도 됩니다. -PostgreSQL,MySQL, Oracle ū ͺ̽ ʿϴٸ, :ref:` ̽ ġ -` ϼ. +파이썬 2.5보다 낮은 버전을 사용한다거나, PostgreSQL, MySQL, Oracle과 같은 "큰" 데이터베이스에서 동작이 필요하다면, :ref:`데이터 베이스 설치 정보 +`\ 를 참고하세요. - Django +이전 Django 버전 제거 --------------------------------- - Django ġǾ ִٸ ׷̵尡 ʿմϴ. ּ. :ref:`ο ġ Django ϱ `. +이전 버전의 Django로부터 업그레이드하고자 한다면, :ref:`새로운 버전을 설치하기 전에 이전 버전의 Django를 제거 `\ 하여야 합니다. -Django ġϱ +Django 설치하기 -------------- -Django ġ ϱ 3 ɼ: +Django를 설치하는 데에는 다음과 같은 세 가지의 쉬운 방법이 있습니다. -* Django ġϱ :doc:` ü ϴ ġϱ - `. ̰ - ü ϴ Django ġϱ ɼԴϴ. +* :doc:`운영체제에서 제공하는 Django 버전 `\ 을 설치합니다. Django와 함께 배포되는 운영체제를 사용하는 경우에 가장 빠르게 구성할 수 있는 방법입니다. -* :ref:` ġϱ`. ̰ - Django ణ Ҿϴٸ - ֽ Django ġϴ ּ ̴. +* :ref:` 공식 릴리스 설치하기 `. 약간 지나간 버전이라 할지라도 안정적인 Django 버전을 원하는 사용자에게 최선의 선택입니다. -* :ref: ֽ ġϱ - `. ̰ ֽŰ ְ ο ڵ ࿡ - ڵ鿡 Դϴ. +* :ref: 최신 개발 버전 설치하기 `. 따끈따끈한 최신의 코드를 실행시키는 데에 주저함이 없는 사용자에게는 최선의 선택이 될 것입니다. -.. :: ̿ϰ ִ Django - شϴ Ȯϼ! +.. admonition:: 문서를 읽으실 때는 항상 이용하고 있는 Django의 버전에 맞는지 확인하세요! - ù °, ° ܰ ϳ ϸ ** ο ** ǥõ - Ϻκ Դϴ.  ÷ - ̸, - ȣȯ ֽϴ. + 위의 첫 번째나 두 번째 방법을 선택하신 경우에는 문서에서 **new in development version**\ 으로 표시된 부분은 쳐다보지 마세요. 그렇게 표시된 부분은 개발 버전에서만 사용할 수 있는 기능이므로, 공식 릴리즈 버전과는 호환이 되지 않을 수도 있습니다. -Ȯ +확인 --------- -Django Ȯϰ ġ Ǿ ִ, 'python' ɾ Է ϸ ̽㿡 ֽϴ. -̽ ޽ Django Դϴ. Then at the Python prompt, try to import Django:: +파이썬에서 Django가 보이는지 확인하려면, 쉘에서 ``python`` 명령어를 입력한 다음, Django를 임포트해봅니다. >>> import django >>> print django.get_version() 1.3 -!---------- +끝! +---------- - ϴ. ̵ϼ~ :doc:` ڽ(tutorial) ̵ϱ`. +이제 끝났습니다. :doc:`자습서를 읽어보세요 `. From f8c1a28bc7ec70b2816f323c8e4520500ca7f3ae Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Fri, 24 Aug 2012 20:17:37 +0900 Subject: [PATCH 045/128] =?UTF-8?q?intro/install=20=EA=B5=90=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- intro/install.txt | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/intro/install.txt b/intro/install.txt index 1d0b6ee..fc662d5 100644 --- a/intro/install.txt +++ b/intro/install.txt @@ -6,7 +6,7 @@ Django를 사용하기 위해선 설치가 필요합니다. 여기서는 소개 파이썬 설치하기 -------------- -Django는 파이썬 웹 프레임워크이므로, 파이썬을 필요로 합니다. Django에서는 파이썬 2.5 ~ 2.7 버전을 사용하며, 해당 버전의 파이썬에는 경량 데이터 베이스인 SQLite_\ 이 포함되어 있기에, 데이터데이스에 대한 설정이 따로 필요하지 않습니다.(파이썬 3.0과의 하위 호환성이 보장되지 않기에, Django에서는 파이썬 3.0을 사용할 수 없습니다. 파이썬 3.0 버전 지원에 대한 좀 더 자세한 사항은 :doc:`Django FAQ `\ 를 참고하세요.) +Django는 파이썬 웹 프레임워크이므로, 파이썬을 필요로 합니다. Django에서는 파이썬 2.5 ~ 2.7 버전을 사용하며, 해당 버전의 파이썬에는 경량 데이터베이스인 SQLite_\ 가 포함되어 있기에, 데이터데이스에 대한 설정이 따로 필요하지 않습니다.(현재 Django는 하위 호환성이 보장되지 않는 파이썬 3.0에서는 사용할 수 없습니다. 파이썬 3.0 버전 지원에 대한 좀 더 자세한 사항은 :doc:`Django FAQ `\ 를 참고하세요.) .. _sqlite: http://sqlite.org/ @@ -20,6 +20,8 @@ Django는 파이썬 웹 프레임워크이므로, 파이썬을 필요로 합니 파이썬이 설치되어 있는지는, 쉘에서 ``python`` 명령어를 입력하여 다음과 같이 표시되는 것으로 확인할 수 있습니다. +:: + Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. @@ -30,7 +32,7 @@ Django는 파이썬 웹 프레임워크이므로, 파이썬을 필요로 합니 파이썬 2.5 버전 이상이 설치되어 있다면 이 부분을 건너뛰어도 됩니다. -파이썬 2.5보다 낮은 버전을 사용한다거나, PostgreSQL, MySQL, Oracle과 같은 "큰" 데이터베이스에서 동작이 필요하다면, :ref:`데이터 베이스 설치 정보 +파이썬 2.5보다 낮은 버전을 사용한다거나, PostgreSQL, MySQL, Oracle과 같은 "큰" 데이터베이스에서 동작이 필요하다면, :ref:`데이터베이스 설치 정보 `\ 를 참고하세요. 이전 Django 버전 제거 @@ -45,9 +47,9 @@ Django를 설치하는 데에는 다음과 같은 세 가지의 쉬운 방법이 * :doc:`운영체제에서 제공하는 Django 버전 `\ 을 설치합니다. Django와 함께 배포되는 운영체제를 사용하는 경우에 가장 빠르게 구성할 수 있는 방법입니다. -* :ref:` 공식 릴리스 설치하기 `. 약간 지나간 버전이라 할지라도 안정적인 Django 버전을 원하는 사용자에게 최선의 선택입니다. +* :ref:`공식 릴리스 설치하기 `\ . 약간 지나간 버전이라 할지라도 안정적인 Django 버전을 원하는 사용자에게 최선의 선택입니다. -* :ref: 최신 개발 버전 설치하기 `. 따끈따끈한 최신의 코드를 실행시키는 데에 주저함이 없는 사용자에게는 최선의 선택이 될 것입니다. +* :ref: 최신 개발 버전 설치하기 `\ . 따끈따끈한 최신의 코드를 실행시키는 데에 주저함이 없는 사용자에게는 최선의 선택이 될 것입니다. .. admonition:: 문서를 읽으실 때는 항상 이용하고 있는 Django의 버전에 맞는지 확인하세요! From 1fed988926f1294e54b2bfd918d44052f037521d Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Fri, 24 Aug 2012 20:22:57 +0900 Subject: [PATCH 046/128] =?UTF-8?q?intro/install=20=EA=B5=90=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- intro/install.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/intro/install.txt b/intro/install.txt index fc662d5..d116083 100644 --- a/intro/install.txt +++ b/intro/install.txt @@ -49,7 +49,7 @@ Django를 설치하는 데에는 다음과 같은 세 가지의 쉬운 방법이 * :ref:`공식 릴리스 설치하기 `\ . 약간 지나간 버전이라 할지라도 안정적인 Django 버전을 원하는 사용자에게 최선의 선택입니다. -* :ref: 최신 개발 버전 설치하기 `\ . 따끈따끈한 최신의 코드를 실행시키는 데에 주저함이 없는 사용자에게는 최선의 선택이 될 것입니다. +* :ref:`최신 개발 버전 설치하기 `\ . 따끈따끈한 최신의 코드를 실행시키는 데에 주저함이 없는 사용자에게는 최선의 선택이 될 것입니다. .. admonition:: 문서를 읽으실 때는 항상 이용하고 있는 Django의 버전에 맞는지 확인하세요! From 7427f26ab363745edbf27c60c6ab558bff25120f Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Fri, 24 Aug 2012 20:55:42 +0900 Subject: [PATCH 047/128] =?UTF-8?q?index=20=EB=B2=88=EC=97=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- index.txt | 440 +++++++++++++++++++++++++++--------------------------- 1 file changed, 219 insertions(+), 221 deletions(-) diff --git a/index.txt b/index.txt index 5b34d02..05ee530 100644 --- a/index.txt +++ b/index.txt @@ -1,221 +1,219 @@ -.. _index: - -==================== -Django 문서(한국어판) -==================== - -.. rubric:: 장고에 관해 알아야 할 모든 것(and then some). - -도움말 -============ - -문제가 있나요? 도와드리고 싶어요! - -* :doc:`FAQ ` 문서를 참고하세요 -- 가장 흔한 질문에 대한 답변들입니다. - -* 특정 주제를 찾으신다면, 다음 문서를 둘러보세요. :ref:`genindex`, :ref:`modindex`, - :doc:`detailed table of contents `. - -* Search for information in the `archives of the django-users mailing list`_, or - `post a question`_. - -* Ask a question in the `#django IRC channel`_, or search the `IRC logs`_ to see - if it's been asked before. - -* Report bugs with Django in our `ticket tracker`_. - -.. _archives of the django-users mailing list: http://groups.google.com/group/django-users/ -.. _post a question: http://groups.google.com/group/django-users/ -.. _#django IRC channel: irc://irc.freenode.net/django -.. _IRC logs: http://django-irc-logs.com/ -.. _ticket tracker: https://code.djangoproject.com/ - -First steps -=========== - -* **From scratch:** - :doc:`Overview ` | - :doc:`Installation ` - -* **Tutorial:** - :doc:`Part 1 ` | - :doc:`Part 2 ` | - :doc:`Part 3 ` | - :doc:`Part 4 ` - -The model layer -=============== - -* **Models:** - :doc:`Model syntax ` | - :doc:`Field types ` | - :doc:`Meta options ` - -* **QuerySets:** - :doc:`Executing queries ` | - :doc:`QuerySet method reference ` - -* **Model instances:** - :doc:`Instance methods ` | - :doc:`Accessing related objects ` - -* **Advanced:** - :doc:`Managers ` | - :doc:`Raw SQL ` | - :doc:`Transactions ` | - :doc:`Aggregation ` | - :doc:`Custom fields ` | - :doc:`Multiple databases ` - -* **Other:** - :doc:`Supported databases ` | - :doc:`Legacy databases ` | - :doc:`Providing initial data ` | - :doc:`Optimize database access ` - -The template layer -================== - -* **For designers:** - :doc:`Syntax overview ` | - :doc:`Built-in tags and filters ` - -* **For programmers:** - :doc:`Template API ` | - :doc:`Custom tags and filters ` - -The view layer -============== - -* **The basics:** - :doc:`URLconfs ` | - :doc:`View functions ` | - :doc:`Shortcuts ` | - :doc:`Decorators ` - -* **Reference:** - :doc:`Request/response objects ` | - :doc:`TemplateResponse objects ` - -* **File uploads:** - :doc:`Overview ` | - :doc:`File objects ` | - :doc:`Storage API ` | - :doc:`Managing files ` | - :doc:`Custom storage ` - -* **Generic views:** - :doc:`Overview` | - :doc:`Built-in generic views` - -* **Advanced:** - :doc:`Generating CSV ` | - :doc:`Generating PDF ` - -* **Middleware:** - :doc:`Overview ` | - :doc:`Built-in middleware classes ` - -Forms -===== - -* **The basics:** - :doc:`Overview ` | - :doc:`Form API ` | - :doc:`Built-in fields ` | - :doc:`Built-in widgets ` - -* **Advanced:** - :doc:`Forms for models ` | - :doc:`Integrating media ` | - :doc:`Formsets ` | - :doc:`Customizing validation ` - -* **Extras:** - :doc:`Form preview ` | - :doc:`Form wizard ` - -The development process -======================= - -* **Settings:** - :doc:`Overview ` | - :doc:`Full list of settings ` - -* **Exceptions:** - :doc:`Overview ` - -* **django-admin.py and manage.py:** - :doc:`Overview ` | - :doc:`Adding custom commands ` - -* **Testing:** :doc:`Overview ` - -* **Deployment:** - :doc:`Overview ` | - :doc:`WSGI servers ` | - :doc:`FastCGI/SCGI/AJP ` | - :doc:`Apache/mod_python (deprecated) ` | - :doc:`Apache authentication ` | - :doc:`Handling static files ` | - :doc:`Tracking code errors by email ` - -Other batteries included -======================== - -* :doc:`Admin site ` | :doc:`Admin actions ` | :doc:`Admin documentation generator` -* :doc:`Authentication ` -* :doc:`Cache system ` -* :doc:`Clickjacking protection ` -* :doc:`Comments ` | :doc:`Moderation ` | :doc:`Custom comments ` -* :doc:`Conditional content processing ` -* :doc:`Content types and generic relations ` -* :doc:`Cross Site Request Forgery protection ` -* :doc:`Cryptographic signing ` -* :doc:`Databrowse ` -* :doc:`E-mail (sending) ` -* :doc:`Flatpages ` -* :doc:`GeoDjango ` -* :doc:`Humanize ` -* :doc:`Internationalization ` -* :doc:`Jython support ` -* :doc:`"Local flavor" ` -* :doc:`Logging ` -* :doc:`Messages ` -* :doc:`Pagination ` -* :doc:`Redirects ` -* :doc:`Security ` -* :doc:`Serialization ` -* :doc:`Sessions ` -* :doc:`Signals ` -* :doc:`Sitemaps ` -* :doc:`Sites ` -* :doc:`Static Files ` -* :doc:`Syndication feeds (RSS/Atom) ` -* :doc:`Unicode in Django ` -* :doc:`Web design helpers ` -* :doc:`Validators ` -* Function-based generic views (Deprecated) :doc:`Overview` | :doc:`Built-in generic views` | :doc:`Migration guide` - -The Django open-source project -============================== - -* **Community:** - :doc:`How to get involved ` | - :doc:`The release process ` | - :doc:`Team of committers ` | - :doc:`The Django source code repository ` - -* **Design philosophies:** - :doc:`Overview ` - -* **Documentation:** - :doc:`About this documentation ` - -* **Third-party distributions:** - :doc:`Overview ` - -* **Django over time:** - :doc:`API stability ` | - :doc:`Release notes and upgrading instructions ` | - :doc:`Deprecation Timeline ` +.. _index: + +==================== +Django 문서(한국어판) +==================== + +.. rubric:: 장고에 대하여 알아야 할 모든 것. + +도움말 +============ + +문제가 있나요? 도와드리고 싶어요! + +* :doc:`FAQ ` 문서를 참고하세요 -- 가장 흔한 질문에 대한 답변들입니다. + +* 특정 주제를 찾으신다면, 다음 문서를 둘러보세요. :ref:`genindex`, :ref:`modindex`, + :doc:`상세한 목차 `. + +* `django-users 메일링 리스트의 아카이브`_\ 에서 정보를 검색하거나, `질문을 올리세요`_. + +* `#django IRC 채널`_\ 에서 물어보거나, 이전에 있었던 질문인지 `IRC 기록`_\ 에서 검색해보세요. + +* Django에 대한 버그를 발견하시면 `티켓 추적 시스템`_\ 에 보고해주세요. + +.. _django-users 메일링 리스트의 아카이브: http://groups.google.com/group/django-users/ +.. _질문을 올리세요: http://groups.google.com/group/django-users/ +.. _#django IRC 채널: irc://irc.freenode.net/django +.. _IRC 기록: http://django-irc-logs.com/ +.. _티켓 추적 시스템: https://code.djangoproject.com/ + +첫걸음 +=========== + +* **시작하기:** + :doc:`개요 ` | + :doc:`설치 ` + +* **자습서:** + :doc:`1부 ` | + :doc:`2부 ` | + :doc:`3부 ` | + :doc:`4부 ` + +모델 계층 +=============== + +* **Models:** + :doc:`Model syntax ` | + :doc:`Field types ` | + :doc:`Meta options ` + +* **QuerySets:** + :doc:`Executing queries ` | + :doc:`QuerySet method reference ` + +* **Model instances:** + :doc:`Instance methods ` | + :doc:`Accessing related objects ` + +* **Advanced:** + :doc:`Managers ` | + :doc:`Raw SQL ` | + :doc:`Transactions ` | + :doc:`Aggregation ` | + :doc:`Custom fields ` | + :doc:`Multiple databases ` + +* **Other:** + :doc:`Supported databases ` | + :doc:`Legacy databases ` | + :doc:`Providing initial data ` | + :doc:`Optimize database access ` + +템플릿 계층 +================== + +* **For designers:** + :doc:`Syntax overview ` | + :doc:`Built-in tags and filters ` + +* **For programmers:** + :doc:`Template API ` | + :doc:`Custom tags and filters ` + +뷰 계층 +============== + +* **The basics:** + :doc:`URLconfs ` | + :doc:`View functions ` | + :doc:`Shortcuts ` | + :doc:`Decorators ` + +* **Reference:** + :doc:`Request/response objects ` | + :doc:`TemplateResponse objects ` + +* **File uploads:** + :doc:`Overview ` | + :doc:`File objects ` | + :doc:`Storage API ` | + :doc:`Managing files ` | + :doc:`Custom storage ` + +* **Generic views:** + :doc:`Overview` | + :doc:`Built-in generic views` + +* **Advanced:** + :doc:`Generating CSV ` | + :doc:`Generating PDF ` + +* **Middleware:** + :doc:`Overview ` | + :doc:`Built-in middleware classes ` + +폼 +===== + +* **The basics:** + :doc:`Overview ` | + :doc:`Form API ` | + :doc:`Built-in fields ` | + :doc:`Built-in widgets ` + +* **Advanced:** + :doc:`Forms for models ` | + :doc:`Integrating media ` | + :doc:`Formsets ` | + :doc:`Customizing validation ` + +* **Extras:** + :doc:`Form preview ` | + :doc:`Form wizard ` + +개발 프로세스 +======================= + +* **Settings:** + :doc:`Overview ` | + :doc:`Full list of settings ` + +* **Exceptions:** + :doc:`Overview ` + +* **django-admin.py and manage.py:** + :doc:`Overview ` | + :doc:`Adding custom commands ` + +* **Testing:** :doc:`Overview ` + +* **Deployment:** + :doc:`Overview ` | + :doc:`WSGI servers ` | + :doc:`FastCGI/SCGI/AJP ` | + :doc:`Apache/mod_python (deprecated) ` | + :doc:`Apache authentication ` | + :doc:`Handling static files ` | + :doc:`Tracking code errors by email ` + +기타 내장된 배터리들 +======================== + +* :doc:`Admin site ` | :doc:`Admin actions ` | :doc:`Admin documentation generator` +* :doc:`Authentication ` +* :doc:`Cache system ` +* :doc:`Clickjacking protection ` +* :doc:`Comments ` | :doc:`Moderation ` | :doc:`Custom comments ` +* :doc:`Conditional content processing ` +* :doc:`Content types and generic relations ` +* :doc:`Cross Site Request Forgery protection ` +* :doc:`Cryptographic signing ` +* :doc:`Databrowse ` +* :doc:`E-mail (sending) ` +* :doc:`Flatpages ` +* :doc:`GeoDjango ` +* :doc:`Humanize ` +* :doc:`Internationalization ` +* :doc:`Jython support ` +* :doc:`"Local flavor" ` +* :doc:`Logging ` +* :doc:`Messages ` +* :doc:`Pagination ` +* :doc:`Redirects ` +* :doc:`Security ` +* :doc:`Serialization ` +* :doc:`Sessions ` +* :doc:`Signals ` +* :doc:`Sitemaps ` +* :doc:`Sites ` +* :doc:`Static Files ` +* :doc:`Syndication feeds (RSS/Atom) ` +* :doc:`Unicode in Django ` +* :doc:`Web design helpers ` +* :doc:`Validators ` +* Function-based generic views (Deprecated) :doc:`Overview` | :doc:`Built-in generic views` | :doc:`Migration guide` + +Django 오픈 소스 프로젝트 +============================== + +* **커뮤니티:** + :doc:`How to get involved ` | + :doc:`The release process ` | + :doc:`Team of committers ` | + :doc:`The Django source code repository ` + +* **디자인 철학:** + :doc:`개요 ` + +* **문서화:** + :doc:`About this documentation ` + +* **서드 파티 분배:** + :doc:`Overview ` + +* **장기간의 유지보수 계획:** + :doc:`API 안정성 ` | + :doc:`Release notes and upgrading instructions ` | + :doc:`Deprecation Timeline ` From 96c5429a18827c43ac02f782abf0f92a082de34e Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Thu, 30 Aug 2012 01:33:35 +0900 Subject: [PATCH 048/128] =?UTF-8?q?misc/design-philosophies=20=EB=B2=88?= =?UTF-8?q?=EC=97=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 소재성님의 번역을 수정하여 올림 --- misc/design-philosophies.txt | 553 +++++++++++++++-------------------- 1 file changed, 241 insertions(+), 312 deletions(-) diff --git a/misc/design-philosophies.txt b/misc/design-philosophies.txt index c4fb582..a56f52b 100644 --- a/misc/design-philosophies.txt +++ b/misc/design-philosophies.txt @@ -1,312 +1,241 @@ -=================== -Design philosophies -=================== - -This document explains some of the fundamental philosophies Django's developers -have used in creating the framework. Its goal is to explain the past and guide -the future. - -Overall -======= - -.. _loose-coupling: - -Loose coupling --------------- - -.. index:: coupling; loose - -A fundamental goal of Django's stack is `loose coupling and tight cohesion`_. -The various layers of the framework shouldn't "know" about each other unless -absolutely necessary. - -For example, the template system knows nothing about Web requests, the database -layer knows nothing about data display and the view system doesn't care which -template system a programmer uses. - -Although Django comes with a full stack for convenience, the pieces of the -stack are independent of another wherever possible. - -.. _`loose coupling and tight cohesion`: http://c2.com/cgi/wiki?CouplingAndCohesion - -.. _less-code: - -Less code ---------- - -Django apps should use as little code as possible; they should lack boilerplate. -Django should take full advantage of Python's dynamic capabilities, such as -introspection. - -.. _quick-development: - -Quick development ------------------ - -The point of a Web framework in the 21st century is to make the tedious aspects -of Web development fast. Django should allow for incredibly quick Web -development. - -.. _dry: - -Don't repeat yourself (DRY) ---------------------------- - -.. index:: - single: DRY - single: Don't repeat yourself - -Every distinct concept and/or piece of data should live in one, and only one, -place. Redundancy is bad. Normalization is good. - -The framework, within reason, should deduce as much as possible from as little -as possible. - -.. seealso:: - - The `discussion of DRY on the Portland Pattern Repository`__ - - __ http://c2.com/cgi/wiki?DontRepeatYourself - -.. _explicit-is-better-than-implicit: - -Explicit is better than implicit --------------------------------- - -This is a core Python principle listed in :pep:`20`, and it means Django -shouldn't do too much "magic." Magic shouldn't happen unless there's a really -good reason for it. Magic is worth using only if it creates a huge convenience -unattainable in other ways, and it isn't implemented in a way that confuses -developers who are trying to learn how to use the feature. - -.. _consistency: - -Consistency ------------ - -The framework should be consistent at all levels. Consistency applies to -everything from low-level (the Python coding style used) to high-level (the -"experience" of using Django). - -Models -====== - -Explicit is better than implicit --------------------------------- - -Fields shouldn't assume certain behaviors based solely on the name of the -field. This requires too much knowledge of the system and is prone to errors. -Instead, behaviors should be based on keyword arguments and, in some cases, on -the type of the field. - -Include all relevant domain logic ---------------------------------- - -Models should encapsulate every aspect of an "object," following Martin -Fowler's `Active Record`_ design pattern. - -This is why both the data represented by a model and information about -it (its human-readable name, options like default ordering, etc.) are -defined in the model class; all the information needed to understand a -given model should be stored *in* the model. - -.. _`Active Record`: http://www.martinfowler.com/eaaCatalog/activeRecord.html - -Database API -============ - -The core goals of the database API are: - -SQL efficiency --------------- - -It should execute SQL statements as few times as possible, and it should -optimize statements internally. - -This is why developers need to call ``save()`` explicitly, rather than the -framework saving things behind the scenes silently. - -This is also why the ``select_related()`` ``QuerySet`` method exists. It's an -optional performance booster for the common case of selecting "every related -object." - -Terse, powerful syntax ----------------------- - -The database API should allow rich, expressive statements in as little syntax -as possible. It should not rely on importing other modules or helper objects. - -Joins should be performed automatically, behind the scenes, when necessary. - -Every object should be able to access every related object, systemwide. This -access should work both ways. - -Option to drop into raw SQL easily, when needed ------------------------------------------------ - -The database API should realize it's a shortcut but not necessarily an -end-all-be-all. The framework should make it easy to write custom SQL -- entire -statements, or just custom ``WHERE`` clauses as custom parameters to API calls. - -URL design -========== - -Loose coupling --------------- - -URLs in a Django app should not be coupled to the underlying Python code. Tying -URLs to Python function names is a Bad And Ugly Thing. - -Along these lines, the Django URL system should allow URLs for the same app to -be different in different contexts. For example, one site may put stories at -``/stories/``, while another may use ``/news/``. - -Infinite flexibility --------------------- - -URLs should be as flexible as possible. Any conceivable URL design should be -allowed. - -Encourage best practices ------------------------- - -The framework should make it just as easy (or even easier) for a developer to -design pretty URLs than ugly ones. - -File extensions in Web-page URLs should be avoided. - -Vignette-style commas in URLs deserve severe punishment. - -.. _definitive-urls: - -Definitive URLs ---------------- - -.. index:: urls; definitive - -Technically, ``foo.com/bar`` and ``foo.com/bar/`` are two different URLs, and -search-engine robots (and some Web traffic-analyzing tools) would treat them as -separate pages. Django should make an effort to "normalize" URLs so that -search-engine robots don't get confused. - -This is the reasoning behind the :setting:`APPEND_SLASH` setting. - -Template system -=============== - -.. _separation-of-logic-and-presentation: - -Separate logic from presentation --------------------------------- - -We see a template system as a tool that controls presentation and -presentation-related logic -- and that's it. The template system shouldn't -support functionality that goes beyond this basic goal. - -If we wanted to put everything in templates, we'd be using PHP. Been there, -done that, wised up. - -Discourage redundancy ---------------------- - -The majority of dynamic Web sites use some sort of common sitewide design -- -a common header, footer, navigation bar, etc. The Django template system should -make it easy to store those elements in a single place, eliminating duplicate -code. - -This is the philosophy behind :ref:`template inheritance -`. - -Be decoupled from HTML ----------------------- - -The template system shouldn't be designed so that it only outputs HTML. It -should be equally good at generating other text-based formats, or just plain -text. - -XML should not be used for template languages ---------------------------------------------- - -.. index:: xml; suckiness of - -Using an XML engine to parse templates introduces a whole new world of human -error in editing templates -- and incurs an unacceptable level of overhead in -template processing. - -Assume designer competence --------------------------- - -The template system shouldn't be designed so that templates necessarily are -displayed nicely in WYSIWYG editors such as Dreamweaver. That is too severe of -a limitation and wouldn't allow the syntax to be as nice as it is. Django -expects template authors are comfortable editing HTML directly. - -Treat whitespace obviously --------------------------- - -The template system shouldn't do magic things with whitespace. If a template -includes whitespace, the system should treat the whitespace as it treats text --- just display it. Any whitespace that's not in a template tag should be -displayed. - -Don't invent a programming language ------------------------------------ - -The template system intentionally doesn't allow the following: - -* Assignment to variables -* Advanced logic - -The goal is not to invent a programming language. The goal is to offer just -enough programming-esque functionality, such as branching and looping, that is -essential for making presentation-related decisions. - -The Django template system recognizes that templates are most often written by -*designers*, not *programmers*, and therefore should not assume Python -knowledge. - -Safety and security -------------------- - -The template system, out of the box, should forbid the inclusion of malicious -code -- such as commands that delete database records. - -This is another reason the template system doesn't allow arbitrary Python code. - -Extensibility -------------- - -The template system should recognize that advanced template authors may want -to extend its technology. - -This is the philosophy behind custom template tags and filters. - -Views -===== - -Simplicity ----------- - -Writing a view should be as simple as writing a Python function. Developers -shouldn't have to instantiate a class when a function will do. - -Use request objects -------------------- - -Views should have access to a request object -- an object that stores metadata -about the current request. The object should be passed directly to a view -function, rather than the view function having to access the request data from -a global variable. This makes it light, clean and easy to test views by passing -in "fake" request objects. - -Loose coupling --------------- - -A view shouldn't care about which template system the developer uses -- or even -whether a template system is used at all. - -Differentiate between GET and POST ----------------------------------- - -GET and POST are distinct; developers should explicitly use one or the other. -The framework should make it easy to distinguish between GET and POST data. +=================== +설계 철학 +=================== + +이 문서는, Django의 개발자들이 프레임워크를 창안하는 데에 있어 중요하게 여기는 근본 원리에 대해 몇 가지를 설명하고 있습니다. 과거를 돌아보고 미래로 나아갈 길을 안내하는 것이 바로 이 문서의 목표입니다. + +개요 +======= + +.. _loose-coupling: + +느슨한 결합 +-------------- + +.. index:: coupling; loose + +Django 스택의 근본 목표는 바로 `느슨한 결합과 강한 응집`_\ 입니다. 프레임워크의 다양한 계층들은 절대적으로 필요한 것을 제외하고는 다른 계층에 대해서 "알아서는" 안됩니다. + +예를 들어서, 템플릿 시스템은 웹이 요청하는 것들에 관해 전혀 알지 못하고, 데이터베이스 계층은 데이터 표시하는 것에 대해 전혀 알지 못하고, 그리고 뷰 시스템은 프로그래머가 어떤 템플릿 시스템 사용하는지에는 상관하지 않습니다. + +비록 Django가 편리성을 위한 전체 스택을 갖추고 있지만, 스택의 일부분은 다른 것들과 가능한 한 독립되어 있습니다. + +.. _`느슨한 결합과 강한 응집`: http://c2.com/cgi/wiki?CouplingAndCohesion + +.. _less-code: + +적은 코드 +--------- + +Django 앱은 가능한 한 적은 코드를 사용해야 합니다. Django는 인트로스펙션과 같은 Python의 동적인 능력으로부터 오는 장점을 최대한 취하려고 합니다. + +.. _quick-development: + +빠른 개발 +----------------- + +21세기 웹 프레임워크의 핵심은 바로 웹 개발의 지겨운 부분을 신속성있게 바꾸는 것입니다. Django는 웹 개발의 속도를 극적으로 높이고자 합니다. + +.. _dry: + +중복 방지(DRY) +--------------------------- + +.. index:: + single: DRY + single: Don't repeat yourself + +개별성을 갖는 개념 및 데이터는 단 한 곳에, 단 한 벌만 존재해야 합니다. 과잉은 나쁜 것이며, 정규화(normalization)는 좋은 것입니다. + +이러한 이유로 인해 프레임워크는 가능한 만큼 최대한 줄여야 합니다. + +.. seealso:: + + `포틀랜드 패턴 저장소의 DRY에 대한 논의`__ + + __ http://c2.com/cgi/wiki?DontRepeatYourself + +.. _explicit-is-better-than-implicit: + +명시적인 구현 +-------------------------------- + +이것은 :pep:`20`\ 에 나열된 파이썬 원리의 핵심이며, Django가 너무 많이 "마술"을 부려서는 안 된다는 것을 의미하고 마술은 그것이 정말 좋은 이유가 아니라면 일어나선 안된다는 것입니다. 마술은 오직 그것이 다른 방법으로는 도달하기 어려운 매우 큰 어떤 편리함을 만들어 내는 데 사용될 때에만 가치가 있으며, 기능을 사용하는 방법을 배우려고 노력하고 있는 개발자가 혼란스러워하는 방법으로 구현되지 않습니다. + +.. _consistency: + +일관성 +----------- + +프레임워크는 모든 수준에서 모순이 없이 일관되어야 합니다. 일관성은 (파이썬 코딩 스타일이 사용된) 저수준으로부터 고수준(Django 사용하기의 "경험")까지 거의 모든 것에 적용됩니다. + +모델 +====== + +명시적인 구현 +-------------------------------- + +필드들은 순전히 필드라고 이름 지어진 것을 기반으로 한 특정 동작을 당연하다고 여겨선 안됩니다. 결국 너무 많은 시스템 정보를 요청하고 그래서 오류가 자주 발생 하게 됩니다. 대신에, 동작들은 인자 키워드에 기반되어야 하고 그리고 때로는 필드의 형식에 기반되어야 합니다. + +모든 적절한 도메인 로직을 포함 +--------------------------------- + +모델은 모든 "개체"의 측면을 요약해야 하고, 마틴 파울러의 `액티브 레코드`_ 디자인 패턴을 따라야 합니다. + +이것이 바로 모델에 의하여 표현되는 데이터 및 그에 대한 정보(사람이 읽을 수 있는 이름, 기본 정렬순서와 같은 선택사항 등)가 모델 클래스 내에 정의되어 있는 이유입니다. 모델을 이해하기 위해 필요한 모든 정보는 모델 *내*\ 에 저장되어야 합니다. + +.. _`액티브 레코드`: http://www.martinfowler.com/eaaCatalog/activeRecord.html + +데이터베이스 API +============ + +데이터베이스 API는 다음과 같은 핵심목표를 갖습니다. + +SQL 효율 +-------------- + +SQL문은 가능한 한 짧은 시간 내에 실행되어야 하고, 내부적으로 문을 최적화해야 합니다. + +저장하는 일을 프레임워크에서 조용히 처리하기보다는 개발자가 ``save()``를 명시적으로 호출하여야 하는 것이 그러한 이유에서입니다. + +또한 ``select_related()`` ``QuerySet`` 메소드가 존재하는 이유이기도 합니다. "모든 연관된 개체"를 선택하는 일반적인 경우를 위한 성능 부스터 입니다. + +간결하고 강력한 구문 +---------------------- + +데이터베이스 API는 가능한 적은 구문으로 풍부하고 표현력이 높은 문장을 제공해야 합니다. 다른 모듈이나 도우미 개체 불러오기에 의지해서는 안 됩니다. + +조인(join)은 필요할 때 이면에서 자동적으로 수행되어야 합니다. + +모든 개체는 연관된 모든 개체에 시스템 전역에서 접근해져야 합니다. 이 접근은 양방향에서 작동해야 합니다. + +필요할 때에는 날것의 SQL을 쉽게 사용할 수 있을 것 +----------------------------------------------- + +데이터베이스 API는 이것이 지름길일 뿐, 반드시 필요한 것이 되어서는 안된다는 점을 인지하여야 합니다. 프레임워크는 맞춤 SQL -- 전체 문장 또는 맞춤 ``WHERE`` 절만을 API 호출의 맞춤 파라미터로서-- 을 작성하기 쉬워야 합니다. + +URL 디자인 +========== + +느슨한 결합 +-------------- + +Django 앱 내의 URL들은 근본적인 파이썬 코드를 위해 연결지어져선 안 됩니다. 파이썬 함수 이름에 URL을 묶는 것은 추악한 것입니다. + +이러한 노선을 따라, Django URL 시스템은 동일한 앱을 대하여 문맥에 따른 URL을 허용합니다. 예를 들어, 어떤 사이트는 기사를 ``/stories/``에 두고, 다른 사이트는 ``/news/``에 두는 것도 가능합니다. + +무한한 유연성 +-------------------- + +URL은 가능한 융통성이 있어야 합니다. 상상할 수 있는 어떠한 URL 디자인도 허용되어야 합니다. + +모범 사례를 권장 +------------------------ + +프레임워크는 추한 것 보다는 아름다운 URL을 디자인 하기 위해 개발자를 위하여 그냥 쉽게 만들어야 합니다. + +웹페이지 URL내에 파일 확장자들은 피해야 합니다. + +URL 내의 비네트 스타일의 쉼표는 중벌을 받아 마땅합니다. + +.. _definitive-urls: + +완전한 URL +--------------- + +.. index:: urls; definitive + +기술적으로, ``foo.com/bar``와 ``foo.com/bar/``는 서로 다른 URL이며, 검색 엔진 로봇과 몇몇 웹 트래픽 분석 도구들은 이를 별도의 페이지로 취급합니다. Django는 검색 엔진 로봇이 헷갈리지 않도록 URL을 "정규화"하려고 노력합니다. + +이것이 :setting:`APPEND_SLASH` 설정이 있는 이유입니다. + +템플릿 시스템 +=============== + +.. _separation-of-logic-and-presentation: + +표현과 로직의 분리 +-------------------------------- + +우리는 템플릿 시스템을 표현 및 표현 관련 로직을 제어하는 도구이며, 그 이상도 이하도 아니라고 생각합니다. 템플릿 시스템은 이러한 기본 목표를 초월하는 기능을 지원해서는 안됩니다. + +템플릿에 모두 다 우겨넣을 생각이었다면, PHP를 사용하고 있을 것입니다. 그런 짓에는 신물이 납니다. + +중복 제거 +--------------------- + +대다수 동적인 웹 사이트들은 일종의 공통 사이트와이드 디자인을 사용합니다. -- 공통의 헤더, 푸터, 네비게이션 바, 기타 등등. Django 템플릿 시스템은 단일한 장소에, 중복된 코드를 빼내고, 쉽게 축적할 수 있도록 해야 합니다. + +이는 :ref:`템플릿 상속 `\ 을 뒷받침하는 철학입니다. + +HTML에 얽매이지 않기 +---------------------- + +템플릿 시스템이 오직 HTML만 출력하도록 설계되어서는 안 됩니다. 다른 텍스트 기반 포맷이라든지 그냥 일반 텍스트를 생성하는 기능도 마찬가지로 훌륭하여야 합니다. + +XML을 템플릿 언어로서 사용하지 말 것 +--------------------------------------------- + +.. index:: xml; suckiness of + +XML 엔진을 템플릿 분석에 사용하는 것은, 템플릿을 편집하는 사람에 의해 발생하는 오류라는 새로운 세계의 문을 열어젖히는 일입니다. 또한 템플릿 처리에 있어 감내하기 힘든 수준의 과부하를 일으킵니다. + +디자이너의 역량을 가정 +-------------------------- + +템플릿 시스템은 드림위버와 같은 위지윅(WYSIWYG) 편집기에서 반드시 잘 보이도록 설계하지는 않습니다. 이는 좋은 구문을 만들어내는 데에 중대한 제약이 되기 때문입니다. Django는 템플릿을 작성하는 사람이 HTML을 직접 편집하는 데에 거리낌이 없을 것으로 기대합니다. + +공백을 분명히 다루기 +-------------------------- + +템플릿 시스템은 공백을 가지고 마술을 부려서는 안 됩니다. 만일 템플릿이 공백을 포함하면, 시스템은 텍스트를 다루는 것처럼 공백을 다루어야 합니다. +-- 그냥 그것을 표시합니다. 템플릿 태그에 있지 않은 공백은 표시 되어야 합니다. + +프로그래밍 언어를 새로 개발하지 말 것 +----------------------------------- + +템플릿 시스템은 의도적으로 다음과 같은 것을 허용하지 않습니다. + +* 변수의 할당 +* 진일보한 로직 + +템플릿 시스템의 목표는 프로그래밍 언어를 창안하는 것이 아닙니다. 표현의 처리에 있어 불가결한 분기와 루핑 등의 프로그래밍 비슷한 기능을 제공할 뿐입니다. + +Django 템플릿 시스템은 템플릿은 *프로그래머*\가 아닌 *디자이너*\ 가 가장 많이 사용하는 것이며, 파이썬에 대한 지식을 가정해서는 안된다는 점을 인식합니다. + +안정성과 보안성 +------------------- + +독창적인 템플릿 시스템은 악의적인 코드가 끼어들 가능성을 배제하여야 합니다. + +이것은 템플릿 시스템이 임의의 파이썬 코드를 허용하지 않는 또 다른 이유입니다. + +확장성 +------------- + +템플릿 시스템은 진일보한 템플릿 작가들이 그것의 기술을 확장하길 원할 수도 있음을 인지해야 합니다. + +이것이 맞춤 템플릿 태그 및 필터가 존재하는 이유입니다. + +뷰 +===== + +단순성 +---------- + +뷰 작성하기는 파이썬 함수를 작성하는 것처럼 가능한 한 단순하여야 합니다. 개발자는 함수가 수행하려고 할 때 클래스를 인스턴스화할 필요가 없습니다. + +요청 개체의 사용 +------------------- + +뷰는 요청 개체 -- 현재 요청에 대한 메타데이터를 저장하는 개체 -- 에 대하여 접근할 수 있어야 합니다. 뷰 함수가 전역 변수로부터 요청 데이터에 접근하기보다는, 개체가 뷰 함수에 직접적으로 전달되어야 합니다. 이것이 가볍고, 깔끔하며, "가짜" 요청 개체를 전달함으로써 뷰를 테스트하기 쉽습니다. + +느슨한 결합 +-------------- + +뷰는 개발자가 어떤 템플릿 시스템을 사용하는지, 혹은 템플릿 시스템을 아예 사용하지 않는지에 대해 관여하지 않아야 합니다. + +GET과 POST의 차별화 +---------------------------------- + +GET과 POST는 다른 것이며, 개발자는 둘 중 하나를 명확하게 사용하여야 합니다. 프레임워크는 GET과 POST를 구분하는 것이 쉽도록 해주어야 합니다. From 2ca47db3dcc347f2eec6393f7bf582f2c5c70814 Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Thu, 30 Aug 2012 01:37:58 +0900 Subject: [PATCH 049/128] =?UTF-8?q?glossary=20=EB=B2=88=EC=97=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- glossary.txt | 141 ++++++++++++++++++++++++--------------------------- 1 file changed, 66 insertions(+), 75 deletions(-) diff --git a/glossary.txt b/glossary.txt index 15776ce..8651380 100644 --- a/glossary.txt +++ b/glossary.txt @@ -1,75 +1,66 @@ -.. _glossary: - -======== -Glossary -======== - -.. glossary:: - - field - An attribute on a :term:`model`; a given field usually maps directly to - a single database column. - - See :doc:`/topics/db/models`. - - generic view - A higher-order :term:`view` function that provides an abstract/generic - implementation of a common idiom or pattern found in view development. - - See :doc:`/ref/generic-views`. - - model - Models store your application's data. - - See :doc:`/topics/db/models`. - - MTV - "Model-template-view"; a software pattern, similar in style to MVC, but - a better description of the way Django does things. - - See :ref:`the FAQ entry `. - - MVC - `Model-view-controller`__; a software pattern. Django :ref:`follows MVC - to some extent `. - - __ http://en.wikipedia.org/wiki/Model-view-controller - - project - A Python package -- i.e. a directory of code -- that contains all the - settings for an instance of Django. This would include database - configuration, Django-specific options and application-specific - settings. - - property - Also known as "managed attributes", and a feature of Python since - version 2.2. This is a neat way to implement attributes whose usage - resembles attribute access, but whose implementation uses method calls. - - See :func:`property`. - - queryset - An object representing some set of rows to be fetched from the database. - - See :doc:`/topics/db/queries`. - - slug - A short label for something, containing only letters, numbers, - underscores or hyphens. They're generally used in URLs. For - example, in a typical blog entry URL: - - .. parsed-literal:: - - https://www.djangoproject.com/weblog/2008/apr/12/**spring**/ - - the last bit (``spring``) is the slug. - - template - A chunk of text that acts as formatting for representing data. A - template helps to abstract the presentation of data from the data - itself. - - See :doc:`/topics/templates`. - - view - A function responsible for rending a page. +.. _glossary: + +======== +용어 +======== + +.. glossary:: + + field + :term:`model`\ 의 어트리뷰트. 하나의 field는 종종 데이터베이스의 한 컬럼에 대응됨. + + :doc:`/topics/db/models` 참조. + + generic view + 뷰 개발에 있어 일반적인 idiom 또는 패턴에 대한 추상적/일반적 구현을 제공하는 보다 높은 order의 :term:`뷰(view)` 함수. + + :doc:`/ref/generic-views` 참조. + + model + 모델은 애플리케이션의 데이터를 저장함. + + :doc:`/topics/db/models` 참조. + + MTV + "모델-템플릿-뷰"; 소프트웨어의 패턴으로서, MVC와 유사하지만, 그보다 Django의 방식을 더 잘 설명하는 용어. + + :ref:`FAQ 항목 ` 참조. + + MVC + `모델-뷰-컨트롤러`__ 소프트웨어 패턴. Django는 :ref:`MVC를 따름 `. + + __ http://en.wikipedia.org/wiki/Model-view-controller + + project + Django의 인스턴스에 대한 모든 설정을 담은 파이썬 패키지 -- 디렉토리 또는 코드 --. + 데이터베이스 설정, Django 설정 및 애플리케이션 설정 등을 포함. + + property + "managed attributes"라고도 하며, 파이썬 버전 2.2부터 제공되는 기능. + 어트리뷰트 접근과 유사한 사용법을 갖는 어트리뷰트를 구현하는 깔끔한 방법이지만, 그 구현은 함수 호출을 사용함. + + :func:`property` 참조. + + queryset + 데이터베이스로부터 얻어낸 행의 집합을 나타내는 개체. + + :doc:`/topics/db/queries` 참조. + + slug + 짧은 라벨로서, 문자, 숫자, 밑줄 또는 하이픈만을 포함. + 일반적으로 URL에 사용. 예를 들어, 블로그 엔트리 URL은 다음과 같다고 할 때, + + .. parsed-literal:: + + https://www.djangoproject.com/weblog/2008/apr/12/**spring**/ + + 마지막 부분(``spring``)이 slug임. + + template + 데이터를 표현하기 위한 형식으로서 쓰이는 텍스트의 덩이리. + 템플릿은 데이터 자체와 그에 대한 표현을 분리하여 추상화하는 데에 도움이 됨. + + :doc:`/topics/templates` 참조. + + view + 페이지를 렌더링하는 역할을 하는 함수. From a0b5302ea7c09dec4c48392cd8707b5043cb66d6 Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Wed, 5 Sep 2012 21:46:29 +0900 Subject: [PATCH 050/128] =?UTF-8?q?introl/tutorial03=20=EB=A7=81=ED=81=AC?= =?UTF-8?q?=20=EA=B9=A8=EC=A7=90=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- intro/tutorial03.txt | 870 +++++++++++++++++++++---------------------- 1 file changed, 435 insertions(+), 435 deletions(-) diff --git a/intro/tutorial03.txt b/intro/tutorial03.txt index 8f53ffa..7930838 100644 --- a/intro/tutorial03.txt +++ b/intro/tutorial03.txt @@ -1,435 +1,435 @@ -===================================== -첫 번째 Django 앱 만들기, part 3 -===================================== - -이 자습서는 :doc:`Tutorial 2 `\ 의 마지막에 이어서 시작 합니다. 우리는 계속해서 "뷰"라고 하는 퍼블릭 인터페이스를 작성하는데 중점을 두고 웹-투표 애플리케이션을 계속 합니다. - -철학 -========== - -뷰는 Django 애플리케이션에서 특정한 기능을 수행하거나, 특정한 템플릿을 가지는 웹 페이지의 "유형" 입니다. 예를 들어 웹블로그 애플리케이션은 아래와 같은 뷰들을 가질 것 입니다. - -* 블로그 홈페이지 -- 최신 엔트리 몇 개를 표시 합니다. - -* 엔트리 "세부" 페이지 -- 한 개의 엔트리를 위한 퍼머링크 페이지입니다. - -* 연도별 아카이브 페이지 -- 주어진 연도에 있는 모든 달들을 엔트리와 함께 나타냅니다. - - -* 월별 아카이브 페이지 -- 주어진 달에 있는 모든 날들을 엔트리와 함께 나타냅니다. - - -* 일별 아카이브 페이지 -- 주어진 날에 있는 모든 엔트리를 나타냅니다. - -* 코멘트 달기 -- 주어진 엔트리에 코멘트를 포스팅 합니다. - -투표 애플리케이션에는 아래와 같이 네 개의 뷰가 있습니다. - -* 투표 "인덱스" 페이지 -- 몇 개의 최신 투표를 나타냅니다. - -* 투표 "세부" 페이지 -- 투표의 질문을 투표 할 수 있는 폼과 함께 나타냅니다. 투표 결과는 보여주지 않습니다. - - -* 투표 "결과" 페이지 -- 특정 투표의 결과를 나타냅니다. - -* 투표 하기 -- 특정 투표에서 특정 선택지에 투표합니다. - - -Django 에서 개별 뷰는 간단한 파이썬 함수로 나타냅니다. - -URL 디자인 하기 -================ - -URL 구조를 디자인 하는 것은 뷰를 작성하는 첫 번째 단계입니다. URLconf라는 파이썬 모듈을 생성함으로써, URL구조를 디자인 할 수 있습니다. URLconfs는 Django가 주어진 URL을 주어진 파이썬 코드와 연결하는 방법 입니다. - -사용자가 Django-powered 페이지를 요청 할 때, 시스템은 Python dotted syntax에 있는 문자열을 포함하는 :setting:'ROOT_URLCONF' 설정을 참고 합니다. Django 는 URLconf 모듈을 로드 합니다. 그리고, 아래와 같은 포맷의 튜플인 모듈-레벨 변수인 ``urlpatterns``\ 를 검색합니다. - -:: - - (regular expression, Python callback function [, optional dictionary]) - -Django는 첫 번째 정규표현식을 시작으로, 일치하는 결과를 찾을 때 까지 요청 받은 URL을 각각의 정규표현식과 비교하면서 리스트 아래로 내려갑니다. - -일치하는 결과를 찾으면, Django는 파이썬 콜백 함수를 호출 합니다. 이 때, :class:`~django.http.HttpRequest` 객체를 첫 번째 인자로 하고, 정규표현식에서 찾은 임의의 값을 키워드 인자로 가집니다. 옵션으로 그 사전에서 임의의 키워드(튜플의 세 번째 아이템)를 가져다가 사용 합니다. - -:class:`~django.http.HttpRequest` 객체에 대해서 자세히 알고 싶다면, :doc:`/ref/request-response`\ 를 참고 하세요. URLconfs 에 대해서 자세히 알고 싶다면, :doc:`/topics/http/urls`\ 를 참고 하세요. - -자습서 1에서 처음 ``django-admin.py startproject mysite`` 를 실행 했을때, 기본 URLconf를 ``mysite/urls.py``\ 에 생성했습니다. 게다가 자동으로 :setting:`ROOT_URLCONF`\ 을 =(``settings.py`` 안에 있는) ``mysite/urls.py``\ 를 가리키도록 설정 했습니다. - -:: - - ROOT_URLCONF = 'mysite.urls' - -예제를 보겠습니다. ``mysite/urls.py``\ 를 아래와 같이 수정합니다. - -:: - - from django.conf.urls import patterns, include, url - - from django.contrib import admin - admin.autodiscover() - - urlpatterns = patterns('', - url(r'^polls/$', 'polls.views.index'), - url(r'^polls/(?P\d+)/$', 'polls.views.detail'), - url(r'^polls/(?P\d+)/results/$', 'polls.views.results'), - url(r'^polls/(?P\d+)/vote/$', 'polls.views.vote'), - url(r'^admin/', include(admin.site.urls)), - ) - -여기까지의 내용을 설명하면, 누군가 웹 사이트에 "/polls/23/"\ 이라는 요청을 하면, Django는 :setting:`ROOT_URLCONF` 설정이 가리키고 있기 때문에 위의 파이썬 모듈을 로드 할 것 입니다. 위의 파이썬 모듈은 ``urlpatterns``라는 이름을 가진 변수를 찾습니다. 그리고, 정규표현식들을 순서대로 순회 합니다. 위의 파이썬 모듈이 일치하는 정규표현식을 찾았을때 -- ``r'^polls/(?P\d+)/$'`` -- 위의 파이썬 모듈은 ``polls/views.py``에 있는 ``detail()`` 함수를 로드 합니다. 끝으로 파이썬 모듈은 아래와 같이 ``detail()`` 함수를 호출 합니다. - -:: - - detail(request=, poll_id='23') - -``poll_id='23'``\ 는 ``(?P\d+)``\ 에서 온 것 입니다. 패턴 주위에 괄호()를 사용해서 그 패턴과 일치하는 텍스트를 "포"하고, 뷰 함수에게 인자로 보냅니다; ``?P``\ 는 일치하는 패턴을 인식하는데 사용 할 이름을 정의 합니다. 그리고 ``\d+``\ 는 숫자가 나와야 할 순서를 의미하는 정규표현식입니다.(역자 주: 정규착 표현식에서 \d는 0~9 사이의 숫자를 의미하고 +는 앞 문자가 1번 이상 나타나면 된다는 것을 의미 합니다. 따라서, 1개 이상의 숫자가 있으면 된다는 뜻입니다. - -URL 패턴들은 정규표현식이기 때문에, 무엇을 하든 제한이 없습니다. 그리고, 아래와 같은 악취미가 있지 않는 한 ``.php``\ 같은 URL 부스러기 들을 붙일 필요가 없습니다. - -:: - - (r'^polls/latest\.php$', 'polls.views.index'), - -위 처럼, 하지마세요. 바보 같으니까요. - -이런 정규표현식들은 GET, POST 파라미터들 또는 도메인 이름을 검색하지는 않는 다는 것을 기억하십시오. 예를 들어 ``http://www.example.com/myapp/``\ 을 향한 요청에서, URLconf는 ``myapp/``\ 만 찾을 것 입니다. ``http://www.example.com/myapp/?page=3``\ 를 향한 요청에서, URLconf는 ``myapp/``\ 만 찾을 것 입니다. - -만약, 정규표현식에 대해 도움이 필요하면, `Wikipedia's entry`_ 그리고 :mod:`re` 모듈의 문서를 참고하십시오. 또, Jeffrey Friedl 의 오라일리의 책 "Mastering Regular Expressions" 도 끝내줍니다. - -Finally, a performance note : 처음 URLconf 모듈이 로드 되었을때, 이 정규표현식들은 컴파일 되었습니다. 그래서, 매우 빠릅니다. - -.. _Wikipedia's entry: http://en.wikipedia.org/wiki/Regular_expression - -첫 번째 뷰 작성 하기 -===================== - -우리는 URLconf 만 만들었습니다. 아직 아무 뷰도 생성 하지 않았습니다. 그렇지만 이전에 Django가 아래의 URLconf를 철저히 따르고 있는지 확실히 하십시오. - -이제 Django 개발 웹 서버를 구동합니다. - -.. code-block:: bash - - python manage.py runserver - -웹브라우저에서 "http://localhost:8000/polls/"\ 로 이동 하십시오. -당신은 유쾌하게 컬러링된 아래 메세지의 에러 페이지를 보게 될 것입니다. - -:: - - ViewDoesNotExist at /polls/ - - Could not import polls.views.index. View does not exist in module polls.views. - -이 오류는 ``polls/views.py`` 모듈에 ``index()`` 함수를 작성한 적이 없기 때문에 발생합니다. - -"/polls/23/", "/polls/23/results/" 그리고 "/polls/23/vote/" 도 시도해 보십시오. 오류 메세지들은 Django가 어떤 뷰에 접근 하려고 했는지 알려줍니다(그리고, 당신이 뷰들을 작성 하지 않았기 때문에 찾기에 실패 합니다). - -첫 번째 뷰를 작성 합니다. ``polls/views.py``를 열어서 아래의 파이썬 코드를 입력 합니다. - -:: - - from django.http import HttpResponse - - def index(request): - return HttpResponse("Hello, world. You're at the poll index.") - -실제로 가능한 가장 간단한 뷰입니다. 브라우저에서 "/polls/" 로 이동하면, 당신이 작성한 텍스트를 볼 수 있어야 합니다. - -뷰를 몇 개 더 추가해 봅니다. 이 뷰들은 인자를 가지기 때문에 조금씩 다릅니다. (기억하세요, URLconf에서 정규표현식으로 무엇이 '포착'되었든지 인자로 들어옵니다.) - -:: - - def detail(request, poll_id): - return HttpResponse("You're looking at poll %s." % poll_id) - - def results(request, poll_id): - return HttpResponse("You're looking at the results of poll %s." % poll_id) - - def vote(request, poll_id): - return HttpResponse("You're voting on poll %s." % poll_id) - -브라우저에서 "/polls/34/"\ 를 둘러보세요. `detail()` 메소드를 실행하고, URL에 입력한 ID를 나타냅니다. "/polls/34/results/"\ 과 "/polls/34/vote/"\ 도 시도해 보세요. -- 이 URL들은 placeholder results와 투표 페이지를 보여줍니다. - -실제로 동작하는 뷰 작성 하기 -====================================== - -각각의 뷰는 둘 중에 하나를 수행합니다. 요청받은 페이지에 대한 컨텐츠를 가지고 있는 :class:`~django.http.HttpResponse` 객체를 반환 하거나 :exc:`~django.http.Http404` 같은 예외를 발생합니다. 나머지는 당신에게 달렸습니다. - -당신의 뷰는 데이터베이스에서 레코드들을 읽을수도, 아닐수도 있습니다. Django에 있는 것 같은 템플릿 시스템 --또는 서드 파티 파이썬 템플릿 시스템 -- 을 사용할수도, 안할수도 있습니다. -PDF 파일을 생성하거나, XML을 출력하거나, ZIP파일을 생성하거나, 당신이 무엇을 원하든 간에 원하는 파이썬 라이브러리들을 사용 하십시오. - -모든 Django가 필요한 것은 :class:`~django.http.HttpResponse`\ 입니다. 또는 예외 입니다. - -사용하기 편리하므로, 우리가 :doc:`Tutorial 1 `\ 에서 다루었던 Django가 가지고 있는 데이터베이스 API를 사용해 봅시다. 날짜 순서로 정렬하고, 콤마로 나눈, 시스템에 있는 최근 5개의 투표 질문들을 보여주는``index()`` 뷰를 만들어봅시다. - -:: - - from polls.models import Poll - from django.http import HttpResponse - - def index(request): - latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] - output = ', '.join([p.question for p in latest_poll_list]) - return HttpResponse(output) - -위의 코드에는 문제가 있습니다. 페이지 디자인을 뷰에 하드 코딩했습니다. 만약 페이지가 보이는 형태를 변경하려고 한다면, 파이썬 코드를 수정 해야 합니다. -그래서 디자인을 파이썬으로부터 분리하기 위해서 Django 템플릿 시스템을 이용합니다. - -:: - - from django.template import Context, loader - from polls.models import Poll - from django.http import HttpResponse - - def index(request): - latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] - t = loader.get_template('polls/index.html') - c = Context({ - 'latest_poll_list': latest_poll_list, - }) - return HttpResponse(t.render(c)) - -위의 코드는 "polls/index.html" 템플릿을 로드하고 컨텍스트를 전달합니다. -컨텍스트는 파이썬 객체들 이름을 가진 사전 매핑 템플릿 변수 입니다. - -페이지를 새로고침 하십시오. 에러를 보게 될것 입니다:: - - TemplateDoesNotExist at /polls/ - polls/index.html - -아. 아직 템플릿이 없군요. 첫 번째, 당신의 파일시스템 아무 곳에나 Django가 접근할 수 있는 곳에 디렉토리를 생성하십시오. (Django runs as whatever user your -server runs.) 대신, 그 파일들은 문서 root에 넣지 마세요. 보안 문제가 있으므로, 디렉토리를 퍼블릭으로 만들지 않아야 합니다. -그리고, ``settings.py``\ 의 :setting:`TEMPLATE_DIRS`\ 를 수정해서, Django에게 어디서 템플릿들을 찾을 수 있는지 알려 주십시오. -- 자습서 2의 "Customize the admin look and feel" 섹션에서 한것 처럼 하면 됩니다. - -위의 내용을 완료 했다면, ``polls`` 디렉토리를 템플릿 디렉토리에 생성하십시오. -그 안에 ``index.html`` 파일을 생성하십시오. 우리의 ``loader.get_template('polls/index.html')`` 코드는 파일 시스템에 있는 "[template_directory]/polls/index.html" 과 매핑 된다는 것을 기억하십시오. - -아래의 코드를 템플릿에 입력하십시오. - -.. code-block:: html+django - - {% if latest_poll_list %} - - {% else %} -

No polls are available.

- {% endif %} - -웹 브라우저에서 페이지를 로드하면, 자습서 1의 "What's up" 투표를 포함하는 bulleted-list를 볼 수 있어야 합니다. 이 링크는 투표의 세부 페이지를 가리킵니다. - -지름길: render_to_response() --------------------------------- - -render_to_response()는 템플릿을 로드하고, 컨텍스트를 채우고, :class:`~django.http.HttpResponse` 객체를 렌더링된 템플릿의 결과와 함께 반환하기 위해 자주 사용하는 구문입니다. Django는 지름길을 제공 합니다. 전체 ``index()`` 뷰를 재작성했습니다. - -:: - - from django.shortcuts import render_to_response - from polls.models import Poll - - def index(request): - latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] - return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list}) - -모든 뷰에서 한 번만 위의 작업을 하면, 더이상 :mod:`~django.template.loader`, :class:`~django.template.Context` 그리고 :class:`~django.http.HttpResponse`\ 를 불러올 필요가 없다는 것을 기억하십시오. - -:func:`~django.shortcuts.render_to_response` 함수는 템플릿 이름을 첫 번째 인자로, 선택 가능한 두 번째 인자로 사전을 갖습니다. :func:`~django.shortcuts.render_to_response` 함수는 주어진 컨텍스트와 함께 렌더링된 템플릿 객체의 :class:`~django.http.HttpResponse` 를 반환 합니다. - -404 띄우기 -=========== - -세부 투표 뷰를 봅시다. -- 세부 투표 뷰는 주어진 투표에 대한 제목을 표시합니다. 아래에 뷰가 있습니다:: - - from django.http import Http404 - # ... - def detail(request, poll_id): - try: - p = Poll.objects.get(pk=poll_id) - except Poll.DoesNotExist: - raise Http404 - return render_to_response('polls/detail.html', {'poll': p}) - -위의 코드에는 이전에 보지 못한 개념이 있습니다. 투표와 함께 요청받은 ID가 존재 하지 않으면 뷰가 :exc:`~django.http.Http404` 예외를 띄웁니다. - -`polls/detail.html``\ 에 무엇을 넣을지는 조금 나중에 고민할 것입니다. 그렇지만, 빠르게 예제를 동작하게 만들고 싶다면, 단지 - -:: - - {{ poll }} - -코드가 지금 당장 코드를 시작 할 수 있게 할 것 입니다. - -지름길: get_object_or_404() -------------------------------- - -get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`\ 를 사용하기 위해서 자주 사용하는 구문입니다. 객체가 없을 때는 :exc:`~django.http.Http404`\ 를 띄웁니다. Django는 지름길을 제공합니다. ``detail()`` 뷰를 재작성했습니다. - -:: - - from django.shortcuts import render_to_response, get_object_or_404 - # ... - def detail(request, poll_id): - p = get_object_or_404(Poll, pk=poll_id) - return render_to_response('polls/detail.html', {'poll': p}) - -:func:`~django.shortcuts.get_object_or_404` 함수는 Django 모델을 첫 번째 인자로 받고, :meth:`~django.db.models.query.QuerySet.get` 함수에서 전달된 임의의 숫자를 키워드 인자로 받습니다. 만약, 객체가 존재하지 않으면, :exc:`~django.http.Http404`\ 를 띄웁니다. - -.. admonition:: 철학 - - 왜 우리가 더 높은 레벨에서 :exc:`~django.core.exceptions.ObjectDoesNotExist`를 사용해서 자동으로 예외를 처리하는 대신 헬퍼 함수인 :func:`~django.shortcuts.get_object_or_404`를 사용 했을까요? - - - 또는 :exc:`~django.core.exceptions.ObjectDoesNotExist`를 사용하는 대신 :exc:`~django.http.Http404`를 띄우는 모델 API를 가지도록 했을까요? - :exc:`~django.core.exceptions.ObjectDoesNotExist`? - - 그 이유는 모델 계층을 뷰 계층에 결합 하기 때문입니다. - Django의 으뜸가는 디자인 목표중 하나는 느슨한 결합을 유지하는 것입니다. - -물론 :func:`~django.shortcuts.get_object_or_404`와 거의 똑같이 동작하는 :func:`~django.shortcuts.get_list_or_404` 함수도 있습니다. -- :meth:`~django.db.models.query.QuerySet.get` 대신 :meth:`~django.db.models.query.QuerySet.filter`를 사용하는 경우는 제외합니다. :func:`~django.shortcuts.get_list_or_404` 는 리스트가 비어 있을 경우에 :exc:`~django.http.Http404`를 띄웁니다. - -404 (page not found) 뷰 작성하기 -================================= - -뷰에서 :exc:`~django.http.Http404`\ 를 일으키면, Django는 404 오류를 다루기로 한 특별한 뷰를 로드할 것 입니다. Django는 루트 URLconf(그리고 오직 루트 URLconf에서 ``handler404``를 설정해야 합니다. 이외의 위치에서는 모두 무시합니다.)에서 ``handler404`` python dotted syntax 내의 문자열 변수를 찾음으로써 404오류를 다루기로한 특별한 뷰를 찾을 것입니다. -- 같은 형태로 일반적인 URLconf 콜백들을 사용 합니다. 404 뷰 자체로는 특별한게 아무것도 없습니다. 일반적인 뷰일 뿐입니다. - -일반적으로는 404 뷰들을 만드는데 신경쓸 필요가 없습니다. 만약 ``handler404``\ 를 설정하지 않으면, 내장된 :func:`django.views.defaults.page_not_found`\ 를 기본적으로 사용합니다. 이 경우에도 여전히 한 가지 할 일이 남아 있기는 합니다. ``404.html`` 템플릿을 root템플릿 디렉토리에 생성 해야 합니다. 기본적인 404 뷰는 그 템플릿을 모든 404 오류에 사용 할 것입니다. 만약 :setting:`DEBUG`\ 를 ``False`` (in your settings module)로 설정 하거나, ``404.html`` -파일을 만들지 않으면, ``Http500``\ 을 대신 띄웁니다. 그런 이유로 ``404.html``\ 을 생성하는 것을 기억하십시오. - -404 뷰들에 대해서 몇 가지더 알아두어야 할 것이 있습니다. - -* :setting:`DEBUG`\ 를 ``True``\ 로 설정 했다면(설정 모듈 안에서) 404 뷰는 절대로 사용하지 않을 것입니다. (그리고 ``404.html`` 템플릿은 절대 렌더 되지 않습니다). 왜냐하면 traceback을 대신 표시하기 때문입니다. - -* 404 뷰는 Django가 URLconf 내의 모든 정규표현식을 검색하고도, 일치하는 표현을 찾지 못했을 때도 호출합니다. - - -500 (server error) 뷰 작성하기 -=============================== - -비슷하게, 루트 URLconf는 서버 오류인 경우에 호출하기 위한 뷰를 가리키는 ``handler500``\ 을 정의하고 있을 것입니다. 서버 오류는 뷰 코드에서 런타임 에러가 있을때 발생합니다. - -템플릿 시스템 사용하기 -======================= - -투표 어플리케이션의 ``detail()`` 뷰로 돌아가 보도록 합니다. ``poll``\ 이 컨텍스트 변수로 주어졌을때, "polls/detail.html" 템플릿이 어떻게 되는지 보도록 합니다. - -.. code-block:: html+django - -

{{ poll.question }}

-
    - {% for choice in poll.choice_set.all %} -
  • {{ choice.choice }}
  • - {% endfor %} -
- -템플릿 시스템은 변수 어트리뷰트들에 접근 하기 위해서 dot-lookup 구문을 사용 합니다. ``{{ poll.question }}``\ 의 예제에서 보면, Django는 처음에 ``poll`` 객체에서 사전을 찾습니다. 찾기에 실패하면, 어트리뷰트를 조회 합니다. -- 이 경우에는 잘 동작 합니다. 만약, 어트리뷰트 조회에 실패하면, list-index 조회를 시도 합니다. - -:ttag:`{% for %}` 루프에서 메소드 호출이 발생합니다: -``poll.choice_set.all`` 은 파이썬 코드 ``poll.choice_set.all()``로 변환 합니다. 파이썬 코드 ``poll.choice_set.all()``\ 는 선택한 객체들의 an iterable을 반환하고, :ttag:`{% for %}` 태그에서 사용하기 적당합니다. - -템플릿에 대한 자세한 내용은 :doc:`template guide
` 를 보세요. - -URLconfs를 단순화 하기 -======================== - -뷰와 템플릿 시스템사이를 종횡무진 하기에는 시간이 좀 걸립니다. URLconf를 수정 하는 동안, 내부에 상당한 양의 불필요한 중복이 있다는 것을 알아차렸을 것입니다. - -:: - - urlpatterns = patterns('', - url(r'^polls/$', 'polls.views.index'), - url(r'^polls/(?P\d+)/$', 'polls.views.detail'), - url(r'^polls/(?P\d+)/results/$', 'polls.views.results'), - url(r'^polls/(?P\d+)/vote/$', 'polls.views.vote'), - ) - -다시말해 ``polls.views``\ 가 모든 콜백에 있습니다. - -왜냐하면 공통적인 경우에, URLconf 프레임워크는 공통적인 prefixs들에 대한 지름길을 제공 합니다. 당신은 공통적인 prefix들을 뽑아 낼수 있습니다. 그리고, 뽑아낸 prefix들을 :func:`~django.conf.urls.patterns`\ 에 아래와 같이 첫 번째 인자로 추가 할 수 있습니다. - -:: - - urlpatterns = patterns('polls.views', - url(r'^polls/$', 'index'), - url(r'^polls/(?P\d+)/$', 'detail'), - url(r'^polls/(?P\d+)/results/$', 'results'), - url(r'^polls/(?P\d+)/vote/$', 'vote'), - ) - -이 방법은 이전의 포매팅과 기능적으로 일치합니다. 더 깔끔합니다. - -일반적으로 URLconf의 모든 콜백에 하나의 애플리케이션을 위한 prefix를 적용하고 싶지 않다면, 여러 개의 :func:`~django.conf.urls.patterns`\ 를 연결 할 수 있습니다. -. ``mysite/urls.py`` 전체는 아래와 같습니다. - -:: - - from django.conf.urls import patterns, include, url - - from django.contrib import admin - admin.autodiscover() - - urlpatterns = patterns('polls.views', - url(r'^polls/$', 'index'), - url(r'^polls/(?P\d+)/$', 'detail'), - url(r'^polls/(?P\d+)/results/$', 'results'), - url(r'^polls/(?P\d+)/vote/$', 'vote'), - ) - - urlpatterns += patterns('', - url(r'^admin/', include(admin.site.urls)), - ) - -URLconf의 결합도 낮추기 -======================= - -하는 김에 우리는 Django 프로젝트 설정으로 부터 우리의 투표-앱 URL 들을 분리하는 시간을 가져야 합니다. Django 앱들은 플러그인 처럼 사용 할수 있도록 만들었습니다. -- 각각의 특정한 앱이 최소한의 수정으로 다른 Django installation 으로 이전 가능해야 합니다. - -이 시점에서 투표 앱은 상당히 결합도가 낮습니다. ``python manage.py startapp``\ 가 생성한 엄격한 디렉토리 구조에 감사하기 바랍니다. 그렇나, 단 하나 URLconf가 Django 설정들과 결합되어 있습니다. - -``mysite/urls.py``\ 에 있는 URL들은 수정했습니다. 그러나, 앱의 URL 디자인은 Django installation이 아니라, 특정 앱 지향적입니다. -- 그래서 URL들을 앱 디렉토리 안으로 이동합니다. - -``mysite/urls.py`` 파일을 ``polls/urls.py``\ 로 복사 하십시오. 그리고, ``mysite/urls.py``\ 에서 투표-한정 URL들을 제거 하고, :func:`~django.conf.urls.include`\ 를 그 자리에 추가하도록 변경합니다. - -:: - - from django.conf.urls import patterns, include, url - - from django.contrib import admin - admin.autodiscover() - - urlpatterns = patterns('', - url(r'^polls/', include('polls.urls')), - url(r'^admin/', include(admin.site.urls)), - ) - -:func:`~django.conf.urls.include`\ 은 간단하게 다른 URLconf를 참조 합니다. -정규표현식은 ``$``\ (문자열의 끝과 일치하는 문자)를 가지지 않고, trailling slash를 가지는 점을 기억하십시오. 어디든지 Django가 :func:`~django.conf.urls.include` 함수를 만나면, 해당 시점에서 URL의 일치하는 부분을 잘라냅니다. 그리고, 남은 문자열을 추가 처리를 위해서 불러들인 URLconf로 전송 합니다. - -사용자가 이 시스템에서 "/polls/34/"\ 로 이동하는 경우 무슨 일이 생기는지 보십시오. - -* Django는 ``'^polls/'``\ 에서 일치하는 것을 찾을 것입니다. - -* 그리고나서, Django 는 일치하는 문자(``"polls/"``)를 벗겨 낼것 입니다. - 남은 문자 -- ``"34/"`` --를 'polls.urls' URLconf로 추가 처리를 위해서 보냅니다. - - -이제, URLconf와 Django 설정의 결합도를 낮추었습니다. 우리는 개별 라인 맨 앞에 있는 "polls/"를 삭제하고, 관리자 사이트에 등록한 라인들을 삭제 함으로써 ``polls.urls``와 URLconf의 결합도를 낮추었습니다. ``polls/urls.py`` 파일은 지금 아래와 같아야 합니다. :: - - from django.conf.urls import patterns, include, url - - urlpatterns = patterns('polls.views', - url(r'^$', 'index'), - url(r'^(?P\d+)/$', 'detail'), - url(r'^(?P\d+)/results/$', 'results'), - url(r'^(?P\d+)/vote/$', 'vote'), - ) - -:func:`~django.conf.urls.include`\ 와 URLconf의 결합도를 낮추는 아이디어는 URL들의 플러그인플레이를 쉽게 만들어 줍니다. 이제 투표들은 각자 URLconf를 가지고 있습니다. 투표들은 "/polls/" 밑에도 있을 수 있고, "/fun_polls/" 밑에도, "/content/polls/" 밑에도, 그리고 다른 어떠한 루트 경로 에도 있을 수 있습니다. 그리고 앱은 여전히 잘 동작 할 것 입니다. - -모든 투표 앱들은 절대 경로가 아니라, 상대 경로를 사용합니다. - -뷰를 작성 하는 것에 익숙해 지면 단순한 폼 처리와 제너릭 뷰를 배우기 위해서 :doc:`part 4 of this tutorial -
`\ 를 읽어보십시오. +===================================== +첫 번째 Django 앱 만들기, part 3 +===================================== + +이 자습서는 :doc:`Tutorial 2
`\ 의 마지막에 이어서 시작 합니다. 우리는 계속해서 "뷰"라고 하는 퍼블릭 인터페이스를 작성하는데 중점을 두고 웹-투표 애플리케이션을 계속 합니다. + +철학 +========== + +뷰는 Django 애플리케이션에서 특정한 기능을 수행하거나, 특정한 템플릿을 가지는 웹 페이지의 "유형" 입니다. 예를 들어 웹블로그 애플리케이션은 아래와 같은 뷰들을 가질 것 입니다. + +* 블로그 홈페이지 -- 최신 엔트리 몇 개를 표시 합니다. + +* 엔트리 "세부" 페이지 -- 한 개의 엔트리를 위한 퍼머링크 페이지입니다. + +* 연도별 아카이브 페이지 -- 주어진 연도에 있는 모든 달들을 엔트리와 함께 나타냅니다. + + +* 월별 아카이브 페이지 -- 주어진 달에 있는 모든 날들을 엔트리와 함께 나타냅니다. + + +* 일별 아카이브 페이지 -- 주어진 날에 있는 모든 엔트리를 나타냅니다. + +* 코멘트 달기 -- 주어진 엔트리에 코멘트를 포스팅 합니다. + +투표 애플리케이션에는 아래와 같이 네 개의 뷰가 있습니다. + +* 투표 "인덱스" 페이지 -- 몇 개의 최신 투표를 나타냅니다. + +* 투표 "세부" 페이지 -- 투표의 질문을 투표 할 수 있는 폼과 함께 나타냅니다. 투표 결과는 보여주지 않습니다. + + +* 투표 "결과" 페이지 -- 특정 투표의 결과를 나타냅니다. + +* 투표 하기 -- 특정 투표에서 특정 선택지에 투표합니다. + + +Django 에서 개별 뷰는 간단한 파이썬 함수로 나타냅니다. + +URL 디자인 하기 +================ + +URL 구조를 디자인 하는 것은 뷰를 작성하는 첫 번째 단계입니다. URLconf라는 파이썬 모듈을 생성함으로써, URL구조를 디자인 할 수 있습니다. URLconfs는 Django가 주어진 URL을 주어진 파이썬 코드와 연결하는 방법 입니다. + +사용자가 Django-powered 페이지를 요청 할 때, 시스템은 Python dotted syntax에 있는 문자열을 포함하는 :setting:'ROOT_URLCONF' 설정을 참고 합니다. Django 는 URLconf 모듈을 로드 합니다. 그리고, 아래와 같은 포맷의 튜플인 모듈-레벨 변수인 ``urlpatterns``\ 를 검색합니다. + +:: + + (regular expression, Python callback function [, optional dictionary]) + +Django는 첫 번째 정규표현식을 시작으로, 일치하는 결과를 찾을 때 까지 요청 받은 URL을 각각의 정규표현식과 비교하면서 리스트 아래로 내려갑니다. + +일치하는 결과를 찾으면, Django는 파이썬 콜백 함수를 호출 합니다. 이 때, :class:`~django.http.HttpRequest` 객체를 첫 번째 인자로 하고, 정규표현식에서 찾은 임의의 값을 키워드 인자로 가집니다. 옵션으로 그 사전에서 임의의 키워드(튜플의 세 번째 아이템)를 가져다가 사용 합니다. + +:class:`~django.http.HttpRequest` 객체에 대해서 자세히 알고 싶다면, :doc:`/ref/request-response`\ 를 참고 하세요. URLconfs 에 대해서 자세히 알고 싶다면, :doc:`/topics/http/urls`\ 를 참고 하세요. + +자습서 1에서 처음 ``django-admin.py startproject mysite`` 를 실행 했을때, 기본 URLconf를 ``mysite/urls.py``\ 에 생성했습니다. 게다가 자동으로 :setting:`ROOT_URLCONF`\ 을 =(``settings.py`` 안에 있는) ``mysite/urls.py``\ 를 가리키도록 설정 했습니다. + +:: + + ROOT_URLCONF = 'mysite.urls' + +예제를 보겠습니다. ``mysite/urls.py``\ 를 아래와 같이 수정합니다. + +:: + + from django.conf.urls import patterns, include, url + + from django.contrib import admin + admin.autodiscover() + + urlpatterns = patterns('', + url(r'^polls/$', 'polls.views.index'), + url(r'^polls/(?P\d+)/$', 'polls.views.detail'), + url(r'^polls/(?P\d+)/results/$', 'polls.views.results'), + url(r'^polls/(?P\d+)/vote/$', 'polls.views.vote'), + url(r'^admin/', include(admin.site.urls)), + ) + +여기까지의 내용을 설명하면, 누군가 웹 사이트에 "/polls/23/"\ 이라는 요청을 하면, Django는 :setting:`ROOT_URLCONF` 설정이 가리키고 있기 때문에 위의 파이썬 모듈을 로드 할 것 입니다. 위의 파이썬 모듈은 ``urlpatterns``\ 라는 이름을 가진 변수를 찾습니다. 그리고, 정규표현식들을 순서대로 순회 합니다. 위의 파이썬 모듈이 일치하는 정규표현식을 찾았을때 -- ``r'^polls/(?P\d+)/$'`` -- 위의 파이썬 모듈은 ``polls/views.py``\ 에 있는 ``detail()`` 함수를 로드 합니다. 끝으로 파이썬 모듈은 아래와 같이 ``detail()`` 함수를 호출 합니다. + +:: + + detail(request=, poll_id='23') + +``poll_id='23'``\ 는 ``(?P\d+)``\ 에서 온 것 입니다. 패턴 주위에 괄호()를 사용해서 그 패턴과 일치하는 텍스트를 "포"하고, 뷰 함수에게 인자로 보냅니다; ``?P``\ 는 일치하는 패턴을 인식하는데 사용 할 이름을 정의 합니다. 그리고 ``\d+``\ 는 숫자가 나와야 할 순서를 의미하는 정규표현식입니다.(역자 주: 정규착 표현식에서 \d는 0~9 사이의 숫자를 의미하고 +는 앞 문자가 1번 이상 나타나면 된다는 것을 의미 합니다. 따라서, 1개 이상의 숫자가 있으면 된다는 뜻입니다. + +URL 패턴들은 정규표현식이기 때문에, 무엇을 하든 제한이 없습니다. 그리고, 아래와 같은 악취미가 있지 않는 한 ``.php``\ 같은 URL 부스러기 들을 붙일 필요가 없습니다. + +:: + + (r'^polls/latest\.php$', 'polls.views.index'), + +위 처럼, 하지마세요. 바보 같으니까요. + +이런 정규표현식들은 GET, POST 파라미터들 또는 도메인 이름을 검색하지는 않는 다는 것을 기억하십시오. 예를 들어 ``http://www.example.com/myapp/``\ 을 향한 요청에서, URLconf는 ``myapp/``\ 만 찾을 것 입니다. ``http://www.example.com/myapp/?page=3``\ 를 향한 요청에서, URLconf는 ``myapp/``\ 만 찾을 것 입니다. + +만약, 정규표현식에 대해 도움이 필요하면, `Wikipedia's entry`_ 그리고 :mod:`re` 모듈의 문서를 참고하십시오. 또, Jeffrey Friedl 의 오라일리의 책 "Mastering Regular Expressions" 도 끝내줍니다. + +Finally, a performance note : 처음 URLconf 모듈이 로드 되었을때, 이 정규표현식들은 컴파일 되었습니다. 그래서, 매우 빠릅니다. + +.. _Wikipedia's entry: http://en.wikipedia.org/wiki/Regular_expression + +첫 번째 뷰 작성 하기 +===================== + +우리는 URLconf 만 만들었습니다. 아직 아무 뷰도 생성 하지 않았습니다. 그렇지만 이전에 Django가 아래의 URLconf를 철저히 따르고 있는지 확실히 하십시오. + +이제 Django 개발 웹 서버를 구동합니다. + +.. code-block:: bash + + python manage.py runserver + +웹브라우저에서 "http://localhost:8000/polls/"\ 로 이동 하십시오. +당신은 유쾌하게 컬러링된 아래 메세지의 에러 페이지를 보게 될 것입니다. + +:: + + ViewDoesNotExist at /polls/ + + Could not import polls.views.index. View does not exist in module polls.views. + +이 오류는 ``polls/views.py`` 모듈에 ``index()`` 함수를 작성한 적이 없기 때문에 발생합니다. + +"/polls/23/", "/polls/23/results/" 그리고 "/polls/23/vote/" 도 시도해 보십시오. 오류 메세지들은 Django가 어떤 뷰에 접근 하려고 했는지 알려줍니다(그리고, 당신이 뷰들을 작성 하지 않았기 때문에 찾기에 실패 합니다). + +첫 번째 뷰를 작성 합니다. ``polls/views.py``\ 를 열어서 아래의 파이썬 코드를 입력 합니다. + +:: + + from django.http import HttpResponse + + def index(request): + return HttpResponse("Hello, world. You're at the poll index.") + +실제로 가능한 가장 간단한 뷰입니다. 브라우저에서 "/polls/" 로 이동하면, 당신이 작성한 텍스트를 볼 수 있어야 합니다. + +뷰를 몇 개 더 추가해 봅니다. 이 뷰들은 인자를 가지기 때문에 조금씩 다릅니다. (기억하세요, URLconf에서 정규표현식으로 무엇이 '포착'되었든지 인자로 들어옵니다.) + +:: + + def detail(request, poll_id): + return HttpResponse("You're looking at poll %s." % poll_id) + + def results(request, poll_id): + return HttpResponse("You're looking at the results of poll %s." % poll_id) + + def vote(request, poll_id): + return HttpResponse("You're voting on poll %s." % poll_id) + +브라우저에서 "/polls/34/"\ 를 둘러보세요. `detail()` 메소드를 실행하고, URL에 입력한 ID를 나타냅니다. "/polls/34/results/"\ 과 "/polls/34/vote/"\ 도 시도해 보세요. -- 이 URL들은 placeholder results와 투표 페이지를 보여줍니다. + +실제로 동작하는 뷰 작성 하기 +====================================== + +각각의 뷰는 둘 중에 하나를 수행합니다. 요청받은 페이지에 대한 컨텐츠를 가지고 있는 :class:`~django.http.HttpResponse` 객체를 반환 하거나 :exc:`~django.http.Http404` 같은 예외를 발생합니다. 나머지는 당신에게 달렸습니다. + +당신의 뷰는 데이터베이스에서 레코드들을 읽을수도, 아닐수도 있습니다. Django에 있는 것 같은 템플릿 시스템 --또는 서드 파티 파이썬 템플릿 시스템 -- 을 사용할수도, 안할수도 있습니다. +PDF 파일을 생성하거나, XML을 출력하거나, ZIP파일을 생성하거나, 당신이 무엇을 원하든 간에 원하는 파이썬 라이브러리들을 사용 하십시오. + +모든 Django가 필요한 것은 :class:`~django.http.HttpResponse`\ 입니다. 또는 예외 입니다. + +사용하기 편리하므로, 우리가 :doc:`Tutorial 1
`\ 에서 다루었던 Django가 가지고 있는 데이터베이스 API를 사용해 봅시다. 날짜 순서로 정렬하고, 콤마로 나눈, 시스템에 있는 최근 5개의 투표 질문들을 보여주는``index()`` 뷰를 만들어봅시다. + +:: + + from polls.models import Poll + from django.http import HttpResponse + + def index(request): + latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] + output = ', '.join([p.question for p in latest_poll_list]) + return HttpResponse(output) + +위의 코드에는 문제가 있습니다. 페이지 디자인을 뷰에 하드 코딩했습니다. 만약 페이지가 보이는 형태를 변경하려고 한다면, 파이썬 코드를 수정 해야 합니다. +그래서 디자인을 파이썬으로부터 분리하기 위해서 Django 템플릿 시스템을 이용합니다. + +:: + + from django.template import Context, loader + from polls.models import Poll + from django.http import HttpResponse + + def index(request): + latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] + t = loader.get_template('polls/index.html') + c = Context({ + 'latest_poll_list': latest_poll_list, + }) + return HttpResponse(t.render(c)) + +위의 코드는 "polls/index.html" 템플릿을 로드하고 컨텍스트를 전달합니다. +컨텍스트는 파이썬 객체들 이름을 가진 사전 매핑 템플릿 변수 입니다. + +페이지를 새로고침 하십시오. 에러를 보게 될것 입니다:: + + TemplateDoesNotExist at /polls/ + polls/index.html + +아. 아직 템플릿이 없군요. 첫 번째, 당신의 파일시스템 아무 곳에나 Django가 접근할 수 있는 곳에 디렉토리를 생성하십시오. (Django runs as whatever user your +server runs.) 대신, 그 파일들은 문서 root에 넣지 마세요. 보안 문제가 있으므로, 디렉토리를 퍼블릭으로 만들지 않아야 합니다. +그리고, ``settings.py``\ 의 :setting:`TEMPLATE_DIRS`\ 를 수정해서, Django에게 어디서 템플릿들을 찾을 수 있는지 알려 주십시오. -- 자습서 2의 "Customize the admin look and feel" 섹션에서 한것 처럼 하면 됩니다. + +위의 내용을 완료 했다면, ``polls`` 디렉토리를 템플릿 디렉토리에 생성하십시오. +그 안에 ``index.html`` 파일을 생성하십시오. 우리의 ``loader.get_template('polls/index.html')`` 코드는 파일 시스템에 있는 "[template_directory]/polls/index.html" 과 매핑 된다는 것을 기억하십시오. + +아래의 코드를 템플릿에 입력하십시오. + +.. code-block:: html+django + + {% if latest_poll_list %} + + {% else %} +

No polls are available.

+ {% endif %} + +웹 브라우저에서 페이지를 로드하면, 자습서 1의 "What's up" 투표를 포함하는 bulleted-list를 볼 수 있어야 합니다. 이 링크는 투표의 세부 페이지를 가리킵니다. + +지름길: render_to_response() +-------------------------------- + +render_to_response()는 템플릿을 로드하고, 컨텍스트를 채우고, :class:`~django.http.HttpResponse` 객체를 렌더링된 템플릿의 결과와 함께 반환하기 위해 자주 사용하는 구문입니다. Django는 지름길을 제공 합니다. 전체 ``index()`` 뷰를 재작성했습니다. + +:: + + from django.shortcuts import render_to_response + from polls.models import Poll + + def index(request): + latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] + return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list}) + +모든 뷰에서 한 번만 위의 작업을 하면, 더이상 :mod:`~django.template.loader`, :class:`~django.template.Context` 그리고 :class:`~django.http.HttpResponse`\ 를 불러올 필요가 없다는 것을 기억하십시오. + +:func:`~django.shortcuts.render_to_response` 함수는 템플릿 이름을 첫 번째 인자로, 선택 가능한 두 번째 인자로 사전을 갖습니다. :func:`~django.shortcuts.render_to_response` 함수는 주어진 컨텍스트와 함께 렌더링된 템플릿 객체의 :class:`~django.http.HttpResponse` 를 반환 합니다. + +404 띄우기 +=========== + +세부 투표 뷰를 봅시다. -- 세부 투표 뷰는 주어진 투표에 대한 제목을 표시합니다. 아래에 뷰가 있습니다:: + + from django.http import Http404 + # ... + def detail(request, poll_id): + try: + p = Poll.objects.get(pk=poll_id) + except Poll.DoesNotExist: + raise Http404 + return render_to_response('polls/detail.html', {'poll': p}) + +위의 코드에는 이전에 보지 못한 개념이 있습니다. 투표와 함께 요청받은 ID가 존재 하지 않으면 뷰가 :exc:`~django.http.Http404` 예외를 띄웁니다. + +`polls/detail.html``\ 에 무엇을 넣을지는 조금 나중에 고민할 것입니다. 그렇지만, 빠르게 예제를 동작하게 만들고 싶다면, 단지 + +:: + + {{ poll }} + +코드가 지금 당장 코드를 시작 할 수 있게 할 것 입니다. + +지름길: get_object_or_404() +------------------------------- + +get_object_or404()는 :meth:`~django.db.models.query.QuerySet.get`\ 를 사용하기 위해서 자주 사용하는 구문입니다. 객체가 없을 때는 :exc:`~django.http.Http404`\ 를 띄웁니다. Django는 지름길을 제공합니다. ``detail()`` 뷰를 재작성했습니다. + +:: + + from django.shortcuts import render_to_response, get_object_or_404 + # ... + def detail(request, poll_id): + p = get_object_or_404(Poll, pk=poll_id) + return render_to_response('polls/detail.html', {'poll': p}) + +:func:`~django.shortcuts.get_object_or_404` 함수는 Django 모델을 첫 번째 인자로 받고, :meth:`~django.db.models.query.QuerySet.get` 함수에서 전달된 임의의 숫자를 키워드 인자로 받습니다. 만약, 객체가 존재하지 않으면, :exc:`~django.http.Http404`\ 를 띄웁니다. + +.. admonition:: 철학 + + 왜 우리가 더 높은 레벨에서 :exc:`~django.core.exceptions.ObjectDoesNotExist`를 사용해서 자동으로 예외를 처리하는 대신 헬퍼 함수인 :func:`~django.shortcuts.get_object_or_404`를 사용 했을까요? + + + 또는 :exc:`~django.core.exceptions.ObjectDoesNotExist`를 사용하는 대신 :exc:`~django.http.Http404`를 띄우는 모델 API를 가지도록 했을까요? + :exc:`~django.core.exceptions.ObjectDoesNotExist`? + + 그 이유는 모델 계층을 뷰 계층에 결합 하기 때문입니다. + Django의 으뜸가는 디자인 목표중 하나는 느슨한 결합을 유지하는 것입니다. + +물론 :func:`~django.shortcuts.get_object_or_404`와 거의 똑같이 동작하는 :func:`~django.shortcuts.get_list_or_404` 함수도 있습니다. -- :meth:`~django.db.models.query.QuerySet.get` 대신 :meth:`~django.db.models.query.QuerySet.filter`를 사용하는 경우는 제외합니다. :func:`~django.shortcuts.get_list_or_404` 는 리스트가 비어 있을 경우에 :exc:`~django.http.Http404`를 띄웁니다. + +404 (page not found) 뷰 작성하기 +================================= + +뷰에서 :exc:`~django.http.Http404`\ 를 일으키면, Django는 404 오류를 다루기로 한 특별한 뷰를 로드할 것 입니다. Django는 루트 URLconf(그리고 오직 루트 URLconf에서 ``handler404``를 설정해야 합니다. 이외의 위치에서는 모두 무시합니다.)에서 ``handler404`` python dotted syntax 내의 문자열 변수를 찾음으로써 404오류를 다루기로한 특별한 뷰를 찾을 것입니다. -- 같은 형태로 일반적인 URLconf 콜백들을 사용 합니다. 404 뷰 자체로는 특별한게 아무것도 없습니다. 일반적인 뷰일 뿐입니다. + +일반적으로는 404 뷰들을 만드는데 신경쓸 필요가 없습니다. 만약 ``handler404``\ 를 설정하지 않으면, 내장된 :func:`django.views.defaults.page_not_found`\ 를 기본적으로 사용합니다. 이 경우에도 여전히 한 가지 할 일이 남아 있기는 합니다. ``404.html`` 템플릿을 root템플릿 디렉토리에 생성 해야 합니다. 기본적인 404 뷰는 그 템플릿을 모든 404 오류에 사용 할 것입니다. 만약 :setting:`DEBUG`\ 를 ``False`` (in your settings module)로 설정 하거나, ``404.html`` +파일을 만들지 않으면, ``Http500``\ 을 대신 띄웁니다. 그런 이유로 ``404.html``\ 을 생성하는 것을 기억하십시오. + +404 뷰들에 대해서 몇 가지더 알아두어야 할 것이 있습니다. + +* :setting:`DEBUG`\ 를 ``True``\ 로 설정 했다면(설정 모듈 안에서) 404 뷰는 절대로 사용하지 않을 것입니다. (그리고 ``404.html`` 템플릿은 절대 렌더 되지 않습니다). 왜냐하면 traceback을 대신 표시하기 때문입니다. + +* 404 뷰는 Django가 URLconf 내의 모든 정규표현식을 검색하고도, 일치하는 표현을 찾지 못했을 때도 호출합니다. + + +500 (server error) 뷰 작성하기 +=============================== + +비슷하게, 루트 URLconf는 서버 오류인 경우에 호출하기 위한 뷰를 가리키는 ``handler500``\ 을 정의하고 있을 것입니다. 서버 오류는 뷰 코드에서 런타임 에러가 있을때 발생합니다. + +템플릿 시스템 사용하기 +======================= + +투표 어플리케이션의 ``detail()`` 뷰로 돌아가 보도록 합니다. ``poll``\ 이 컨텍스트 변수로 주어졌을때, "polls/detail.html" 템플릿이 어떻게 되는지 보도록 합니다. + +.. code-block:: html+django + +

{{ poll.question }}

+
    + {% for choice in poll.choice_set.all %} +
  • {{ choice.choice }}
  • + {% endfor %} +
+ +템플릿 시스템은 변수 어트리뷰트들에 접근 하기 위해서 dot-lookup 구문을 사용 합니다. ``{{ poll.question }}``\ 의 예제에서 보면, Django는 처음에 ``poll`` 객체에서 사전을 찾습니다. 찾기에 실패하면, 어트리뷰트를 조회 합니다. -- 이 경우에는 잘 동작 합니다. 만약, 어트리뷰트 조회에 실패하면, list-index 조회를 시도 합니다. + +:ttag:`{% for %}` 루프에서 메소드 호출이 발생합니다: +``poll.choice_set.all`` 은 파이썬 코드 ``poll.choice_set.all()``로 변환 합니다. 파이썬 코드 ``poll.choice_set.all()``\ 는 선택한 객체들의 an iterable을 반환하고, :ttag:`{% for %}` 태그에서 사용하기 적당합니다. + +템플릿에 대한 자세한 내용은 :doc:`template guide ` 를 보세요. + +URLconfs를 단순화 하기 +======================== + +뷰와 템플릿 시스템사이를 종횡무진 하기에는 시간이 좀 걸립니다. URLconf를 수정 하는 동안, 내부에 상당한 양의 불필요한 중복이 있다는 것을 알아차렸을 것입니다. + +:: + + urlpatterns = patterns('', + url(r'^polls/$', 'polls.views.index'), + url(r'^polls/(?P\d+)/$', 'polls.views.detail'), + url(r'^polls/(?P\d+)/results/$', 'polls.views.results'), + url(r'^polls/(?P\d+)/vote/$', 'polls.views.vote'), + ) + +다시말해 ``polls.views``\ 가 모든 콜백에 있습니다. + +왜냐하면 공통적인 경우에, URLconf 프레임워크는 공통적인 prefixs들에 대한 지름길을 제공 합니다. 당신은 공통적인 prefix들을 뽑아 낼수 있습니다. 그리고, 뽑아낸 prefix들을 :func:`~django.conf.urls.patterns`\ 에 아래와 같이 첫 번째 인자로 추가 할 수 있습니다. + +:: + + urlpatterns = patterns('polls.views', + url(r'^polls/$', 'index'), + url(r'^polls/(?P\d+)/$', 'detail'), + url(r'^polls/(?P\d+)/results/$', 'results'), + url(r'^polls/(?P\d+)/vote/$', 'vote'), + ) + +이 방법은 이전의 포매팅과 기능적으로 일치합니다. 더 깔끔합니다. + +일반적으로 URLconf의 모든 콜백에 하나의 애플리케이션을 위한 prefix를 적용하고 싶지 않다면, 여러 개의 :func:`~django.conf.urls.patterns`\ 를 연결 할 수 있습니다. +. ``mysite/urls.py`` 전체는 아래와 같습니다. + +:: + + from django.conf.urls import patterns, include, url + + from django.contrib import admin + admin.autodiscover() + + urlpatterns = patterns('polls.views', + url(r'^polls/$', 'index'), + url(r'^polls/(?P\d+)/$', 'detail'), + url(r'^polls/(?P\d+)/results/$', 'results'), + url(r'^polls/(?P\d+)/vote/$', 'vote'), + ) + + urlpatterns += patterns('', + url(r'^admin/', include(admin.site.urls)), + ) + +URLconf의 결합도 낮추기 +======================= + +하는 김에 우리는 Django 프로젝트 설정으로 부터 우리의 투표-앱 URL 들을 분리하는 시간을 가져야 합니다. Django 앱들은 플러그인 처럼 사용 할수 있도록 만들었습니다. -- 각각의 특정한 앱이 최소한의 수정으로 다른 Django installation 으로 이전 가능해야 합니다. + +이 시점에서 투표 앱은 상당히 결합도가 낮습니다. ``python manage.py startapp``\ 가 생성한 엄격한 디렉토리 구조에 감사하기 바랍니다. 그렇나, 단 하나 URLconf가 Django 설정들과 결합되어 있습니다. + +``mysite/urls.py``\ 에 있는 URL들은 수정했습니다. 그러나, 앱의 URL 디자인은 Django installation이 아니라, 특정 앱 지향적입니다. -- 그래서 URL들을 앱 디렉토리 안으로 이동합니다. + +``mysite/urls.py`` 파일을 ``polls/urls.py``\ 로 복사 하십시오. 그리고, ``mysite/urls.py``\ 에서 투표-한정 URL들을 제거 하고, :func:`~django.conf.urls.include`\ 를 그 자리에 추가하도록 변경합니다. + +:: + + from django.conf.urls import patterns, include, url + + from django.contrib import admin + admin.autodiscover() + + urlpatterns = patterns('', + url(r'^polls/', include('polls.urls')), + url(r'^admin/', include(admin.site.urls)), + ) + +:func:`~django.conf.urls.include`\ 은 간단하게 다른 URLconf를 참조 합니다. +정규표현식은 ``$``\ (문자열의 끝과 일치하는 문자)를 가지지 않고, trailling slash를 가지는 점을 기억하십시오. 어디든지 Django가 :func:`~django.conf.urls.include` 함수를 만나면, 해당 시점에서 URL의 일치하는 부분을 잘라냅니다. 그리고, 남은 문자열을 추가 처리를 위해서 불러들인 URLconf로 전송 합니다. + +사용자가 이 시스템에서 "/polls/34/"\ 로 이동하는 경우 무슨 일이 생기는지 보십시오. + +* Django는 ``'^polls/'``\ 에서 일치하는 것을 찾을 것입니다. + +* 그리고나서, Django 는 일치하는 문자(``"polls/"``)를 벗겨 낼것 입니다. + 남은 문자 -- ``"34/"`` --를 'polls.urls' URLconf로 추가 처리를 위해서 보냅니다. + + +이제, URLconf와 Django 설정의 결합도를 낮추었습니다. 우리는 개별 라인 맨 앞에 있는 "polls/"를 삭제하고, 관리자 사이트에 등록한 라인들을 삭제 함으로써 ``polls.urls``와 URLconf의 결합도를 낮추었습니다. ``polls/urls.py`` 파일은 지금 아래와 같아야 합니다. :: + + from django.conf.urls import patterns, include, url + + urlpatterns = patterns('polls.views', + url(r'^$', 'index'), + url(r'^(?P\d+)/$', 'detail'), + url(r'^(?P\d+)/results/$', 'results'), + url(r'^(?P\d+)/vote/$', 'vote'), + ) + +:func:`~django.conf.urls.include`\ 와 URLconf의 결합도를 낮추는 아이디어는 URL들의 플러그인플레이를 쉽게 만들어 줍니다. 이제 투표들은 각자 URLconf를 가지고 있습니다. 투표들은 "/polls/" 밑에도 있을 수 있고, "/fun_polls/" 밑에도, "/content/polls/" 밑에도, 그리고 다른 어떠한 루트 경로 에도 있을 수 있습니다. 그리고 앱은 여전히 잘 동작 할 것 입니다. + +모든 투표 앱들은 절대 경로가 아니라, 상대 경로를 사용합니다. + +뷰를 작성 하는 것에 익숙해 지면 단순한 폼 처리와 제너릭 뷰를 배우기 위해서 :doc:`part 4 of this tutorial +
`\ 를 읽어보십시오. From 41ec110955b6f91148adea8b7525797d1a3f1991 Mon Sep 17 00:00:00 2001 From: sk kwon Date: Thu, 6 Sep 2012 18:33:27 +0900 Subject: [PATCH 051/128] =?UTF-8?q?1=EC=B0=A8=EB=B2=88=EC=97=AD=20?= =?UTF-8?q?=EC=9D=BC=EB=B6=80=20=EC=99=84=EB=A3=8C=ED=95=A8.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문장하나가 잘 이해가 안되네요.검토 부탁드립니다.. 아래 부분입니다 The best way to make sure tickets do not get hung up on the way to checkin is to make it dead easy, even for someone who may not be intimately familiar with that area of the code, to understand the problem and verify the fix: --- faq/contributing.txt | 197 +++++++++++++++++++++---------------------- 1 file changed, 95 insertions(+), 102 deletions(-) diff --git a/faq/contributing.txt b/faq/contributing.txt index 6f2dfd9..44b07fe 100644 --- a/faq/contributing.txt +++ b/faq/contributing.txt @@ -1,102 +1,95 @@ -FAQ: Contributing code -====================== - -How can I get started contributing code to Django? --------------------------------------------------- - -Thanks for asking! We've written an entire document devoted to this question. -It's titled :doc:`Contributing to Django `. - -I submitted a bug fix in the ticket system several weeks ago. Why are you ignoring my patch? --------------------------------------------------------------------------------------------- - -Don't worry: We're not ignoring you! - -It's important to understand there is a difference between "a ticket is being -ignored" and "a ticket has not been attended to yet." Django's ticket system -contains hundreds of open tickets, of various degrees of impact on end-user -functionality, and Django's developers have to review and prioritize. - -On top of that: the people who work on Django are all volunteers. As a result, -the amount of time that we have to work on the framework is limited and will -vary from week to week depending on our spare time. If we're busy, we may not -be able to spend as much time on Django as we might want. - -The best way to make sure tickets do not get hung up on the way to checkin is -to make it dead easy, even for someone who may not be intimately familiar with -that area of the code, to understand the problem and verify the fix: - -* Are there clear instructions on how to reproduce the bug? If this - touches a dependency (such as PIL), a contrib module, or a specific - database, are those instructions clear enough even for someone not - familiar with it? - -* If there are several patches attached to the ticket, is it clear what - each one does, which ones can be ignored and which matter? - -* Does the patch include a unit test? If not, is there a very clear - explanation why not? A test expresses succinctly what the problem is, - and shows that the patch actually fixes it. - -If your patch stands no chance of inclusion in Django, we won't ignore it -- -we'll just close the ticket. So if your ticket is still open, it doesn't mean -we're ignoring you; it just means we haven't had time to look at it yet. - -When and how might I remind the core team of a patch I care about? ------------------------------------------------------------------- - -A polite, well-timed message to the mailing list is one way to get attention. -To determine the right time, you need to keep an eye on the schedule. If you -post your message when the core developers are trying to hit a feature -deadline or manage a planning phase, you're not going to get the sort of -attention you require. However, if you draw attention to a ticket when the -core developers are paying particular attention to bugs -- just before a bug -fixing sprint, or in the lead up to a beta release for example -- you're much -more likely to get a productive response. - -Gentle IRC reminders can also work -- again, strategically timed if possible. -During a bug sprint would be a very good time, for example. - -Another way to get traction is to pull several related tickets together. When -the core developers sit down to fix a bug in an area they haven't touched for -a while, it can take a few minutes to remember all the fine details of how -that area of code works. If you collect several minor bug fixes together into -a similarly themed group, you make an attractive target, as the cost of coming -up to speed on an area of code can be spread over multiple tickets. - -Please refrain from emailing core developers personally, or repeatedly raising -the same issue over and over. This sort of behavior will not gain you any -additional attention -- certainly not the attention that you need in order to -get your pet bug addressed. - -But I've reminded you several times and you keep ignoring my patch! -------------------------------------------------------------------- - -Seriously - we're not ignoring you. If your patch stands no chance of -inclusion in Django, we'll close the ticket. For all the other tickets, we -need to prioritize our efforts, which means that some tickets will be -addressed before others. - -One of the criteria that is used to prioritize bug fixes is the number of -people that will likely be affected by a given bug. Bugs that have the -potential to affect many people will generally get priority over those that -are edge cases. - -Another reason that bugs might be ignored for while is if the bug is a symptom -of a larger problem. While we can spend time writing, testing and applying -lots of little patches, sometimes the right solution is to rebuild. If a -rebuild or refactor of a particular component has been proposed or is -underway, you may find that bugs affecting that component will not get as much -attention. Again, this is just a matter of prioritizing scarce resources. By -concentrating on the rebuild, we can close all the little bugs at once, and -hopefully prevent other little bugs from appearing in the future. - -Whatever the reason, please keep in mind that while you may hit a particular -bug regularly, it doesn't necessarily follow that every single Django user -will hit the same bug. Different users use Django in different ways, stressing -different parts of the code under different conditions. When we evaluate the -relative priorities, we are generally trying to consider the needs of the -entire community, not just the severity for one particular user. This doesn't -mean that we think your problem is unimportant -- just that in the limited -time we have available, we will always err on the side of making 10 people -happy rather than making 1 person happy. +FAQ: 오픈소스 참여방법(Contributing code) +====================== + +Django 오픈소스 시작은 어떻게하나?-------------------------------------------------- + +감사합니다이 주제와 관련된 문서전체를 작성했습니다. +문서의 타이틀은:`Contributing to Django `입니다. + +저는 몇 주전 티켓시스템에 버그픽스를 제출했습니다. 그런데 왜 저의 패치가무시되고 있죠?-------------------------------------------------------------------------------------------- + +걱정마세요: 당신을 무시하는 것이 아닙니다! + +"티켓이 무시되는 것"은 "티켓이 아직 미참여 상태에 있는 것"과 다릅니다( 즉 이 둘 사이에는 중요한 차이점이 있습니다) Django 티켓시스템은 수백개의 오픈티켓을 포함하고 있으며, 엔드유저입장에서보면 각각 다양한 수준의 기능상 임팩트를 가지고 있습니다. 또한 Django개발자들은 리뷰하고 우선순위를 매겨야 합니다. + +무엇보다도 Django프로젝트에 참여하는 모든 이는 자발적 참여자입니다. 결론적으로, +이 프레임웍에 투자하는 시간은 제한적입니다. 그리고 투자할 수 있는 여가시간은 주 단위로 바뀝니다. 만약에 바쁜 경우라면 원하는 만큼 투자할 수 없겠죠. + +The best way to make sure tickets do not get hung up on the way to checkin is +to make it dead easy, even for someone who may not be intimately familiar with +that area of the code, to understand the problem and verify the fix:( 체크인이 오래동안 해결되지 않는 상태를 방지하기 위해서는 문제점을 쉽게 이해하고 수정해버리는 것이다. 즉 특정코드에 대한 이해가 부족하더라도 말이다. -- 번역검토요) + +* 버그를 재현하는 특정한 설명이나 지침서가 있나요?만약 이것이 + 디펜던시(이를테면 PIL같은 경우), contrib 모듈, 또는 특정 + 데이타베이스를 건드리는 경우라면, 이 지침서는 이 코드에 친숙하지 않은 사용자를 위해서도 충분한가? + familiar with it? + +* If there are several patches attached to the ticket, is it clear what + each one does, which ones can be ignored and which matter? + +* 패치는 유닛테스트를 포함하고 있나요?만약에 포함하고 있지 않다면, 설명가능한 명백한 이유가 있나요? + 왜?A test expresses succinctly what the problem is, + and shows that the patch actually fixes it. + +If your patch stands no chance of inclusion in Django, we won't ignore it -- +we'll just close the ticket. So if your ticket is still open, it doesn't mean +we're ignoring you; it just means we haven't had time to look at it yet. + +When and how might I remind the core team of a patch I care about? +------------------------------------------------------------------ + +A polite, well-timed message to the mailing list is one way to get attention. +To determine the right time, you need to keep an eye on the schedule. If you +post your message when the core developers are trying to hit a feature +deadline or manage a planning phase, you're not going to get the sort of +attention you require. However, if you draw attention to a ticket when the +core developers are paying particular attention to bugs -- just before a bug +fixing sprint, or in the lead up to a beta release for example -- you're much +more likely to get a productive response. + +Gentle IRC reminders can also work -- again, strategically timed if possible. +During a bug sprint would be a very good time, for example. + +Another way to get traction is to pull several related tickets together. When +the core developers sit down to fix a bug in an area they haven't touched for +a while, it can take a few minutes to remember all the fine details of how +that area of code works. If you collect several minor bug fixes together into +a similarly themed group, you make an attractive target, as the cost of coming +up to speed on an area of code can be spread over multiple tickets. + +Please refrain from emailing core developers personally, or repeatedly raising +the same issue over and over. This sort of behavior will not gain you any +additional attention -- certainly not the attention that you need in order to +get your pet bug addressed. + +But I've reminded you several times and you keep ignoring my patch! +------------------------------------------------------------------- + +Seriously - we're not ignoring you. If your patch stands no chance of +inclusion in Django, we'll close the ticket. For all the other tickets, we +need to prioritize our efforts, which means that some tickets will be +addressed before others. + +One of the criteria that is used to prioritize bug fixes is the number of +people that will likely be affected by a given bug. Bugs that have the +potential to affect many people will generally get priority over those that +are edge cases. + +Another reason that bugs might be ignored for while is if the bug is a symptom +of a larger problem. While we can spend time writing, testing and applying +lots of little patches, sometimes the right solution is to rebuild. If a +rebuild or refactor of a particular component has been proposed or is +underway, you may find that bugs affecting that component will not get as much +attention. Again, this is just a matter of prioritizing scarce resources. By +concentrating on the rebuild, we can close all the little bugs at once, and +hopefully prevent other little bugs from appearing in the future. + +Whatever the reason, please keep in mind that while you may hit a particular +bug regularly, it doesn't necessarily follow that every single Django user +will hit the same bug. Different users use Django in different ways, stressing +different parts of the code under different conditions. When we evaluate the +relative priorities, we are generally trying to consider the needs of the +entire community, not just the severity for one particular user. This doesn't +mean that we think your problem is unimportant -- just that in the limited +time we have available, we will always err on the side of making 10 people +happy rather than making 1 person happy. From ce639c175a1689f66b56d1996d79cf5f8a3a829d Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Fri, 7 Sep 2012 22:46:43 +0900 Subject: [PATCH 052/128] =?UTF-8?q?ref/django-admin=20=EB=B2=88=EC=97=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit compilemessages와 makemessages 옵션 --- ref/django-admin.txt | 3031 +++++++++++++++++++++--------------------- 1 file changed, 1509 insertions(+), 1522 deletions(-) diff --git a/ref/django-admin.txt b/ref/django-admin.txt index 5ea7280..883f6c9 100644 --- a/ref/django-admin.txt +++ b/ref/django-admin.txt @@ -1,1522 +1,1509 @@ -============================= -django-admin.py and manage.py -============================= - -``django-admin.py`` is Django's command-line utility for administrative tasks. -This document outlines all it can do. - -In addition, ``manage.py`` is automatically created in each Django project. -``manage.py`` is a thin wrapper around ``django-admin.py`` that takes care of -two things for you before delegating to ``django-admin.py``: - -* It puts your project's package on ``sys.path``. - -* It sets the :envvar:`DJANGO_SETTINGS_MODULE` environment variable so that - it points to your project's ``settings.py`` file. - -The ``django-admin.py`` script should be on your system path if you installed -Django via its ``setup.py`` utility. If it's not on your path, you can find it -in ``site-packages/django/bin`` within your Python installation. Consider -symlinking it from some place on your path, such as ``/usr/local/bin``. - -For Windows users, who do not have symlinking functionality available, you can -copy ``django-admin.py`` to a location on your existing path or edit the -``PATH`` settings (under ``Settings - Control Panel - System - Advanced - -Environment...``) to point to its installed location. - -Generally, when working on a single Django project, it's easier to use -``manage.py``. Use ``django-admin.py`` with ``DJANGO_SETTINGS_MODULE``, or the -``--settings`` command line option, if you need to switch between multiple -Django settings files. - -The command-line examples throughout this document use ``django-admin.py`` to -be consistent, but any example can use ``manage.py`` just as well. - -Usage -===== - -.. code-block:: bash - - django-admin.py [options] - manage.py [options] - -``command`` should be one of the commands listed in this document. -``options``, which is optional, should be zero or more of the options available -for the given command. - -Getting runtime help --------------------- - -.. django-admin:: help - -Run ``django-admin.py help`` to display usage information and a list of the -commands provided by each application. - -Run ``django-admin.py help --commands`` to display a list of all available -commands. - -Run ``django-admin.py help `` to display a description of the given -command and a list of its available options. - -App names ---------- - -Many commands take a list of "app names." An "app name" is the basename of -the package containing your models. For example, if your :setting:`INSTALLED_APPS` -contains the string ``'mysite.blog'``, the app name is ``blog``. - -Determining the version ------------------------ - -.. django-admin:: version - -Run ``django-admin.py version`` to display the current Django version. - -The output follows the schema described in :pep:`386`:: - - 1.4.dev17026 - 1.4a1 - 1.4 - -Displaying debug output ------------------------ - -Use :djadminopt:`--verbosity` to specify the amount of notification and debug information -that ``django-admin.py`` should print to the console. For more details, see the -documentation for the :djadminopt:`--verbosity` option. - -Available commands -================== - -cleanup -------- - -.. django-admin:: cleanup - -Can be run as a cronjob or directly to clean out old data from the database -(only expired sessions at the moment). - -compilemessages ---------------- - -.. django-admin:: compilemessages - -Compiles .po files created with ``makemessages`` to .mo files for use with -the builtin gettext support. See :doc:`/topics/i18n/index`. - -Use the :djadminopt:`--locale` option to specify the locale to process. -If not provided, all locales are processed. - -Example usage:: - - django-admin.py compilemessages --locale=br_PT - -createcachetable ----------------- - -.. django-admin:: createcachetable - -Creates a cache table named ``tablename`` for use with the database cache -backend. See :doc:`/topics/cache` for more information. - -.. versionadded:: 1.2 - -The :djadminopt:`--database` option can be used to specify the database -onto which the cachetable will be installed. - -dbshell -------- - -.. django-admin:: dbshell - -Runs the command-line client for the database engine specified in your -``ENGINE`` setting, with the connection parameters specified in your -:setting:`USER`, :setting:`PASSWORD`, etc., settings. - -* For PostgreSQL, this runs the ``psql`` command-line client. -* For MySQL, this runs the ``mysql`` command-line client. -* For SQLite, this runs the ``sqlite3`` command-line client. - -This command assumes the programs are on your ``PATH`` so that a simple call to -the program name (``psql``, ``mysql``, ``sqlite3``) will find the program in -the right place. There's no way to specify the location of the program -manually. - -.. versionadded:: 1.2 - -The :djadminopt:`--database` option can be used to specify the database -onto which to open a shell. - -diffsettings ------------- - -.. django-admin:: diffsettings - -Displays differences between the current settings file and Django's default -settings. - -Settings that don't appear in the defaults are followed by ``"###"``. For -example, the default settings don't define :setting:`ROOT_URLCONF`, so -:setting:`ROOT_URLCONF` is followed by ``"###"`` in the output of -``diffsettings``. - -Note that Django's default settings live in ``django/conf/global_settings.py``, -if you're ever curious to see the full list of defaults. - -dumpdata --------------------------------------------- - -.. django-admin:: dumpdata - -Outputs to standard output all data in the database associated with the named -application(s). - -If no application name is provided, all installed applications will be dumped. - -The output of ``dumpdata`` can be used as input for ``loaddata``. - -Note that ``dumpdata`` uses the default manager on the model for selecting the -records to dump. If you're using a :ref:`custom manager ` as -the default manager and it filters some of the available records, not all of the -objects will be dumped. - -.. versionadded:: 1.3 - -The :djadminopt:`--all` option may be provided to specify that -``dumpdata`` should use Django's base manager, dumping records which -might otherwise be filtered or modified by a custom manager. - -.. django-admin-option:: --format - -By default, ``dumpdata`` will format its output in JSON, but you can use the -``--format`` option to specify another format. Currently supported formats -are listed in :ref:`serialization-formats`. - -.. django-admin-option:: --indent - -By default, ``dumpdata`` will output all data on a single line. This isn't -easy for humans to read, so you can use the ``--indent`` option to -pretty-print the output with a number of indentation spaces. - -The :djadminopt:`--exclude` option may be provided to prevent specific -applications from being dumped. - -.. versionadded:: 1.3 - -The :djadminopt:`--exclude` option may also be provided to prevent specific -models (specified as in the form of ``appname.ModelName``) from being dumped. - -In addition to specifying application names, you can provide a list of -individual models, in the form of ``appname.Model``. If you specify a model -name to ``dumpdata``, the dumped output will be restricted to that model, -rather than the entire application. You can also mix application names and -model names. - -.. versionadded:: 1.2 - -The :djadminopt:`--database` option can be used to specify the database -onto which the data will be loaded. - -.. django-admin-option:: --natural - -.. versionadded:: 1.2 - -Use :ref:`natural keys ` to represent -any foreign key and many-to-many relationship with a model that provides -a natural key definition. If you are dumping ``contrib.auth`` ``Permission`` -objects or ``contrib.contenttypes`` ``ContentType`` objects, you should -probably be using this flag. - -flush ------ - -.. django-admin:: flush - -Returns the database to the state it was in immediately after syncdb was -executed. This means that all data will be removed from the database, any -post-synchronization handlers will be re-executed, and the ``initial_data`` -fixture will be re-installed. - -The :djadminopt:`--noinput` option may be provided to suppress all user -prompts. - -.. versionadded:: 1.2 - -The :djadminopt:`--database` option may be used to specify the database -to flush. - -inspectdb ---------- - -.. django-admin:: inspectdb - -Introspects the database tables in the database pointed-to by the -:setting:`NAME` setting and outputs a Django model module (a ``models.py`` -file) to standard output. - -Use this if you have a legacy database with which you'd like to use Django. -The script will inspect the database and create a model for each table within -it. - -As you might expect, the created models will have an attribute for every field -in the table. Note that ``inspectdb`` has a few special cases in its field-name -output: - -* If ``inspectdb`` cannot map a column's type to a model field type, it'll - use ``TextField`` and will insert the Python comment - ``'This field type is a guess.'`` next to the field in the generated - model. - -* If the database column name is a Python reserved word (such as - ``'pass'``, ``'class'`` or ``'for'``), ``inspectdb`` will append - ``'_field'`` to the attribute name. For example, if a table has a column - ``'for'``, the generated model will have a field ``'for_field'``, with - the ``db_column`` attribute set to ``'for'``. ``inspectdb`` will insert - the Python comment - ``'Field renamed because it was a Python reserved word.'`` next to the - field. - -This feature is meant as a shortcut, not as definitive model generation. After -you run it, you'll want to look over the generated models yourself to make -customizations. In particular, you'll need to rearrange models' order, so that -models that refer to other models are ordered properly. - -Primary keys are automatically introspected for PostgreSQL, MySQL and -SQLite, in which case Django puts in the ``primary_key=True`` where -needed. - -``inspectdb`` works with PostgreSQL, MySQL and SQLite. Foreign-key detection -only works in PostgreSQL and with certain types of MySQL tables. - -.. versionadded:: 1.2 - -The :djadminopt:`--database` option may be used to specify the -database to introspect. - -loaddata ------------------------------- - -.. django-admin:: loaddata - -Searches for and loads the contents of the named fixture into the database. - -.. versionadded:: 1.2 - -The :djadminopt:`--database` option can be used to specify the database -onto which the data will be loaded. - -What's a "fixture"? -~~~~~~~~~~~~~~~~~~~ - -A *fixture* is a collection of files that contain the serialized contents of -the database. Each fixture has a unique name, and the files that comprise the -fixture can be distributed over multiple directories, in multiple applications. - -Django will search in three locations for fixtures: - -1. In the ``fixtures`` directory of every installed application -2. In any directory named in the :setting:`FIXTURE_DIRS` setting -3. In the literal path named by the fixture - -Django will load any and all fixtures it finds in these locations that match -the provided fixture names. - -If the named fixture has a file extension, only fixtures of that type -will be loaded. For example:: - - django-admin.py loaddata mydata.json - -would only load JSON fixtures called ``mydata``. The fixture extension -must correspond to the registered name of a -:ref:`serializer ` (e.g., ``json`` or ``xml``). - -If you omit the extensions, Django will search all available fixture types -for a matching fixture. For example:: - - django-admin.py loaddata mydata - -would look for any fixture of any fixture type called ``mydata``. If a fixture -directory contained ``mydata.json``, that fixture would be loaded -as a JSON fixture. - -The fixtures that are named can include directory components. These -directories will be included in the search path. For example:: - - django-admin.py loaddata foo/bar/mydata.json - -would search ``/fixtures/foo/bar/mydata.json`` for each installed -application, ``/foo/bar/mydata.json`` for each directory in -:setting:`FIXTURE_DIRS`, and the literal path ``foo/bar/mydata.json``. - -When fixture files are processed, the data is saved to the database as is. -Model defined ``save`` methods and ``pre_save`` signals are not called. - -Note that the order in which fixture files are processed is undefined. However, -all fixture data is installed as a single transaction, so data in -one fixture can reference data in another fixture. If the database backend -supports row-level constraints, these constraints will be checked at the -end of the transaction. - -The ``dumpdata`` command can be used to generate input for ``loaddata``. - -Compressed fixtures -~~~~~~~~~~~~~~~~~~~ - -Fixtures may be compressed in ``zip``, ``gz``, or ``bz2`` format. For example:: - - django-admin.py loaddata mydata.json - -would look for any of ``mydata.json``, ``mydata.json.zip``, -``mydata.json.gz``, or ``mydata.json.bz2``. The first file contained within a -zip-compressed archive is used. - -Note that if two fixtures with the same name but different -fixture type are discovered (for example, if ``mydata.json`` and -``mydata.xml.gz`` were found in the same fixture directory), fixture -installation will be aborted, and any data installed in the call to -``loaddata`` will be removed from the database. - -.. admonition:: MySQL with MyISAM and fixtures - - The MyISAM storage engine of MySQL doesn't support transactions or - constraints, so if you use MyISAM, you won't get validation of fixture - data, or a rollback if multiple transaction files are found. - -Database-specific fixtures -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If you're in a multi-database setup, you might have fixture data that -you want to load onto one database, but not onto another. In this -situation, you can add database identifier into the names of your fixtures. - -For example, if your :setting:`DATABASES` setting has a 'master' database -defined, name the fixture ``mydata.master.json`` or -``mydata.master.json.gz`` and the fixture will only be loaded when you -specify you want to load data into the ``master`` database. - -makemessages ------------- - -.. django-admin:: makemessages - -Runs over the entire source tree of the current directory and pulls out all -strings marked for translation. It creates (or updates) a message file in the -conf/locale (in the django tree) or locale (for project and application) -directory. After making changes to the messages files you need to compile them -with ``compilemessages`` for use with the builtin gettext support. See the -:ref:`i18n documentation ` for details. - -.. django-admin-option:: --all - -Use the ``--all`` or ``-a`` option to update the message files for all -available languages. - -Example usage:: - - django-admin.py makemessages --all - -.. django-admin-option:: --extension - -Use the ``--extension`` or ``-e`` option to specify a list of file extensions -to examine (default: ".html", ".txt"). - -Example usage:: - - django-admin.py makemessages --locale=de --extension xhtml - -Separate multiple extensions with commas or use -e or --extension multiple times:: - - django-admin.py makemessages --locale=de --extension=html,txt --extension xml - -Use the :djadminopt:`--locale` option to specify the locale to process. - -Example usage:: - - django-admin.py makemessages --locale=br_PT - -.. django-admin-option:: --domain - -Use the ``--domain`` or ``-d`` option to change the domain of the messages files. -Currently supported: - -* ``django`` for all ``*.py``, ``*.html`` and ``*.txt`` files (default) -* ``djangojs`` for ``*.js`` files - -.. django-admin-option:: --symlinks - -.. versionadded:: 1.2 - -Use the ``--symlinks`` or ``-s`` option to follow symlinks to directories when -looking for new translation strings. - -Example usage:: - - django-admin.py makemessages --locale=de --symlinks - -.. django-admin-option:: --ignore - -Use the ``--ignore`` or ``-i`` option to ignore files or directories matching -the given :mod:`glob`-style pattern. Use multiple times to ignore more. - -These patterns are used by default: ``'CVS'``, ``'.*'``, ``'*~'`` - -Example usage:: - - django-admin.py makemessages --locale=en_US --ignore=apps/* --ignore=secret/*.html - -.. django-admin-option:: --no-default-ignore - -Use the ``--no-default-ignore`` option to disable the default values of -:djadminopt:`--ignore`. - -.. django-admin-option:: --no-wrap - -.. versionadded:: 1.3 - -Use the ``--no-wrap`` option to disable breaking long message lines into -several lines in language files. - -.. django-admin-option:: --no-location - -.. versionadded:: 1.4 - -Use the ``--no-location`` option to not write '``#: filename:line``' -comment lines in language files. Note that using this option makes it harder -for technically skilled translators to understand each message's context. - -reset ---------------------------- - -.. deprecated:: 1.3 - This command has been deprecated. The ``flush`` can be used to delete - everything. You can also use ALTER TABLE or DROP TABLE statements manually. - -.. django-admin:: reset - -Executes the equivalent of ``sqlreset`` for the given app name(s). - -The :djadminopt:`--noinput` option may be provided to suppress all user -prompts. - -.. versionadded:: 1.2 - -The :djadminopt:`--database` option can be used to specify the alias -of the database to reset. - -runfcgi [options] ------------------ - -.. django-admin:: runfcgi - -Starts a set of FastCGI processes suitable for use with any Web server that -supports the FastCGI protocol. See the :doc:`FastCGI deployment documentation -` for details. Requires the Python FastCGI module from -`flup`_. - -.. versionadded:: 1.4 - Internally, this wraps the WSGI application object specified by the - :setting:`WSGI_APPLICATION` setting. - -.. _flup: http://www.saddi.com/software/flup/ - -The options accepted by this command are passed to the FastCGI library and -don't use the ``'--'`` prefix as is usual for other Django management commands. - -.. django-admin-option:: protocol - -``protocol=PROTOCOL`` - -Protocol to use. *PROTOCOL* can be ``fcgi``, ``scgi``, ``ajp``, etc. -(default is ``fcgi``) - -.. django-admin-option:: host - -``host=HOSTNAME`` - -Hostname to listen on. - -.. django-admin-option:: port - -``port=PORTNUM`` - -Port to listen on. - -.. django-admin-option:: socket - -``socket=FILE`` - -UNIX socket to listen on. - -.. django-admin-option:: method - -``method=IMPL`` - -Possible values: ``prefork`` or ``threaded`` (default ``prefork``) - -.. django-admin-option:: maxrequests - -``maxrequests=NUMBER`` - -Number of requests a child handles before it is killed and a new child is -forked (0 means no limit). - -.. django-admin-option:: maxspare - -``maxspare=NUMBER`` - -Max number of spare processes / threads. - -.. django-admin-option:: minspare - -``minspare=NUMBER`` - -Min number of spare processes / threads. - -.. django-admin-option:: maxchildren - -``maxchildren=NUMBER`` - -Hard limit number of processes / threads. - -.. django-admin-option:: daemonize - -``daemonize=BOOL`` - -Whether to detach from terminal. - -.. django-admin-option:: pidfile - -``pidfile=FILE`` - -Write the spawned process-id to file *FILE*. - -.. django-admin-option:: workdir - -``workdir=DIRECTORY`` - -Change to directory *DIRECTORY* when daemonizing. - -.. django-admin-option:: debug - -``debug=BOOL`` - -Set to true to enable flup tracebacks. - -.. django-admin-option:: outlog - -``outlog=FILE`` - -Write stdout to the *FILE* file. - -.. django-admin-option:: errlog - -``errlog=FILE`` - -Write stderr to the *FILE* file. - -.. django-admin-option:: umask - -``umask=UMASK`` - -Umask to use when daemonizing. The value is interpeted as an octal number -(default value is ``022``). - -Example usage:: - - django-admin.py runfcgi socket=/tmp/fcgi.sock method=prefork daemonize=true \ - pidfile=/var/run/django-fcgi.pid - -Run a FastCGI server as a daemon and write the spawned PID in a file. - -runserver [port or address:port] --------------------------------- - -.. django-admin:: runserver - -Starts a lightweight development Web server on the local machine. By default, -the server runs on port 8000 on the IP address ``127.0.0.1``. You can pass in an -IP address and port number explicitly. - -If you run this script as a user with normal privileges (recommended), you -might not have access to start a port on a low port number. Low port numbers -are reserved for the superuser (root). - -.. versionadded:: 1.4 - This server uses the WSGI application object specified by the - :setting:`WSGI_APPLICATION` setting. - -DO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through -security audits or performance tests. (And that's how it's gonna stay. We're in -the business of making Web frameworks, not Web servers, so improving this -server to be able to handle a production environment is outside the scope of -Django.) - -The development server automatically reloads Python code for each request, as -needed. You don't need to restart the server for code changes to take effect. - -When you start the server, and each time you change Python code while the -server is running, the server will validate all of your installed models. (See -the ``validate`` command below.) If the validator finds errors, it will print -them to standard output, but it won't stop the server. - -You can run as many servers as you want, as long as they're on separate ports. -Just execute ``django-admin.py runserver`` more than once. - -Note that the default IP address, ``127.0.0.1``, is not accessible from other -machines on your network. To make your development server viewable to other -machines on the network, use its own IP address (e.g. ``192.168.2.1``) or -``0.0.0.0`` or ``::`` (with IPv6 enabled). - -.. versionchanged:: 1.3 - -You can provide an IPv6 address surrounded by brackets -(e.g. ``[200a::1]:8000``). This will automatically enable IPv6 support. - -A hostname containing ASCII-only characters can also be used. - -.. django-admin-option:: --adminmedia - -Use the ``--adminmedia`` option to tell Django where to find the various CSS -and JavaScript files for the Django admin interface. Normally, the development -server serves these files out of the Django source tree magically, but you'd -want to use this if you made any changes to those files for your own site. - -Example usage:: - - django-admin.py runserver --adminmedia=/tmp/new-admin-style/ - -.. versionchanged:: 1.3 - -If the :doc:`staticfiles` contrib app is enabled -(default in new projects) the :djadmin:`runserver` command will be overriden -with an own :djadmin:`runserver` command which doesn't -have the :djadminopt:`--adminmedia` option due to deprecation. - -.. django-admin-option:: --noreload - -Use the ``--noreload`` option to disable the use of the auto-reloader. This -means any Python code changes you make while the server is running will *not* -take effect if the particular Python modules have already been loaded into -memory. - -Example usage:: - - django-admin.py runserver --noreload - -.. django-admin-option:: --nothreading - -.. versionadded:: 1.4 - -Use the ``--nothreading`` option to disable the use of threading in the -development server. - -.. django-admin-option:: --ipv6, -6 - -.. versionadded:: 1.3 - -Use the ``--ipv6`` (or shorter ``-6``) option to tell Django to use IPv6 for -the development server. This changes the default IP address from -``127.0.0.1`` to ``::1``. - -Example usage:: - - django-admin.py runserver --ipv6 - -Examples of using different ports and addresses -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Port 8000 on IP address ``127.0.0.1``:: - - django-admin.py runserver - -Port 8000 on IP address ``1.2.3.4``:: - - django-admin.py runserver 1.2.3.4:8000 - -Port 7000 on IP address ``127.0.0.1``:: - - django-admin.py runserver 7000 - -Port 7000 on IP address ``1.2.3.4``:: - - django-admin.py runserver 1.2.3.4:7000 - -Port 8000 on IPv6 address ``::1``:: - - django-admin.py runserver -6 - -Port 7000 on IPv6 address ``::1``:: - - django-admin.py runserver -6 7000 - -Port 7000 on IPv6 address ``2001:0db8:1234:5678::9``:: - - django-admin.py runserver [2001:0db8:1234:5678::9]:7000 - -Port 8000 on IPv4 address of host ``localhost``:: - - django-admin.py runserver localhost:8000 - -Port 8000 on IPv6 address of host ``localhost``:: - - django-admin.py runserver -6 localhost:8000 - -Serving static files with the development server -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -By default, the development server doesn't serve any static files for your site -(such as CSS files, images, things under :setting:`MEDIA_URL` and so forth). If -you want to configure Django to serve static media, read :doc:`/howto/static-files`. - -shell ------ - -.. django-admin:: shell - -Starts the Python interactive interpreter. - -Django will use IPython_ or bpython_ if either is installed. If you have a -rich shell installed but want to force use of the "plain" Python interpreter, -use the ``--plain`` option, like so:: - - django-admin.py shell --plain - -.. _IPython: http://ipython.scipy.org/ -.. _bpython: http://bpython-interpreter.org/ - -sql -------------------------- - -.. django-admin:: sql - -Prints the CREATE TABLE SQL statements for the given app name(s). - -.. versionadded:: 1.2 - -The :djadminopt:`--database` option can be used to specify the database for -which to print the SQL. - -sqlall ----------------------------- - -.. django-admin:: sqlall - -Prints the CREATE TABLE and initial-data SQL statements for the given app name(s). - -Refer to the description of ``sqlcustom`` for an explanation of how to -specify initial data. - -.. versionadded:: 1.2 - -The :djadminopt:`--database` option can be used to specify the database for -which to print the SQL. - -sqlclear ------------------------------- - -.. django-admin:: sqlclear - -Prints the DROP TABLE SQL statements for the given app name(s). - -.. versionadded:: 1.2 - -The :djadminopt:`--database` option can be used to specify the database for -which to print the SQL. - -sqlcustom -------------------------------- - -.. django-admin:: sqlcustom - -Prints the custom SQL statements for the given app name(s). - -For each model in each specified app, this command looks for the file -``/sql/.sql``, where ```` is the given app name and -```` is the model's name in lowercase. For example, if you have an -app ``news`` that includes a ``Story`` model, ``sqlcustom`` will attempt -to read a file ``news/sql/story.sql`` and append it to the output of this -command. - -Each of the SQL files, if given, is expected to contain valid SQL. The SQL -files are piped directly into the database after all of the models' -table-creation statements have been executed. Use this SQL hook to make any -table modifications, or insert any SQL functions into the database. - -Note that the order in which the SQL files are processed is undefined. - -.. versionadded:: 1.2 - -The :djadminopt:`--database` option can be used to specify the database for -which to print the SQL. - -sqlflush --------- - -.. django-admin:: sqlflush - -Prints the SQL statements that would be executed for the :djadmin:`flush` -command. - -.. versionadded:: 1.2 - -The :djadminopt:`--database` option can be used to specify the database for -which to print the SQL. - -sqlindexes --------------------------------- - -.. django-admin:: sqlindexes - -Prints the CREATE INDEX SQL statements for the given app name(s). - -.. versionadded:: 1.2 - -The :djadminopt:`--database` option can be used to specify the database for -which to print the SQL. - -sqlreset ------------------------------- - -.. deprecated:: 1.3 - This command has been deprecated. The ``sqlflush`` can be used to delete - everything. You can also use ALTER TABLE or DROP TABLE statements manually. - -.. django-admin:: sqlreset - -Prints the DROP TABLE SQL, then the CREATE TABLE SQL, for the given app name(s). - -.. versionadded:: 1.2 - -The :djadminopt:`--database` option can be used to specify the database for -which to print the SQL. - -sqlsequencereset --------------------------------------- - -.. django-admin:: sqlsequencereset - -Prints the SQL statements for resetting sequences for the given app name(s). - -Sequences are indexes used by some database engines to track the next available -number for automatically incremented fields. - -Use this command to generate SQL which will fix cases where a sequence is out -of sync with its automatically incremented field data. - -.. versionadded:: 1.2 - -The :djadminopt:`--database` option can be used to specify the database for -which to print the SQL. - -startapp [destination] --------------------------------- - -.. django-admin:: startapp - -Creates a Django app directory structure for the given app name in the current -directory or the given destination. - -.. versionchanged:: 1.4 - -By default the directory created contains a ``models.py`` file and other app -template files. (See the `source`_ for more details.) If only the app -name is given, the app directory will be created in the current working -directory. - -If the optional destination is provided, Django will use that existing -directory rather than creating a new one. You can use '.' to denote the current -working directory. - -For example:: - - django-admin.py startapp myapp /Users/jezdez/Code/myapp - -.. versionadded:: 1.4 -.. django-admin-option:: --template - -With the ``--template`` option, you can use a custom app template by providing -either the path to a directory with the app template file, or a path to a -compressed file (``.tar.gz``, ``.tar.bz2``, ``.tgz``, ``.tbz``, ``.zip``) -containing the app template files. - -Django will also accept URLs (``http``, ``https``, ``ftp``) to compressed -archives with the app template files, downloading and extracting them on the -fly. - -For example, this would look for an app template in the given directory when -creating the ``myapp`` app:: - - django-admin.py startapp --template=/Users/jezdez/Code/my_app_template myapp - -.. versionadded:: 1.4 - -When Django copies the app template files, it also renders certain files -through the template engine: the files whose extensions match the -``--extension`` option (``py`` by default) and the files whose names are passed -with the ``--name`` option. The :class:`template context -` used is: - -- Any option passed to the startapp command -- ``app_name`` -- the app name as passed to the command -- ``app_directory`` -- the full path of the newly created app - -.. _render_warning: - -.. warning:: - - When the app template files are rendered with the Django template - engine (by default all ``*.py`` files), Django will also replace all - stray template variables contained. For example, if one of the Python files - contains a docstring explaining a particular feature related - to template rendering, it might result in an incorrect example. - - To work around this problem, you can use the :ttag:`templatetag` - templatetag to "escape" the various parts of the template syntax. - -.. _source: https://code.djangoproject.com/browser/django/trunk/django/conf/app_template/ - -startproject [destination] ----------------------------------------- - -.. django-admin:: startproject - -Creates a Django project directory structure for the given project name in -the current directory or the given destination. - -.. versionchanged:: 1.4 - -By default, the new directory contains ``manage.py`` and a project package -(containing a ``settings.py`` and other files). See the `template source`_ for -details. - -If only the project name is given, both the project directory and project -package will be named ```` and the project directory -will be created in the current working directory. - -If the optional destination is provided, Django will use that existing -directory as the project directory, and create ``manage.py`` and the project -package within it. Use '.' to denote the current working directory. - -For example:: - - django-admin.py startproject myproject /Users/jezdez/Code/myproject_repo - -.. versionadded:: 1.4 - -As with the :djadmin:`startapp` command, the ``--template`` option lets you -specify a directory, file path or URL of a custom project template. See the -:djadmin:`startapp` documentation for details of supported project template -formats. - -For example, this would look for a project template in the given directory -when creating the ``myproject`` project:: - - django-admin.py startproject --template=/Users/jezdez/Code/my_project_template myproject - -When Django copies the project template files, it also renders certain files -through the template engine: the files whose extensions match the -``--extension`` option (``py`` by default) and the files whose names are passed -with the ``--name`` option. The :class:`template context -` used is: - -- Any option passed to the startproject command -- ``project_name`` -- the project name as passed to the command -- ``project_directory`` -- the full path of the newly created project -- ``secret_key`` -- a random key for the :setting:`SECRET_KEY` setting - -Please also see the :ref:`rendering warning ` as mentioned -for :djadmin:`startapp`. - -.. _`template source`: https://code.djangoproject.com/browser/django/trunk/django/conf/project_template/ - -syncdb ------- - -.. django-admin:: syncdb - -Creates the database tables for all apps in :setting:`INSTALLED_APPS` whose -tables have not already been created. - -Use this command when you've added new applications to your project and want to -install them in the database. This includes any apps shipped with Django that -might be in :setting:`INSTALLED_APPS` by default. When you start a new project, -run this command to install the default apps. - -.. admonition:: Syncdb will not alter existing tables - - ``syncdb`` will only create tables for models which have not yet been - installed. It will *never* issue ``ALTER TABLE`` statements to match - changes made to a model class after installation. Changes to model classes - and database schemas often involve some form of ambiguity and, in those - cases, Django would have to guess at the correct changes to make. There is - a risk that critical data would be lost in the process. - - If you have made changes to a model and wish to alter the database tables - to match, use the ``sql`` command to display the new SQL structure and - compare that to your existing table schema to work out the changes. - -If you're installing the ``django.contrib.auth`` application, ``syncdb`` will -give you the option of creating a superuser immediately. - -``syncdb`` will also search for and install any fixture named ``initial_data`` -with an appropriate extension (e.g. ``json`` or ``xml``). See the -documentation for ``loaddata`` for details on the specification of fixture -data files. - -The :djadminopt:`--noinput` option may be provided to suppress all user -prompts. - -.. versionadded:: 1.2 - -The :djadminopt:`--database` option can be used to specify the database to -synchronize. - -test ------------------------------ - -.. django-admin:: test - -Runs tests for all installed models. See :doc:`/topics/testing` for more -information. - -.. versionadded:: 1.2 -.. django-admin-option:: --failfast - -The ``--failfast`` option can be used to stop running tests and report the -failure immediately after a test fails. - -.. versionadded:: 1.4 -.. django-admin-option:: --testrunner - -The ``--testrunner`` option can be used to control the test runner class that -is used to execute tests. If this value is provided, it overrides the value -provided by the :setting:`TEST_RUNNER` setting. - -.. versionadded:: 1.4 -.. django-admin-option:: --liveserver - -The ``--liveserver`` option can be used to override the default address where -the live server (used with :class:`~django.test.LiveServerTestCase`) is -expected to run from. The default value is ``localhost:8081``. - -testserver --------------------------------- - -.. django-admin:: testserver - -Runs a Django development server (as in ``runserver``) using data from the -given fixture(s). - -For example, this command:: - - django-admin.py testserver mydata.json - -...would perform the following steps: - -1. Create a test database, as described in :doc:`/topics/testing`. -2. Populate the test database with fixture data from the given fixtures. - (For more on fixtures, see the documentation for ``loaddata`` above.) -3. Runs the Django development server (as in ``runserver``), pointed at - this newly created test database instead of your production database. - -This is useful in a number of ways: - -* When you're writing :doc:`unit tests ` of how your views - act with certain fixture data, you can use ``testserver`` to interact with - the views in a Web browser, manually. - -* Let's say you're developing your Django application and have a "pristine" - copy of a database that you'd like to interact with. You can dump your - database to a fixture (using the ``dumpdata`` command, explained above), - then use ``testserver`` to run your Web application with that data. With - this arrangement, you have the flexibility of messing up your data - in any way, knowing that whatever data changes you're making are only - being made to a test database. - -Note that this server does *not* automatically detect changes to your Python -source code (as ``runserver`` does). It does, however, detect changes to -templates. - -.. django-admin-option:: --addrport [port number or ipaddr:port] - -Use ``--addrport`` to specify a different port, or IP address and port, from -the default of ``127.0.0.1:8000``. This value follows exactly the same format and -serves exactly the same function as the argument to the ``runserver`` command. - -Examples: - -To run the test server on port 7000 with ``fixture1`` and ``fixture2``:: - - django-admin.py testserver --addrport 7000 fixture1 fixture2 - django-admin.py testserver fixture1 fixture2 --addrport 7000 - -(The above statements are equivalent. We include both of them to demonstrate -that it doesn't matter whether the options come before or after the fixture -arguments.) - -To run on 1.2.3.4:7000 with a ``test`` fixture:: - - django-admin.py testserver --addrport 1.2.3.4:7000 test - -.. versionadded:: 1.3 - -The :djadminopt:`--noinput` option may be provided to suppress all user -prompts. - -validate --------- - -.. django-admin:: validate - -Validates all installed models (according to the :setting:`INSTALLED_APPS` -setting) and prints validation errors to standard output. - -Commands provided by applications -================================= - -Some commands are only available when the ``django.contrib`` application that -:doc:`implements ` them has been -:setting:`enabled `. This section describes them grouped by -their application. - -``django.contrib.auth`` ------------------------ - -changepassword -~~~~~~~~~~~~~~ - -.. django-admin:: changepassword - -.. versionadded:: 1.2 - -This command is only available if Django's :doc:`authentication system -` (``django.contrib.auth``) is installed. - -Allows changing a user's password. It prompts you to enter twice the password of -the user given as parameter. If they both match, the new password will be -changed immediately. If you do not supply a user, the command will attempt to -change the password whose username matches the current user. - -.. versionadded:: 1.4 - -Use the ``--database`` option to specify the database to query for the user. If -it's not supplied, Django will use the ``default`` database. - -Example usage:: - - django-admin.py changepassword ringo - -createsuperuser -~~~~~~~~~~~~~~~ - -.. django-admin:: createsuperuser - -This command is only available if Django's :doc:`authentication system -` (``django.contrib.auth``) is installed. - -Creates a superuser account (a user who has all permissions). This is -useful if you need to create an initial superuser account but did not -do so during ``syncdb``, or if you need to programmatically generate -superuser accounts for your site(s). - -When run interactively, this command will prompt for a password for -the new superuser account. When run non-interactively, no password -will be set, and the superuser account will not be able to log in until -a password has been manually set for it. - -.. django-admin-option:: --username -.. django-admin-option:: --email - -The username and email address for the new account can be supplied by -using the ``--username`` and ``--email`` arguments on the command -line. If either of those is not supplied, ``createsuperuser`` will prompt for -it when running interactively. - -.. versionadded:: 1.4 - -Use the ``--database`` option to specify the database into which the superuser -object will be saved. - -``django.contrib.gis`` ----------------------- - -ogrinspect -~~~~~~~~~~ - -This command is only available if :doc:`GeoDjango ` -(``django.contrib.gis``) is installed. - -Please refer to its :djadmin:`description ` in the GeoDjango -documentation. - -``django.contrib.sitemaps`` ---------------------------- - -ping_google -~~~~~~~~~~~ - -This command is only available if the :doc:`Sitemaps framework -` (``django.contrib.sitemaps``) is installed. - -Please refer to its :djadmin:`description ` in the Sitemaps -documentation. - -``django.contrib.staticfiles`` ------------------------------- - -collectstatic -~~~~~~~~~~~~~ - -This command is only available if the :doc:`static files application -` (``django.contrib.staticfiles``) is installed. - -Please refer to its :djadmin:`description ` in the -:doc:`staticfiles ` documentation. - -findstatic -~~~~~~~~~~ - -This command is only available if the :doc:`static files application -` (``django.contrib.staticfiles``) is installed. - -Please refer to its :djadmin:`description ` in the :doc:`staticfiles -` documentation. - -Default options -=============== - -Although some commands may allow their own custom options, every command -allows for the following options: - -.. django-admin-option:: --pythonpath - -Example usage:: - - django-admin.py syncdb --pythonpath='/home/djangoprojects/myproject' - -Adds the given filesystem path to the Python `import search path`_. If this -isn't provided, ``django-admin.py`` will use the ``PYTHONPATH`` environment -variable. - -Note that this option is unnecessary in ``manage.py``, because it takes care of -setting the Python path for you. - -.. _import search path: http://diveintopython.net/getting_to_know_python/everything_is_an_object.html - -.. django-admin-option:: --settings - -Example usage:: - - django-admin.py syncdb --settings=mysite.settings - -Explicitly specifies the settings module to use. The settings module should be -in Python package syntax, e.g. ``mysite.settings``. If this isn't provided, -``django-admin.py`` will use the ``DJANGO_SETTINGS_MODULE`` environment -variable. - -Note that this option is unnecessary in ``manage.py``, because it uses -``settings.py`` from the current project by default. - -.. django-admin-option:: --traceback - -Example usage:: - - django-admin.py syncdb --traceback - -By default, ``django-admin.py`` will show a simple error message whenever an -error occurs. If you specify ``--traceback``, ``django-admin.py`` will -output a full stack trace whenever an exception is raised. - -.. django-admin-option:: --verbosity - -Example usage:: - - django-admin.py syncdb --verbosity 2 - -Use ``--verbosity`` to specify the amount of notification and debug information -that ``django-admin.py`` should print to the console. - -* ``0`` means no output. -* ``1`` means normal output (default). -* ``2`` means verbose output. -* ``3`` means *very* verbose output. - -Common options -============== - -The following options are not available on every command, but they are common -to a number of commands. - -.. django-admin-option:: --database - -.. versionadded:: 1.2 - -Used to specify the database on which a command will operate. If not -specified, this option will default to an alias of ``default``. - -For example, to dump data from the database with the alias ``master``:: - - django-admin.py dumpdata --database=master - -.. django-admin-option:: --exclude - -Exclude a specific application from the applications whose contents is -output. For example, to specifically exclude the `auth` application from -the output of dumpdata, you would call:: - - django-admin.py dumpdata --exclude=auth - -If you want to exclude multiple applications, use multiple ``--exclude`` -directives:: - - django-admin.py dumpdata --exclude=auth --exclude=contenttypes - -.. django-admin-option:: --locale - -Use the ``--locale`` or ``-l`` option to specify the locale to process. -If not provided all locales are processed. - -.. django-admin-option:: --noinput - -Use the ``--noinput`` option to suppress all user prompting, such as "Are -you sure?" confirmation messages. This is useful if ``django-admin.py`` is -being executed as an unattended, automated script. - -Extra niceties -============== - -.. _syntax-coloring: - -Syntax coloring ---------------- - -The ``django-admin.py`` / ``manage.py`` commands will use pretty -color-coded output if your terminal supports ANSI-colored output. It -won't use the color codes if you're piping the command's output to -another program. - -The colors used for syntax highlighting can be customized. Django -ships with three color palettes: - -* ``dark``, suited to terminals that show white text on a black - background. This is the default palette. - -* ``light``, suited to terminals that show black text on a white - background. - -* ``nocolor``, which disables syntax highlighting. - -You select a palette by setting a ``DJANGO_COLORS`` environment -variable to specify the palette you want to use. For example, to -specify the ``light`` palette under a Unix or OS/X BASH shell, you -would run the following at a command prompt:: - - export DJANGO_COLORS="light" - -You can also customize the colors that are used. Django specifies a -number of roles in which color is used: - -* ``error`` - A major error. -* ``notice`` - A minor error. -* ``sql_field`` - The name of a model field in SQL. -* ``sql_coltype`` - The type of a model field in SQL. -* ``sql_keyword`` - A SQL keyword. -* ``sql_table`` - The name of a model in SQL. -* ``http_info`` - A 1XX HTTP Informational server response. -* ``http_success`` - A 2XX HTTP Success server response. -* ``http_not_modified`` - A 304 HTTP Not Modified server response. -* ``http_redirect`` - A 3XX HTTP Redirect server response other than 304. -* ``http_not_found`` - A 404 HTTP Not Found server response. -* ``http_bad_request`` - A 4XX HTTP Bad Request server response other than 404. -* ``http_server_error`` - A 5XX HTTP Server Error response. - -Each of these roles can be assigned a specific foreground and -background color, from the following list: - -* ``black`` -* ``red`` -* ``green`` -* ``yellow`` -* ``blue`` -* ``magenta`` -* ``cyan`` -* ``white`` - -Each of these colors can then be modified by using the following -display options: - -* ``bold`` -* ``underscore`` -* ``blink`` -* ``reverse`` -* ``conceal`` - -A color specification follows one of the following patterns: - -* ``role=fg`` -* ``role=fg/bg`` -* ``role=fg,option,option`` -* ``role=fg/bg,option,option`` - -where ``role`` is the name of a valid color role, ``fg`` is the -foreground color, ``bg`` is the background color and each ``option`` -is one of the color modifying options. Multiple color specifications -are then separated by semicolon. For example:: - - export DJANGO_COLORS="error=yellow/blue,blink;notice=magenta" - -would specify that errors be displayed using blinking yellow on blue, -and notices displayed using magenta. All other color roles would be -left uncolored. - -Colors can also be specified by extending a base palette. If you put -a palette name in a color specification, all the colors implied by that -palette will be loaded. So:: - - export DJANGO_COLORS="light;error=yellow/blue,blink;notice=magenta" - -would specify the use of all the colors in the light color palette, -*except* for the colors for errors and notices which would be -overridden as specified. - -Bash completion ---------------- - -If you use the Bash shell, consider installing the Django bash completion -script, which lives in ``extras/django_bash_completion`` in the Django -distribution. It enables tab-completion of ``django-admin.py`` and -``manage.py`` commands, so you can, for instance... - -* Type ``django-admin.py``. -* Press [TAB] to see all available options. -* Type ``sql``, then [TAB], to see all available options whose names start - with ``sql``. - - -See :doc:`/howto/custom-management-commands` for how to add customized actions. - - -========================================== -Running management commands from your code -========================================== - -.. _call-command: - -.. function:: django.core.management.call_command(name, *args, **options) - -To call a management command from code use ``call_command``. - -``name`` - the name of the command to call. - -``*args`` - a list of arguments accepted by the command. - -``**options`` - named options accepted on the command-line. - -Examples:: - - from django.core import management - management.call_command('flush', verbosity=0, interactive=False) - management.call_command('loaddata', 'test_data', verbosity=0) +============================= +django-admin.py and manage.py +============================= + +``django-admin.py`` is Django's command-line utility for administrative tasks. +This document outlines all it can do. + +In addition, ``manage.py`` is automatically created in each Django project. +``manage.py`` is a thin wrapper around ``django-admin.py`` that takes care of +two things for you before delegating to ``django-admin.py``: + +* It puts your project's package on ``sys.path``. + +* It sets the :envvar:`DJANGO_SETTINGS_MODULE` environment variable so that + it points to your project's ``settings.py`` file. + +The ``django-admin.py`` script should be on your system path if you installed +Django via its ``setup.py`` utility. If it's not on your path, you can find it +in ``site-packages/django/bin`` within your Python installation. Consider +symlinking it from some place on your path, such as ``/usr/local/bin``. + +For Windows users, who do not have symlinking functionality available, you can +copy ``django-admin.py`` to a location on your existing path or edit the +``PATH`` settings (under ``Settings - Control Panel - System - Advanced - +Environment...``) to point to its installed location. + +Generally, when working on a single Django project, it's easier to use +``manage.py``. Use ``django-admin.py`` with ``DJANGO_SETTINGS_MODULE``, or the +``--settings`` command line option, if you need to switch between multiple +Django settings files. + +The command-line examples throughout this document use ``django-admin.py`` to +be consistent, but any example can use ``manage.py`` just as well. + +Usage +===== + +.. code-block:: bash + + django-admin.py [options] + manage.py [options] + +``command`` should be one of the commands listed in this document. +``options``, which is optional, should be zero or more of the options available +for the given command. + +Getting runtime help +-------------------- + +.. django-admin:: help + +Run ``django-admin.py help`` to display usage information and a list of the +commands provided by each application. + +Run ``django-admin.py help --commands`` to display a list of all available +commands. + +Run ``django-admin.py help `` to display a description of the given +command and a list of its available options. + +App names +--------- + +Many commands take a list of "app names." An "app name" is the basename of +the package containing your models. For example, if your :setting:`INSTALLED_APPS` +contains the string ``'mysite.blog'``, the app name is ``blog``. + +Determining the version +----------------------- + +.. django-admin:: version + +Run ``django-admin.py version`` to display the current Django version. + +The output follows the schema described in :pep:`386`:: + + 1.4.dev17026 + 1.4a1 + 1.4 + +Displaying debug output +----------------------- + +Use :djadminopt:`--verbosity` to specify the amount of notification and debug information +that ``django-admin.py`` should print to the console. For more details, see the +documentation for the :djadminopt:`--verbosity` option. + +Available commands +================== + +cleanup +------- + +.. django-admin:: cleanup + +Can be run as a cronjob or directly to clean out old data from the database +(only expired sessions at the moment). + +compilemessages +--------------- + +.. django-admin:: compilemessages + +``makemessages``\ 로 생성한 .po 파일을 내장된 gettext 지원에 사용할 수 있도록 .mo 파일로 컴파일합니다. :doc:`/topics/i18n/index` 참조. + +로케일을 지정하려면 :djadminopt:`--locale` 옵션을 사용합니다. 생략한 경우, 모든 로케일에 대하여 처리합니다. + +용례:: + + django-admin.py compilemessages --locale=br_PT + +createcachetable +---------------- + +.. django-admin:: createcachetable + +Creates a cache table named ``tablename`` for use with the database cache +backend. See :doc:`/topics/cache` for more information. + +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database +onto which the cachetable will be installed. + +dbshell +------- + +.. django-admin:: dbshell + +Runs the command-line client for the database engine specified in your +``ENGINE`` setting, with the connection parameters specified in your +:setting:`USER`, :setting:`PASSWORD`, etc., settings. + +* For PostgreSQL, this runs the ``psql`` command-line client. +* For MySQL, this runs the ``mysql`` command-line client. +* For SQLite, this runs the ``sqlite3`` command-line client. + +This command assumes the programs are on your ``PATH`` so that a simple call to +the program name (``psql``, ``mysql``, ``sqlite3``) will find the program in +the right place. There's no way to specify the location of the program +manually. + +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database +onto which to open a shell. + +diffsettings +------------ + +.. django-admin:: diffsettings + +Displays differences between the current settings file and Django's default +settings. + +Settings that don't appear in the defaults are followed by ``"###"``. For +example, the default settings don't define :setting:`ROOT_URLCONF`, so +:setting:`ROOT_URLCONF` is followed by ``"###"`` in the output of +``diffsettings``. + +Note that Django's default settings live in ``django/conf/global_settings.py``, +if you're ever curious to see the full list of defaults. + +dumpdata +-------------------------------------------- + +.. django-admin:: dumpdata + +Outputs to standard output all data in the database associated with the named +application(s). + +If no application name is provided, all installed applications will be dumped. + +The output of ``dumpdata`` can be used as input for ``loaddata``. + +Note that ``dumpdata`` uses the default manager on the model for selecting the +records to dump. If you're using a :ref:`custom manager ` as +the default manager and it filters some of the available records, not all of the +objects will be dumped. + +.. versionadded:: 1.3 + +The :djadminopt:`--all` option may be provided to specify that +``dumpdata`` should use Django's base manager, dumping records which +might otherwise be filtered or modified by a custom manager. + +.. django-admin-option:: --format + +By default, ``dumpdata`` will format its output in JSON, but you can use the +``--format`` option to specify another format. Currently supported formats +are listed in :ref:`serialization-formats`. + +.. django-admin-option:: --indent + +By default, ``dumpdata`` will output all data on a single line. This isn't +easy for humans to read, so you can use the ``--indent`` option to +pretty-print the output with a number of indentation spaces. + +The :djadminopt:`--exclude` option may be provided to prevent specific +applications from being dumped. + +.. versionadded:: 1.3 + +The :djadminopt:`--exclude` option may also be provided to prevent specific +models (specified as in the form of ``appname.ModelName``) from being dumped. + +In addition to specifying application names, you can provide a list of +individual models, in the form of ``appname.Model``. If you specify a model +name to ``dumpdata``, the dumped output will be restricted to that model, +rather than the entire application. You can also mix application names and +model names. + +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database +onto which the data will be loaded. + +.. django-admin-option:: --natural + +.. versionadded:: 1.2 + +Use :ref:`natural keys ` to represent +any foreign key and many-to-many relationship with a model that provides +a natural key definition. If you are dumping ``contrib.auth`` ``Permission`` +objects or ``contrib.contenttypes`` ``ContentType`` objects, you should +probably be using this flag. + +flush +----- + +.. django-admin:: flush + +Returns the database to the state it was in immediately after syncdb was +executed. This means that all data will be removed from the database, any +post-synchronization handlers will be re-executed, and the ``initial_data`` +fixture will be re-installed. + +The :djadminopt:`--noinput` option may be provided to suppress all user +prompts. + +.. versionadded:: 1.2 + +The :djadminopt:`--database` option may be used to specify the database +to flush. + +inspectdb +--------- + +.. django-admin:: inspectdb + +Introspects the database tables in the database pointed-to by the +:setting:`NAME` setting and outputs a Django model module (a ``models.py`` +file) to standard output. + +Use this if you have a legacy database with which you'd like to use Django. +The script will inspect the database and create a model for each table within +it. + +As you might expect, the created models will have an attribute for every field +in the table. Note that ``inspectdb`` has a few special cases in its field-name +output: + +* If ``inspectdb`` cannot map a column's type to a model field type, it'll + use ``TextField`` and will insert the Python comment + ``'This field type is a guess.'`` next to the field in the generated + model. + +* If the database column name is a Python reserved word (such as + ``'pass'``, ``'class'`` or ``'for'``), ``inspectdb`` will append + ``'_field'`` to the attribute name. For example, if a table has a column + ``'for'``, the generated model will have a field ``'for_field'``, with + the ``db_column`` attribute set to ``'for'``. ``inspectdb`` will insert + the Python comment + ``'Field renamed because it was a Python reserved word.'`` next to the + field. + +This feature is meant as a shortcut, not as definitive model generation. After +you run it, you'll want to look over the generated models yourself to make +customizations. In particular, you'll need to rearrange models' order, so that +models that refer to other models are ordered properly. + +Primary keys are automatically introspected for PostgreSQL, MySQL and +SQLite, in which case Django puts in the ``primary_key=True`` where +needed. + +``inspectdb`` works with PostgreSQL, MySQL and SQLite. Foreign-key detection +only works in PostgreSQL and with certain types of MySQL tables. + +.. versionadded:: 1.2 + +The :djadminopt:`--database` option may be used to specify the +database to introspect. + +loaddata +------------------------------ + +.. django-admin:: loaddata + +Searches for and loads the contents of the named fixture into the database. + +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database +onto which the data will be loaded. + +What's a "fixture"? +~~~~~~~~~~~~~~~~~~~ + +A *fixture* is a collection of files that contain the serialized contents of +the database. Each fixture has a unique name, and the files that comprise the +fixture can be distributed over multiple directories, in multiple applications. + +Django will search in three locations for fixtures: + +1. In the ``fixtures`` directory of every installed application +2. In any directory named in the :setting:`FIXTURE_DIRS` setting +3. In the literal path named by the fixture + +Django will load any and all fixtures it finds in these locations that match +the provided fixture names. + +If the named fixture has a file extension, only fixtures of that type +will be loaded. For example:: + + django-admin.py loaddata mydata.json + +would only load JSON fixtures called ``mydata``. The fixture extension +must correspond to the registered name of a +:ref:`serializer ` (e.g., ``json`` or ``xml``). + +If you omit the extensions, Django will search all available fixture types +for a matching fixture. For example:: + + django-admin.py loaddata mydata + +would look for any fixture of any fixture type called ``mydata``. If a fixture +directory contained ``mydata.json``, that fixture would be loaded +as a JSON fixture. + +The fixtures that are named can include directory components. These +directories will be included in the search path. For example:: + + django-admin.py loaddata foo/bar/mydata.json + +would search ``/fixtures/foo/bar/mydata.json`` for each installed +application, ``/foo/bar/mydata.json`` for each directory in +:setting:`FIXTURE_DIRS`, and the literal path ``foo/bar/mydata.json``. + +When fixture files are processed, the data is saved to the database as is. +Model defined ``save`` methods and ``pre_save`` signals are not called. + +Note that the order in which fixture files are processed is undefined. However, +all fixture data is installed as a single transaction, so data in +one fixture can reference data in another fixture. If the database backend +supports row-level constraints, these constraints will be checked at the +end of the transaction. + +The ``dumpdata`` command can be used to generate input for ``loaddata``. + +Compressed fixtures +~~~~~~~~~~~~~~~~~~~ + +Fixtures may be compressed in ``zip``, ``gz``, or ``bz2`` format. For example:: + + django-admin.py loaddata mydata.json + +would look for any of ``mydata.json``, ``mydata.json.zip``, +``mydata.json.gz``, or ``mydata.json.bz2``. The first file contained within a +zip-compressed archive is used. + +Note that if two fixtures with the same name but different +fixture type are discovered (for example, if ``mydata.json`` and +``mydata.xml.gz`` were found in the same fixture directory), fixture +installation will be aborted, and any data installed in the call to +``loaddata`` will be removed from the database. + +.. admonition:: MySQL with MyISAM and fixtures + + The MyISAM storage engine of MySQL doesn't support transactions or + constraints, so if you use MyISAM, you won't get validation of fixture + data, or a rollback if multiple transaction files are found. + +Database-specific fixtures +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you're in a multi-database setup, you might have fixture data that +you want to load onto one database, but not onto another. In this +situation, you can add database identifier into the names of your fixtures. + +For example, if your :setting:`DATABASES` setting has a 'master' database +defined, name the fixture ``mydata.master.json`` or +``mydata.master.json.gz`` and the fixture will only be loaded when you +specify you want to load data into the ``master`` database. + +makemessages +------------ + +.. django-admin:: makemessages + +현재 디렉토리의 전체 소스 트리를 돌면서 번역 표시가 된 문자열을 뽑아냅니다. (django 트리 내의) conf/locale 또는 (프로젝트 및 애플리케이션의 경우) locale 디렉토리에 메시지 파일을 생성하거나 수정합니다. 내장된 gettext 지원을 상ㅇ하기 위해서는 메시지 파일을 변경한 후에 ``compilemessages``\ 로 컴파일하여야 합니다. 자세한 내용은 :ref:`i18n 문서 `\ 를 참조하세요. + +.. django-admin-option:: --all + +사용가능한 모든 언어에 대하여 메시지 파일을 수정하려면 ``--all`` 또는 ``-a`` 옵션을 사용합니다. + +용례:: + + django-admin.py makemessages --all + +.. django-admin-option:: --extension + +검사할 파일 확장자의 목록을 정의하려면 ``--extension`` 또는 ``-e`` 옵션을 사용합니다(기본값: ".html", ".txt"). + +용례:: + + django-admin.py makemessages --locale=de --extension xhtml + +쉼표로 여러 확장자를 구분하거나 -e 또는 --extension 옵션을 여러 번 사용합니다. + +:: + + django-admin.py makemessages --locale=de --extension=html,txt --extension xml + +처리할 로케일을 지정하려면 :djadminopt:`--locale` 옵션을 사용합니다. + +용례:: + + django-admin.py makemessages --locale=br_PT + +.. django-admin-option:: --domain + +메시지 파일의 도메인을 변경하려면 ``--domain`` 또는 ``-d`` 옵션을 사용합니다. +현재 지원 형식:: + +* ``django``: 모든 ``*.py``, ``*.html`` 및 ``*.txt`` 파일 (기본값) +* ``djangojs``: ``*.js`` 파일 + +.. django-admin-option:: --symlinks + +.. versionadded:: 1.2 + +새로운 번역 문자열을 찾을 때 디렉토리에 대한 심볼릭 링크를 따라가려면 ``--symlinks`` 또는 ``-s`` 옵션을 사용합니다. + +용례:: + + django-admin.py makemessages --locale=de --symlinks + +.. django-admin-option:: --ignore + +``--ignore`` 또는 ``-i`` 옵션을 사용하면 :mod:`glob`-스타일 패턴과 일치하는 파일이나 디렉토리를 무시합니다. 여러 번 사용하여 무시할 패턴을 추가로 지정할 수 있습니다. + +기본으로 적용되는 패턴: ``'CVS'``, ``'.*'``, ``'*~'`` + +용례:: + + django-admin.py makemessages --locale=en_US --ignore=apps/* --ignore=secret/*.html + +.. django-admin-option:: --no-default-ignore + +``--no-default-ignore`` 옵션을 사용하면 :djadminopt:`--ignore`의 기본값을 적용하지 않습니다. + +.. django-admin-option:: --no-wrap + +.. versionadded:: 1.3 + +``--no-wrap`` 옵션을 사용하면 언어 파일의 긴 메시지를 여러 행으로 분할하지 않습니다. + +.. django-admin-option:: --no-location + +.. versionadded:: 1.4 + +``--no-location`` 옵션을 사용하면 언어 파일에 '``#: filename:line``' 주석 행을 기록하지 않습니다. 이 옵션을 사용할 경우 숙련된 번역자가 각 메시지의 문맥을 이해하는 데에 어려움을 겪을 수도 있으므로 주의하시기 바랍니다. + +reset +--------------------------- + +.. deprecated:: 1.3 + This command has been deprecated. The ``flush`` can be used to delete + everything. You can also use ALTER TABLE or DROP TABLE statements manually. + +.. django-admin:: reset + +Executes the equivalent of ``sqlreset`` for the given app name(s). + +The :djadminopt:`--noinput` option may be provided to suppress all user +prompts. + +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the alias +of the database to reset. + +runfcgi [options] +----------------- + +.. django-admin:: runfcgi + +Starts a set of FastCGI processes suitable for use with any Web server that +supports the FastCGI protocol. See the :doc:`FastCGI deployment documentation +` for details. Requires the Python FastCGI module from +`flup`_. + +.. versionadded:: 1.4 + Internally, this wraps the WSGI application object specified by the + :setting:`WSGI_APPLICATION` setting. + +.. _flup: http://www.saddi.com/software/flup/ + +The options accepted by this command are passed to the FastCGI library and +don't use the ``'--'`` prefix as is usual for other Django management commands. + +.. django-admin-option:: protocol + +``protocol=PROTOCOL`` + +Protocol to use. *PROTOCOL* can be ``fcgi``, ``scgi``, ``ajp``, etc. +(default is ``fcgi``) + +.. django-admin-option:: host + +``host=HOSTNAME`` + +Hostname to listen on. + +.. django-admin-option:: port + +``port=PORTNUM`` + +Port to listen on. + +.. django-admin-option:: socket + +``socket=FILE`` + +UNIX socket to listen on. + +.. django-admin-option:: method + +``method=IMPL`` + +Possible values: ``prefork`` or ``threaded`` (default ``prefork``) + +.. django-admin-option:: maxrequests + +``maxrequests=NUMBER`` + +Number of requests a child handles before it is killed and a new child is +forked (0 means no limit). + +.. django-admin-option:: maxspare + +``maxspare=NUMBER`` + +Max number of spare processes / threads. + +.. django-admin-option:: minspare + +``minspare=NUMBER`` + +Min number of spare processes / threads. + +.. django-admin-option:: maxchildren + +``maxchildren=NUMBER`` + +Hard limit number of processes / threads. + +.. django-admin-option:: daemonize + +``daemonize=BOOL`` + +Whether to detach from terminal. + +.. django-admin-option:: pidfile + +``pidfile=FILE`` + +Write the spawned process-id to file *FILE*. + +.. django-admin-option:: workdir + +``workdir=DIRECTORY`` + +Change to directory *DIRECTORY* when daemonizing. + +.. django-admin-option:: debug + +``debug=BOOL`` + +Set to true to enable flup tracebacks. + +.. django-admin-option:: outlog + +``outlog=FILE`` + +Write stdout to the *FILE* file. + +.. django-admin-option:: errlog + +``errlog=FILE`` + +Write stderr to the *FILE* file. + +.. django-admin-option:: umask + +``umask=UMASK`` + +Umask to use when daemonizing. The value is interpeted as an octal number +(default value is ``022``). + +용례:: + + django-admin.py runfcgi socket=/tmp/fcgi.sock method=prefork daemonize=true \ + pidfile=/var/run/django-fcgi.pid + +Run a FastCGI server as a daemon and write the spawned PID in a file. + +runserver [port or address:port] +-------------------------------- + +.. django-admin:: runserver + +Starts a lightweight development Web server on the local machine. By default, +the server runs on port 8000 on the IP address ``127.0.0.1``. You can pass in an +IP address and port number explicitly. + +If you run this script as a user with normal privileges (recommended), you +might not have access to start a port on a low port number. Low port numbers +are reserved for the superuser (root). + +.. versionadded:: 1.4 + This server uses the WSGI application object specified by the + :setting:`WSGI_APPLICATION` setting. + +DO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through +security audits or performance tests. (And that's how it's gonna stay. We're in +the business of making Web frameworks, not Web servers, so improving this +server to be able to handle a production environment is outside the scope of +Django.) + +The development server automatically reloads Python code for each request, as +needed. You don't need to restart the server for code changes to take effect. + +When you start the server, and each time you change Python code while the +server is running, the server will validate all of your installed models. (See +the ``validate`` command below.) If the validator finds errors, it will print +them to standard output, but it won't stop the server. + +You can run as many servers as you want, as long as they're on separate ports. +Just execute ``django-admin.py runserver`` more than once. + +Note that the default IP address, ``127.0.0.1``, is not accessible from other +machines on your network. To make your development server viewable to other +machines on the network, use its own IP address (e.g. ``192.168.2.1``) or +``0.0.0.0`` or ``::`` (with IPv6 enabled). + +.. versionchanged:: 1.3 + +You can provide an IPv6 address surrounded by brackets +(e.g. ``[200a::1]:8000``). This will automatically enable IPv6 support. + +A hostname containing ASCII-only characters can also be used. + +.. django-admin-option:: --adminmedia + +Use the ``--adminmedia`` option to tell Django where to find the various CSS +and JavaScript files for the Django admin interface. Normally, the development +server serves these files out of the Django source tree magically, but you'd +want to use this if you made any changes to those files for your own site. + +용례:: + + django-admin.py runserver --adminmedia=/tmp/new-admin-style/ + +.. versionchanged:: 1.3 + +If the :doc:`staticfiles` contrib app is enabled +(default in new projects) the :djadmin:`runserver` command will be overriden +with an own :djadmin:`runserver` command which doesn't +have the :djadminopt:`--adminmedia` option due to deprecation. + +.. django-admin-option:: --noreload + +Use the ``--noreload`` option to disable the use of the auto-reloader. This +means any Python code changes you make while the server is running will *not* +take effect if the particular Python modules have already been loaded into +memory. + +용례:: + + django-admin.py runserver --noreload + +.. django-admin-option:: --nothreading + +.. versionadded:: 1.4 + +Use the ``--nothreading`` option to disable the use of threading in the +development server. + +.. django-admin-option:: --ipv6, -6 + +.. versionadded:: 1.3 + +Use the ``--ipv6`` (or shorter ``-6``) option to tell Django to use IPv6 for +the development server. This changes the default IP address from +``127.0.0.1`` to ``::1``. + +용례:: + + django-admin.py runserver --ipv6 + +Examples of using different ports and addresses +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Port 8000 on IP address ``127.0.0.1``:: + + django-admin.py runserver + +Port 8000 on IP address ``1.2.3.4``:: + + django-admin.py runserver 1.2.3.4:8000 + +Port 7000 on IP address ``127.0.0.1``:: + + django-admin.py runserver 7000 + +Port 7000 on IP address ``1.2.3.4``:: + + django-admin.py runserver 1.2.3.4:7000 + +Port 8000 on IPv6 address ``::1``:: + + django-admin.py runserver -6 + +Port 7000 on IPv6 address ``::1``:: + + django-admin.py runserver -6 7000 + +Port 7000 on IPv6 address ``2001:0db8:1234:5678::9``:: + + django-admin.py runserver [2001:0db8:1234:5678::9]:7000 + +Port 8000 on IPv4 address of host ``localhost``:: + + django-admin.py runserver localhost:8000 + +Port 8000 on IPv6 address of host ``localhost``:: + + django-admin.py runserver -6 localhost:8000 + +Serving static files with the development server +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +By default, the development server doesn't serve any static files for your site +(such as CSS files, images, things under :setting:`MEDIA_URL` and so forth). If +you want to configure Django to serve static media, read :doc:`/howto/static-files`. + +shell +----- + +.. django-admin:: shell + +Starts the Python interactive interpreter. + +Django will use IPython_ or bpython_ if either is installed. If you have a +rich shell installed but want to force use of the "plain" Python interpreter, +use the ``--plain`` option, like so:: + + django-admin.py shell --plain + +.. _IPython: http://ipython.scipy.org/ +.. _bpython: http://bpython-interpreter.org/ + +sql +------------------------- + +.. django-admin:: sql + +Prints the CREATE TABLE SQL statements for the given app name(s). + +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database for +which to print the SQL. + +sqlall +---------------------------- + +.. django-admin:: sqlall + +Prints the CREATE TABLE and initial-data SQL statements for the given app name(s). + +Refer to the description of ``sqlcustom`` for an explanation of how to +specify initial data. + +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database for +which to print the SQL. + +sqlclear +------------------------------ + +.. django-admin:: sqlclear + +Prints the DROP TABLE SQL statements for the given app name(s). + +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database for +which to print the SQL. + +sqlcustom +------------------------------- + +.. django-admin:: sqlcustom + +Prints the custom SQL statements for the given app name(s). + +For each model in each specified app, this command looks for the file +``/sql/.sql``, where ```` is the given app name and +```` is the model's name in lowercase. For example, if you have an +app ``news`` that includes a ``Story`` model, ``sqlcustom`` will attempt +to read a file ``news/sql/story.sql`` and append it to the output of this +command. + +Each of the SQL files, if given, is expected to contain valid SQL. The SQL +files are piped directly into the database after all of the models' +table-creation statements have been executed. Use this SQL hook to make any +table modifications, or insert any SQL functions into the database. + +Note that the order in which the SQL files are processed is undefined. + +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database for +which to print the SQL. + +sqlflush +-------- + +.. django-admin:: sqlflush + +Prints the SQL statements that would be executed for the :djadmin:`flush` +command. + +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database for +which to print the SQL. + +sqlindexes +-------------------------------- + +.. django-admin:: sqlindexes + +Prints the CREATE INDEX SQL statements for the given app name(s). + +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database for +which to print the SQL. + +sqlreset +------------------------------ + +.. deprecated:: 1.3 + This command has been deprecated. The ``sqlflush`` can be used to delete + everything. You can also use ALTER TABLE or DROP TABLE statements manually. + +.. django-admin:: sqlreset + +Prints the DROP TABLE SQL, then the CREATE TABLE SQL, for the given app name(s). + +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database for +which to print the SQL. + +sqlsequencereset +-------------------------------------- + +.. django-admin:: sqlsequencereset + +Prints the SQL statements for resetting sequences for the given app name(s). + +Sequences are indexes used by some database engines to track the next available +number for automatically incremented fields. + +Use this command to generate SQL which will fix cases where a sequence is out +of sync with its automatically incremented field data. + +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database for +which to print the SQL. + +startapp [destination] +-------------------------------- + +.. django-admin:: startapp + +Creates a Django app directory structure for the given app name in the current +directory or the given destination. + +.. versionchanged:: 1.4 + +By default the directory created contains a ``models.py`` file and other app +template files. (See the `source`_ for more details.) If only the app +name is given, the app directory will be created in the current working +directory. + +If the optional destination is provided, Django will use that existing +directory rather than creating a new one. You can use '.' to denote the current +working directory. + +For example:: + + django-admin.py startapp myapp /Users/jezdez/Code/myapp + +.. versionadded:: 1.4 +.. django-admin-option:: --template + +With the ``--template`` option, you can use a custom app template by providing +either the path to a directory with the app template file, or a path to a +compressed file (``.tar.gz``, ``.tar.bz2``, ``.tgz``, ``.tbz``, ``.zip``) +containing the app template files. + +Django will also accept URLs (``http``, ``https``, ``ftp``) to compressed +archives with the app template files, downloading and extracting them on the +fly. + +For example, this would look for an app template in the given directory when +creating the ``myapp`` app:: + + django-admin.py startapp --template=/Users/jezdez/Code/my_app_template myapp + +.. versionadded:: 1.4 + +When Django copies the app template files, it also renders certain files +through the template engine: the files whose extensions match the +``--extension`` option (``py`` by default) and the files whose names are passed +with the ``--name`` option. The :class:`template context +` used is: + +- Any option passed to the startapp command +- ``app_name`` -- the app name as passed to the command +- ``app_directory`` -- the full path of the newly created app + +.. _render_warning: + +.. warning:: + + When the app template files are rendered with the Django template + engine (by default all ``*.py`` files), Django will also replace all + stray template variables contained. For example, if one of the Python files + contains a docstring explaining a particular feature related + to template rendering, it might result in an incorrect example. + + To work around this problem, you can use the :ttag:`templatetag` + templatetag to "escape" the various parts of the template syntax. + +.. _source: https://code.djangoproject.com/browser/django/trunk/django/conf/app_template/ + +startproject [destination] +---------------------------------------- + +.. django-admin:: startproject + +Creates a Django project directory structure for the given project name in +the current directory or the given destination. + +.. versionchanged:: 1.4 + +By default, the new directory contains ``manage.py`` and a project package +(containing a ``settings.py`` and other files). See the `template source`_ for +details. + +If only the project name is given, both the project directory and project +package will be named ```` and the project directory +will be created in the current working directory. + +If the optional destination is provided, Django will use that existing +directory as the project directory, and create ``manage.py`` and the project +package within it. Use '.' to denote the current working directory. + +For example:: + + django-admin.py startproject myproject /Users/jezdez/Code/myproject_repo + +.. versionadded:: 1.4 + +As with the :djadmin:`startapp` command, the ``--template`` option lets you +specify a directory, file path or URL of a custom project template. See the +:djadmin:`startapp` documentation for details of supported project template +formats. + +For example, this would look for a project template in the given directory +when creating the ``myproject`` project:: + + django-admin.py startproject --template=/Users/jezdez/Code/my_project_template myproject + +When Django copies the project template files, it also renders certain files +through the template engine: the files whose extensions match the +``--extension`` option (``py`` by default) and the files whose names are passed +with the ``--name`` option. The :class:`template context +` used is: + +- Any option passed to the startproject command +- ``project_name`` -- the project name as passed to the command +- ``project_directory`` -- the full path of the newly created project +- ``secret_key`` -- a random key for the :setting:`SECRET_KEY` setting + +Please also see the :ref:`rendering warning ` as mentioned +for :djadmin:`startapp`. + +.. _`template source`: https://code.djangoproject.com/browser/django/trunk/django/conf/project_template/ + +syncdb +------ + +.. django-admin:: syncdb + +Creates the database tables for all apps in :setting:`INSTALLED_APPS` whose +tables have not already been created. + +Use this command when you've added new applications to your project and want to +install them in the database. This includes any apps shipped with Django that +might be in :setting:`INSTALLED_APPS` by default. When you start a new project, +run this command to install the default apps. + +.. admonition:: Syncdb will not alter existing tables + + ``syncdb`` will only create tables for models which have not yet been + installed. It will *never* issue ``ALTER TABLE`` statements to match + changes made to a model class after installation. Changes to model classes + and database schemas often involve some form of ambiguity and, in those + cases, Django would have to guess at the correct changes to make. There is + a risk that critical data would be lost in the process. + + If you have made changes to a model and wish to alter the database tables + to match, use the ``sql`` command to display the new SQL structure and + compare that to your existing table schema to work out the changes. + +If you're installing the ``django.contrib.auth`` application, ``syncdb`` will +give you the option of creating a superuser immediately. + +``syncdb`` will also search for and install any fixture named ``initial_data`` +with an appropriate extension (e.g. ``json`` or ``xml``). See the +documentation for ``loaddata`` for details on the specification of fixture +data files. + +The :djadminopt:`--noinput` option may be provided to suppress all user +prompts. + +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database to +synchronize. + +test +----------------------------- + +.. django-admin:: test + +Runs tests for all installed models. See :doc:`/topics/testing` for more +information. + +.. versionadded:: 1.2 +.. django-admin-option:: --failfast + +The ``--failfast`` option can be used to stop running tests and report the +failure immediately after a test fails. + +.. versionadded:: 1.4 +.. django-admin-option:: --testrunner + +The ``--testrunner`` option can be used to control the test runner class that +is used to execute tests. If this value is provided, it overrides the value +provided by the :setting:`TEST_RUNNER` setting. + +.. versionadded:: 1.4 +.. django-admin-option:: --liveserver + +The ``--liveserver`` option can be used to override the default address where +the live server (used with :class:`~django.test.LiveServerTestCase`) is +expected to run from. The default value is ``localhost:8081``. + +testserver +-------------------------------- + +.. django-admin:: testserver + +Runs a Django development server (as in ``runserver``) using data from the +given fixture(s). + +For example, this command:: + + django-admin.py testserver mydata.json + +...would perform the following steps: + +1. Create a test database, as described in :doc:`/topics/testing`. +2. Populate the test database with fixture data from the given fixtures. + (For more on fixtures, see the documentation for ``loaddata`` above.) +3. Runs the Django development server (as in ``runserver``), pointed at + this newly created test database instead of your production database. + +This is useful in a number of ways: + +* When you're writing :doc:`unit tests ` of how your views + act with certain fixture data, you can use ``testserver`` to interact with + the views in a Web browser, manually. + +* Let's say you're developing your Django application and have a "pristine" + copy of a database that you'd like to interact with. You can dump your + database to a fixture (using the ``dumpdata`` command, explained above), + then use ``testserver`` to run your Web application with that data. With + this arrangement, you have the flexibility of messing up your data + in any way, knowing that whatever data changes you're making are only + being made to a test database. + +Note that this server does *not* automatically detect changes to your Python +source code (as ``runserver`` does). It does, however, detect changes to +templates. + +.. django-admin-option:: --addrport [port number or ipaddr:port] + +Use ``--addrport`` to specify a different port, or IP address and port, from +the default of ``127.0.0.1:8000``. This value follows exactly the same format and +serves exactly the same function as the argument to the ``runserver`` command. + +Examples: + +To run the test server on port 7000 with ``fixture1`` and ``fixture2``:: + + django-admin.py testserver --addrport 7000 fixture1 fixture2 + django-admin.py testserver fixture1 fixture2 --addrport 7000 + +(The above statements are equivalent. We include both of them to demonstrate +that it doesn't matter whether the options come before or after the fixture +arguments.) + +To run on 1.2.3.4:7000 with a ``test`` fixture:: + + django-admin.py testserver --addrport 1.2.3.4:7000 test + +.. versionadded:: 1.3 + +The :djadminopt:`--noinput` option may be provided to suppress all user +prompts. + +validate +-------- + +.. django-admin:: validate + +Validates all installed models (according to the :setting:`INSTALLED_APPS` +setting) and prints validation errors to standard output. + +Commands provided by applications +================================= + +Some commands are only available when the ``django.contrib`` application that +:doc:`implements ` them has been +:setting:`enabled `. This section describes them grouped by +their application. + +``django.contrib.auth`` +----------------------- + +changepassword +~~~~~~~~~~~~~~ + +.. django-admin:: changepassword + +.. versionadded:: 1.2 + +This command is only available if Django's :doc:`authentication system +` (``django.contrib.auth``) is installed. + +Allows changing a user's password. It prompts you to enter twice the password of +the user given as parameter. If they both match, the new password will be +changed immediately. If you do not supply a user, the command will attempt to +change the password whose username matches the current user. + +.. versionadded:: 1.4 + +Use the ``--database`` option to specify the database to query for the user. If +it's not supplied, Django will use the ``default`` database. + +용례:: + + django-admin.py changepassword ringo + +createsuperuser +~~~~~~~~~~~~~~~ + +.. django-admin:: createsuperuser + +This command is only available if Django's :doc:`authentication system +` (``django.contrib.auth``) is installed. + +Creates a superuser account (a user who has all permissions). This is +useful if you need to create an initial superuser account but did not +do so during ``syncdb``, or if you need to programmatically generate +superuser accounts for your site(s). + +When run interactively, this command will prompt for a password for +the new superuser account. When run non-interactively, no password +will be set, and the superuser account will not be able to log in until +a password has been manually set for it. + +.. django-admin-option:: --username +.. django-admin-option:: --email + +The username and email address for the new account can be supplied by +using the ``--username`` and ``--email`` arguments on the command +line. If either of those is not supplied, ``createsuperuser`` will prompt for +it when running interactively. + +.. versionadded:: 1.4 + +Use the ``--database`` option to specify the database into which the superuser +object will be saved. + +``django.contrib.gis`` +---------------------- + +ogrinspect +~~~~~~~~~~ + +This command is only available if :doc:`GeoDjango ` +(``django.contrib.gis``) is installed. + +Please refer to its :djadmin:`description ` in the GeoDjango +documentation. + +``django.contrib.sitemaps`` +--------------------------- + +ping_google +~~~~~~~~~~~ + +This command is only available if the :doc:`Sitemaps framework +` (``django.contrib.sitemaps``) is installed. + +Please refer to its :djadmin:`description ` in the Sitemaps +documentation. + +``django.contrib.staticfiles`` +------------------------------ + +collectstatic +~~~~~~~~~~~~~ + +This command is only available if the :doc:`static files application +` (``django.contrib.staticfiles``) is installed. + +Please refer to its :djadmin:`description ` in the +:doc:`staticfiles ` documentation. + +findstatic +~~~~~~~~~~ + +This command is only available if the :doc:`static files application +` (``django.contrib.staticfiles``) is installed. + +Please refer to its :djadmin:`description ` in the :doc:`staticfiles +` documentation. + +Default options +=============== + +Although some commands may allow their own custom options, every command +allows for the following options: + +.. django-admin-option:: --pythonpath + +용례:: + + django-admin.py syncdb --pythonpath='/home/djangoprojects/myproject' + +Adds the given filesystem path to the Python `import search path`_. If this +isn't provided, ``django-admin.py`` will use the ``PYTHONPATH`` environment +variable. + +Note that this option is unnecessary in ``manage.py``, because it takes care of +setting the Python path for you. + +.. _import search path: http://diveintopython.net/getting_to_know_python/everything_is_an_object.html + +.. django-admin-option:: --settings + +용례:: + + django-admin.py syncdb --settings=mysite.settings + +Explicitly specifies the settings module to use. The settings module should be +in Python package syntax, e.g. ``mysite.settings``. If this isn't provided, +``django-admin.py`` will use the ``DJANGO_SETTINGS_MODULE`` environment +variable. + +Note that this option is unnecessary in ``manage.py``, because it uses +``settings.py`` from the current project by default. + +.. django-admin-option:: --traceback + +용례:: + + django-admin.py syncdb --traceback + +By default, ``django-admin.py`` will show a simple error message whenever an +error occurs. If you specify ``--traceback``, ``django-admin.py`` will +output a full stack trace whenever an exception is raised. + +.. django-admin-option:: --verbosity + +용례:: + + django-admin.py syncdb --verbosity 2 + +Use ``--verbosity`` to specify the amount of notification and debug information +that ``django-admin.py`` should print to the console. + +* ``0`` means no output. +* ``1`` means normal output (default). +* ``2`` means verbose output. +* ``3`` means *very* verbose output. + +Common options +============== + +The following options are not available on every command, but they are common +to a number of commands. + +.. django-admin-option:: --database + +.. versionadded:: 1.2 + +Used to specify the database on which a command will operate. If not +specified, this option will default to an alias of ``default``. + +For example, to dump data from the database with the alias ``master``:: + + django-admin.py dumpdata --database=master + +.. django-admin-option:: --exclude + +Exclude a specific application from the applications whose contents is +output. For example, to specifically exclude the `auth` application from +the output of dumpdata, you would call:: + + django-admin.py dumpdata --exclude=auth + +If you want to exclude multiple applications, use multiple ``--exclude`` +directives:: + + django-admin.py dumpdata --exclude=auth --exclude=contenttypes + +.. django-admin-option:: --locale + +Use the ``--locale`` or ``-l`` option to specify the locale to process. +If not provided all locales are processed. + +.. django-admin-option:: --noinput + +Use the ``--noinput`` option to suppress all user prompting, such as "Are +you sure?" confirmation messages. This is useful if ``django-admin.py`` is +being executed as an unattended, automated script. + +Extra niceties +============== + +.. _syntax-coloring: + +Syntax coloring +--------------- + +The ``django-admin.py`` / ``manage.py`` commands will use pretty +color-coded output if your terminal supports ANSI-colored output. It +won't use the color codes if you're piping the command's output to +another program. + +The colors used for syntax highlighting can be customized. Django +ships with three color palettes: + +* ``dark``, suited to terminals that show white text on a black + background. This is the default palette. + +* ``light``, suited to terminals that show black text on a white + background. + +* ``nocolor``, which disables syntax highlighting. + +You select a palette by setting a ``DJANGO_COLORS`` environment +variable to specify the palette you want to use. For example, to +specify the ``light`` palette under a Unix or OS/X BASH shell, you +would run the following at a command prompt:: + + export DJANGO_COLORS="light" + +You can also customize the colors that are used. Django specifies a +number of roles in which color is used: + +* ``error`` - A major error. +* ``notice`` - A minor error. +* ``sql_field`` - The name of a model field in SQL. +* ``sql_coltype`` - The type of a model field in SQL. +* ``sql_keyword`` - A SQL keyword. +* ``sql_table`` - The name of a model in SQL. +* ``http_info`` - A 1XX HTTP Informational server response. +* ``http_success`` - A 2XX HTTP Success server response. +* ``http_not_modified`` - A 304 HTTP Not Modified server response. +* ``http_redirect`` - A 3XX HTTP Redirect server response other than 304. +* ``http_not_found`` - A 404 HTTP Not Found server response. +* ``http_bad_request`` - A 4XX HTTP Bad Request server response other than 404. +* ``http_server_error`` - A 5XX HTTP Server Error response. + +Each of these roles can be assigned a specific foreground and +background color, from the following list: + +* ``black`` +* ``red`` +* ``green`` +* ``yellow`` +* ``blue`` +* ``magenta`` +* ``cyan`` +* ``white`` + +Each of these colors can then be modified by using the following +display options: + +* ``bold`` +* ``underscore`` +* ``blink`` +* ``reverse`` +* ``conceal`` + +A color specification follows one of the following patterns: + +* ``role=fg`` +* ``role=fg/bg`` +* ``role=fg,option,option`` +* ``role=fg/bg,option,option`` + +where ``role`` is the name of a valid color role, ``fg`` is the +foreground color, ``bg`` is the background color and each ``option`` +is one of the color modifying options. Multiple color specifications +are then separated by semicolon. For example:: + + export DJANGO_COLORS="error=yellow/blue,blink;notice=magenta" + +would specify that errors be displayed using blinking yellow on blue, +and notices displayed using magenta. All other color roles would be +left uncolored. + +Colors can also be specified by extending a base palette. If you put +a palette name in a color specification, all the colors implied by that +palette will be loaded. So:: + + export DJANGO_COLORS="light;error=yellow/blue,blink;notice=magenta" + +would specify the use of all the colors in the light color palette, +*except* for the colors for errors and notices which would be +overridden as specified. + +Bash completion +--------------- + +If you use the Bash shell, consider installing the Django bash completion +script, which lives in ``extras/django_bash_completion`` in the Django +distribution. It enables tab-completion of ``django-admin.py`` and +``manage.py`` commands, so you can, for instance... + +* Type ``django-admin.py``. +* Press [TAB] to see all available options. +* Type ``sql``, then [TAB], to see all available options whose names start + with ``sql``. + + +See :doc:`/howto/custom-management-commands` for how to add customized actions. + + +========================================== +Running management commands from your code +========================================== + +.. _call-command: + +.. function:: django.core.management.call_command(name, *args, **options) + +To call a management command from code use ``call_command``. + +``name`` + the name of the command to call. + +``*args`` + a list of arguments accepted by the command. + +``**options`` + named options accepted on the command-line. + +Examples:: + + from django.core import management + management.call_command('flush', verbosity=0, interactive=False) + management.call_command('loaddata', 'test_data', verbosity=0) From 066e485f301aa31460578de17a4ef990162e5b0a Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Fri, 7 Sep 2012 22:58:02 +0900 Subject: [PATCH 053/128] =?UTF-8?q?ref/django-admin=20makemessages=20?= =?UTF-8?q?=EA=B5=90=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ref/django-admin.txt | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/ref/django-admin.txt b/ref/django-admin.txt index 883f6c9..4598827 100644 --- a/ref/django-admin.txt +++ b/ref/django-admin.txt @@ -397,7 +397,7 @@ makemessages .. django-admin:: makemessages -현재 디렉토리의 전체 소스 트리를 돌면서 번역 표시가 된 문자열을 뽑아냅니다. (django 트리 내의) conf/locale 또는 (프로젝트 및 애플리케이션의 경우) locale 디렉토리에 메시지 파일을 생성하거나 수정합니다. 내장된 gettext 지원을 상ㅇ하기 위해서는 메시지 파일을 변경한 후에 ``compilemessages``\ 로 컴파일하여야 합니다. 자세한 내용은 :ref:`i18n 문서 `\ 를 참조하세요. +현재 디렉토리의 전체 소스 트리를 돌면서 번역 표시가 된 문자열을 뽑아냅니다. (django 트리 내의) conf/locale 또는 (프로젝트 및 애플리케이션의 경우) locale 디렉토리에 메시지 파일을 생성하거나 수정합니다. 내장된 gettext 지원을 사용하기 위해서는 메시지 파일을 변경한 후에 ``compilemessages``\ 로 컴파일하여야 합니다. 자세한 내용은 :ref:`i18n 문서 `\ 를 참조하세요. .. django-admin-option:: --all @@ -429,8 +429,9 @@ makemessages .. django-admin-option:: --domain -메시지 파일의 도메인을 변경하려면 ``--domain`` 또는 ``-d`` 옵션을 사용합니다. -현재 지원 형식:: +메시지 파일의 도메인을 변경하려면 ``--domain`` 또는 ``-d`` 옵션을 사용합니다. 현재 지원하는 형식은 다음과 같습니다. + +:: * ``django``: 모든 ``*.py``, ``*.html`` 및 ``*.txt`` 파일 (기본값) * ``djangojs``: ``*.js`` 파일 @@ -447,7 +448,7 @@ makemessages .. django-admin-option:: --ignore -``--ignore`` 또는 ``-i`` 옵션을 사용하면 :mod:`glob`-스타일 패턴과 일치하는 파일이나 디렉토리를 무시합니다. 여러 번 사용하여 무시할 패턴을 추가로 지정할 수 있습니다. +``--ignore`` 또는 ``-i`` 옵션을 사용하면 :mod:`glob` 스타일의 패턴에 일치하는 파일이나 디렉토리를 무시합니다. 여러 번 사용하여 무시할 패턴을 추가로 지정할 수 있습니다. 기본으로 적용되는 패턴: ``'CVS'``, ``'.*'``, ``'*~'`` @@ -457,7 +458,7 @@ makemessages .. django-admin-option:: --no-default-ignore -``--no-default-ignore`` 옵션을 사용하면 :djadminopt:`--ignore`의 기본값을 적용하지 않습니다. +``--no-default-ignore`` 옵션을 사용하면 :djadminopt:`--ignore`\ 의 기본값을 적용하지 않습니다. .. django-admin-option:: --no-wrap From 0832e8b47c5e304c48eeaf66069d2f1bd9a7f934 Mon Sep 17 00:00:00 2001 From: sk8erchoi Date: Sun, 9 Sep 2012 22:44:50 +0900 Subject: [PATCH 054/128] =?UTF-8?q?topics/forms/index=20=EB=B2=88=EC=97=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1~102행 번역 --- topics/forms/index.txt | 785 ++++++++++++++++++++--------------------- 1 file changed, 378 insertions(+), 407 deletions(-) diff --git a/topics/forms/index.txt b/topics/forms/index.txt index 18e55f5..3ea5e22 100644 --- a/topics/forms/index.txt +++ b/topics/forms/index.txt @@ -1,407 +1,378 @@ -================== -Working with forms -================== - -.. admonition:: About this document - - This document provides an introduction to Django's form handling features. - For a more detailed look at specific areas of the forms API, see - :doc:`/ref/forms/api`, :doc:`/ref/forms/fields`, and - :doc:`/ref/forms/validation`. - -.. highlightlang:: html+django - -``django.forms`` is Django's form-handling library. - -While it is possible to process form submissions just using Django's -:class:`~django.http.HttpRequest` class, using the form library takes care of a -number of common form-related tasks. Using it, you can: - -1. Display an HTML form with automatically generated form widgets. -2. Check submitted data against a set of validation rules. -3. Redisplay a form in the case of validation errors. -4. Convert submitted form data to the relevant Python data types. - -Overview -======== - -The library deals with these concepts: - -.. glossary:: - - Widget - A class that corresponds to an HTML form widget, e.g. - ```` or ``