본문 바로가기

Python/Django

[Django] Hardcoded URL 제거 / Namespacing URL names

출처

Django Documentation -Removing hardcoded URLs in templates


Removing hardcoded URLs in templates

Hardcoded URLs 예시

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

Hardcoded URLs 제거

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

polls.urls 모듈

# ...
path('<int:question_id>/', views.detail, name='detail'),

Namespacing URL names

  • polls 앱 외에 여러 앱들이 있는 경우
  • app_name을 명시해줌으로써 url name의 중복을 방지할 수 있다.

polls/urls.py

from django.urls import path

from . import views

app_name = 'polls' # app_name 추가
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
    path('<int:question_id>/results/', views.results, name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

polls/index.html

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