django
[Django] App URL mapping
peach_h
2023. 3. 25. 20:56
App URL mapping이란 ?
project 내에서 App이 많아졌을 때, urls.py를 각 App에 mapping하는 방법이다.
-> project urls.py가 끝도 없이 늘어나는 것을 막기 위함
url도 각 app이 관리하게 하는 것
1. project / urls.py에 path를추가한다
이때 import에 include를 추가해줘야함
2. App 하위에 urls.py를 생성한다
원하는 path를 추가 -> myapps/first 이런식으로 연결 될 예정
3. App / views.py를 수정
4. templates에 url과 연결 될 html 파일 생성
- i ndex.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>first</h1>
</body>
</html>
- detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>second</h1>
</body>
</html>
5. runserver로 실행 결과 확인
project / urls.py에는 myapps만 추가했는데
mapping을 함으로 써 /myapps/first/와 /myapps/second url이 추가되었고,
제대로 연결된 것을 확인