Django
URL Namespace / Templates Namespace (Django 플젝 시작 시 유의사항)
zhelddustmq
2024. 8. 16. 17:46
1. URL Namespace
2. Templates Namespace
1. URL Namespace: 어느 소속의 URL인지 밝히는 것
# articles/urls.py
from django.urls import path
from . import views
urlpatterns = [
...
path("hello/", views.hello, name="hello"),
...
]
# users/urls.py
from django.urls import path
from . import views
urlpatterns = [
...
path("hello/", views.hello, name="hello"),
...
]
만약 articles/urls.py에도 hello/ url이 있고, users/urls.py에도 hello/가 있다면 어떤것을 호출하는가?
users는...?
- Django는 서로 다른 앱에서 동일한 URL Name을 사용하는 경우, 고유하게 구분할 수 있도록 namespace를 지원
from django.urls import path
from . import views
app_name = "articles"
urlpatterns = [
...
path("hello/", views.hello, name="hello"),
...
]
- url에 이름공간을 만들어주고 나면, namespace:url_name형태로 사용
{% url 'articles:hello' %}
redirect('articles:hello')
이렇게 namespace를 설정해주고 이전 방식을 사용하면 에러 발생
수정하기
articles
이 url들의 Name을 참조하고 있는 모든 곳들을 수정해야 함. → 따라서 프로젝트 만들 때는 처음부터 app_name을 지정하고 만들자!
{% url 'create' %} -> {% url 'articles:create' %}
redirect('create') -> redirect('articles:create')
users
{% url 'profile' %} -> {% url 'users:profile' %}
redirect('profile') -> redirect('users:profile')
2. Templates Namespace: 어느 소속의 html인지 밝히는 것
만약, users앱에도 index.html이 있고 articles앱에도 index.html 이 있다면
위와 같이 순서가 빠른 녀석의 코드를 호출함
Templates Namespace 만들어주기
- <app_name>/templates/<app_name>으로 구조 만들기( templates 폴더에 app_name 폴더를 만들고 기존 html을 싹다 넣기)
→템플릿을 사용할 때는 <app_name>/template.html 으로 사용!
※ 마찬가지로 처음부터 <app_name>/templates/<app_name>으로 구조를 잡고 시작하기!!