📗 Django 


URL Namespace

hello/는 동일하지만
하나는 articles/hello/, 다른 하나는 uesrs/hello/ 일 때, 어떻게 구분지어야 할까?

 

→ Django는 서로 다른 앱에서 동일한 URL Name을 사용하는 경우, 고유하게 구분할 수 있도록 namespace를 지원한다.

 

순서

Namespace

⬇️

url

 

  • urlpatterns 보다 더 위에 app_name을 적어주면 된다.
    • 이렇게 되면, "articles"의 "data_throw" 이런 식으로 인식하게 된다.
✔️ urls.py, html, views.py 등 모든 파일에 있는 url 주소를 변경해 주자
VSCode에서 돋보기를 누르면 쉽게 찾을 수 있다.

  • 'data_throw' → 'articles : data_throw' 이런 식으로 수정해 주면 namespace 설정 끝이다.

 

🚨 url 하나하나 수정하면서 느낀 거지만, 제발 코드 형식을 통일시키자. 🚨

작은따옴표면 끝까지 작은따옴표,

큰 따옴표면 끝까지 큰 따옴표.

 

✔️ redirect()도 url name을 언급하니, 꼭 수정해 주자


Templates 구조

 

  • settings.py에 보면 Apps의 순서대로 파일을 확인하며 찾아주는 구조이다.
  • 하지만, 'articles'와 'users' 순서를 바꾸게 되면 users에 있는 동일한 html을 가져올 것이다.

Templates Namespace 만들어주기

↓ 처음부터 이런 구조로 Django를 시작하면 좋다.

<app_name>/templates/<app_name>

 

 

  • <app_name> : articles
  • <templates> : articles app 안에 templates 폴더를 만들었다.
  • <articles> : articles app 안에 templates 폴더 안에 articles 폴더를 만들었다.

 

  • articles app 안에 templates 폴더 안에 articles 폴더 속으로 html 파일을 넣어준다.
    • 그러면, articles app 안에 templates 폴더가 templates/articles 이름으로 변경된다.

 

이제 articles app의 views.py을 수정하자

수정 전

⬇️

 

변경 사항

return render(request, "index.html")

⬇️

return render(request, "articles/index.html")

 

  • html 파일 앞에 새로운 경로를 다 적어줘야 한다.
  • 이렇게 하면, articles의 templates의 articles 폴더에서 html 파일을 들고 오게 되는 것이다.

 

+ Recent posts