본문 바로가기

Program Language/dJango

django 1.6 Tutorial03 한글 공부


Philosophy(철학)

“뷰”는 장고 앱이 일반적으로 제공하는 웹페이지의 유형중의 하나이다.



첫 뷰 쓰기

views.py에 다음 코드를 입력한다
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

polls폴더에 urls.py를 추가하고 소스를 추가한다. 
from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index')
)
mysite폵더의 urls.py에 다음 소스를 추가한다.
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)),
)

http://localhost:8000/polls/ 를 실행 시, Hello World문장이 나타난다.

urls()의 4개의 argument(인자)는
  1. regex - 정규식
  2. view-뷰
  3. kwargs-임의의 키워드 인자 보기로 - 사전에 전달 할 수 있음
  4. name - 템플릿에서 명확하게 참조하기위해 이름.


더 많은 뷰를 쓰기

polls/view.py 에
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)
코드를 추가하고,

pools.urls 에 
from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
    # ex: /polls/
    url(r'^$', views.index, name='index'),
    # ex: /polls/5/
    url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
    # ex: /polls/5/results/
    url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
    # ex: /polls/5/vote/
    url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)

쓰면 된다.

이렇게 하면 각 주소에 따라서 보여지는 문자가 달라진다.





실제로 무언가 하는 뷰를 만들기

모든 뷰는 두가지 중에 하나의 응답을 한다.
HttpResponse를 통해 내용을 포함한 요청한 페이지를 Object를 통해 리턴 하거나, HTTP404 Exception같은 익셉션을 돌려주거나

각 앱의 하위에 Templates 폴더를 만들면 장고에서 TEMPLATE_DIRS르 수정하지 않고도 템플릿을 확인 한다. 
앱이 아닌 프로젝트의 하위Templates 폴더를 하나 만들어서 관리 할 수도 있지만, 각 앱이 자신의 템플릿을 적용하는데에는 각자 하는 것이 좋다.

Templates 내에 템플릿 이름이 겹칠 경우 장고는 오류를 일으 킬 수 있다. 따라서 Temlates 폴더 내에 앱의 이름(여기서는 polls)을 가진 폴더를 만들고 그 안에 index.html을 만든다.

index.html에는 
{% if latest_poll_list %}
    <ul>
    {% for poll in latest_poll_list %}
        <li><a href="/polls/{{ poll.id }}/"]]
>
{{ poll.question }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}
를 넣어준다.
polls/view.py 에는 
from django.http import HttpResponse
from django.template import RequestContext, loader

from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = RequestContext(request, {
        'latest_poll_list': latest_poll_list,
    })
    return HttpResponse(template.render(context))
를 추가해준다.

이를 더 짧게 만든 함수가 render()이다.
from django.shortcuts import render

from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    context = {'latest_poll_list': latest_poll_list}
    return render(request, 'polls/index.html', context)
render를 import한 후
인덱스에 리턴 부붙과 같이 인자를 넣으면 더 쉽고 짧게 쓸 수 있다.
render()의 인수는 3개로 이건 나중에 다시 보고 수정(살짝 이해 안됨)
The render() function takes the request object as its first argument, a template name as its second argument and a dictionary as its optional third argument. It returns an HttpResponse object of the given template rendered with the given context.



404에러 띄우기

만약 ID가 없다면 페이지가 없음을 알리는 404 에러를 띄운다.
detail.html에 {{poll}}
을 넣어주고

from django.http import Http404
from django.shortcuts import render

from polls.models import Poll
# ...
def detail(request, poll_id):
    try:
        poll = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render(request, 'polls/detail.html', {'poll': poll})
로 detail을 수정해서 아이디가 있으면 poll 에 값을 연결해주고 DoesNotException  이 발생하면 http404 를 발생시킨다.

숏컷 함수 : get_object_or_404()
장고에서 지원하는 숏컷이다.

from django.shortcuts import render, get_object_or_404

from polls.models import Poll
# ...
def detail(request, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id)
    return render(request, 'polls/detail.html', {'poll': poll})



템플릿 시스템 사용하기

detail()로 돌아가보면,  context 변수 poll을 넣어 놓았다. polls/detail.html 템플릿을 이와 같이 수정해보자.
<h1>{{ poll.question }}</h1>
<ul>
{% for choice in poll.choice_set.all %}
    <li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
{{poll.question}}
처음 장고는 디텍토리를 보고 poll 오브젝트를 찾는다.
그 다음, 변수 속성을 찾는다. 동작한다. 만약 조회를 실패했다면, 리스트 인덱스를 찾는다.
->정확하지 않다. 나중에 수정



 템플릿에서 하드코어 URLs 를 제거하기
     
<li><a href="/polls/{{ poll.id }}/"]]
>
{{ poll.question }}</a></li>
와 같이 polls/ ~id 보다는
<li><a href="{% url 'detail' poll.id %}"]]
>
{{ poll.question }}</a></li>
와 같이 url() 펑션을 쓰는것이 좋다.(뭐가 더 좋은지는 크게 감이 안온다. 다른 프로젝트에서 접근 하는데 더 쉽고 어려운 그런게 있는건가?)

이유:polls/1이 아닌
polls/specifics/1 로 바꾸고 싶을 때, 템플릿을 수정하는 것이 아니라, 
url(r'^specifics/(?P<poll_id>\d+)/$', views.detail, name='detail'),
polls/urls.py의 url 부분을 간단하게 수정함으로 그 동작을 수행 할 수 있다.



URL 이름 짓기

튜토리얼 프로젝트는 단지 하나의 앱 polls를 가지고 있다. 진짜 장고 프로젝트는 수많은 앱을 가지고 있기 마련이다. 어떻게 장고는 다른 URL 이름을 구분할까? 
답은 네임스페이스를 내 root URLconf에 추가하는 것이다.
mysite/urls.py 파일에 include 네임스페이싱을 해준다.

urlpatterns = patterns('',
    url(r'^polls/', include('polls.urls', namespace="polls")),
    url(r'^admin/', include(admin.site.urls)),
)
mysite/urls.py 의 urlpatterns의 url()애 namespace를 추가해주고


polls/index 주소에도 polls/detail이라고 적어주면 장고에서 여러개의 앱을 프로젝트에서 사용하더라도 어떤 앱의 detail인지 고민하지 않게 도와준다.


<li><a href="{% url 'detail' poll.id %}"]]
>
{{ poll.question }}</a></li>

to point at the namespaced detail view:

<li><a href="{% url 'polls:detail' poll.id %}"]]
>
{{ poll.question }}</a></li>