Django 정리

[장고 Template 시작하기]

100.nam 2025. 1. 7. 16:45

1.  요청과 응답

💡 Django가 요청을 받고 응답을 하는 과정은 이렇습니다. (MVT 패턴)

  1. 요청(Request)이 들어오면
  2. URL(urls.py) 처리
  3. View(views.py) 처리
  4. Template(html) 처리
  5. 응답(Response) 전달

 

 

  • urls.py를 열어보자
  • 💡 이 곳은 어떤 url패턴으로 들어오면 어디의 뷰로 보낼까? 를 설정해 주는 곳입니다!
  • urlpatterns 내부에 정의해주면 됩니다!
  • index라는 패턴이 들어오면 views 안에 index 함수로 보내줘라고 만들었다.
# my_first_pjt/my_first_pjt/urls.py

from django.contrib import admin
from django.urls import path
from articles import views #views는 articles 파일에 있으니 가져오기 위해서 import

urlpatterns = [
    path("admin/", admin.site.urls),
    path("index/", views.index), 
]

 

 

  • articles에 view.py에 코드를 적어주자
from django.http import HttpResponse

def index(request):
	response = HttpResponse("<h1>Hello, Django!</h1>") 
	return response

 

  • 저장 후 실행 해보자
python manage.py runserver

 

 

  • 로켓은 사라지고 이러한 화면이 나올 것이다.
  • 이제 내가 코딩한 대로 페이지가 나오게 되었다.
  • 우리가 정해준 index/ 경로로 들어가보자
  • http://127.0.0.1:8000/index/

  • Chrome → HttpRequest → urls.py → views.py → HttpResponse → Chrome
  • 위의 흐름을 거쳐 동작하여 “Hellom Django!”를 볼 수 있게 된 것입니다!

 

2. Template

  • 코드가 길어지면 100줄 다 쓸 수 없기에 Html 파일을 보여주면 좋겠다.
  • views.py에 아래와 같이 코드를 변경해주자
# my_first_pjt/articles/views.py
from django.shortcuts import render

def index(request):
    return render(request, "index.html")

 

  • articles안 폴더에 templates라는 폴더를 만들고 그 안에 index.html를 만들어 주자

  • 이제 이 index.html에 html 코드를 적어주자. 인사만 쓰자
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<h1>
Hello
</h1>    

</body>
</html>
  • 이러고 이제 다시 서버에 들어가보자, 잘 나오는 것을 확인 할 수 있다.
  • HttpRequest → URLs → View→ Template → View → HttpResponse 이런 흐름으로 보여주고 있다.

 

  • my_first_pjt에 setting.py에 들어가보면 56번째 줄에 TEMPLATES가 있다
  • 이 코드에 APP_DIRS= True 가 있는데 이것으로 APP에 Templates에 있는 html를 찾아주는 것이다.