갈루아의 반서재

Namespacing URL names


현재 예제에서는 하나의 앱만 다루고 있지만, 실제 프로젝트에서 앱의 수는 20개 그 이상일 수도 있다. 그러면 장고는 그러한 URL 네임들을 어떻게 차별화시키는 것일까?

예를 들어, poll 앱의 경우 상세 뷰를 가지고 있고, 동일한 프로젝트에 블로그를 위한 앱을 가지고 있다고 하자. {% url %} 템플릿 태그를 사용할 때 어떤 앱의 뷰를 생성해야하는지 알 수 있을까?


그 해답은 현재의 root URLconf 에 네임스페이스를 추가하는 것이다. mysite/urls.py 에 네임스페이스를 포함하도록 변경해보자. 



/root/mysite/mysite/urls.py


from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^polls/', include('polls.urls', namespace="polls")),
    url(r'^admin/', include(admin.site.urls)),
]


그러면 polls/index.html 템플릿을 수정하자.위에서 지정한 네임스페이스를 지정해주는 것이다. 


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

{% if latest_question_list %}

    <ul>

    {% for question in latest_question_list %}

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

    {% endfor %}

    </ul>

{% else %}

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

{% endif %}