갈루아의 반서재

detail() 뷰로 다시 돌아가보자. 


polls/templates/polls/detail.html

<h1>{{ question.question_text }}</h1>

<ul>

{% for choice in question.choice_set.all %}

    <li>{{ choice.choice_text }}</li>

{% endfor %}

</ul>



템플릿 시스템은 변수의 속성에 접근하기 위해 dot-lookup 구문을 사용한다. 

위의 예에서 장고Django 는 우선 오브젝트 질문에 대해 dictionary lookup 을 수행한다. 그리고 그것이 실패하는 경우에 attribute lookup을 수행한다. attribute lookup 이 실패하면 list-index lookup 을 수행한다. 


{% for %} 루프에서 메서드 호출이 일어난다. question.choice_set.all는 question.choice_set.all() 라는 파이썬 코드로 변환되고, {% for %} 태그에서 사용하기 적합한 보기 오브젝트를 반복해서 반환한다. 


템플릿에서 하드 코딩 URLs 제거


우리는 아래 파일에서 일부 하드코딩 구문을 사용한 적이 있다.


/root/mysite/polls/templates/polls/index.html

{% if latest_question_list %}

    <ul>

    {% for question in latest_question_list %}

        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>

    {% endfor %}

    </ul>

{% else %}

    <p>No polls are available.</p>

{% endif %}



polls.urls 모듈의 url() 함수에서 'name' 인수를 정의했기 때문에, {% url %} 템플릿 태그를 이용하여 특정 URL 경로를 제거할 수 있다. 


{% if latest_question_list %}

    <ul>

    {% for question in latest_question_list %}

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

    {% endfor %}

    </ul>

{% else %}

    <p>No polls are available.</p>

{% endif %}


/root/mysite/polls/urls.py

from django.conf.urls import url

from . import views


urlpatterns = [

    # ex: /polls/

    url(r'^$', views.index, name='index'),

    # ex: /polls/5/

    url(r'^(?P<question_id>[0-9]+)/$', views.detail, name = 'detail' ),

    # ex: /polls/5/results/

    url(r'^(?P<question_id>[0-9]+)/results/$$', views.results, name='results'),

    # ex: /polls/5/vote/

    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote')

    

]


{% url %} 템플릿 태그에 의해 'name' 의 값이 호출된다. polls/specifics/12/ 와 같이 해당 설문의 URL 을 변경하고자 한다면, polls/urls.py 를 아래와 같이 변경하면 되낟. 


...

# added the word 'specifics'

url(r'^specifics/(?P<question_id>[0-9]+)/$', views.detail, name='detail'),

...