본문 바로가기
Dev/Web

[Django] MVT (model-view-templete)

by jusep 2024. 4. 11.

MVT 구성요소

Model

  • 사용될 데이터에 대한 정의를 담고 있는 django의 클래스
  • ORM으로 동작한다
  •  model.py.에서 모델 클래스를 정의해서 사용한다
#model.py
from django.db import models

class Person(models, Model):
		first_name = models.CharField(max_length=30)
		last_name = models.CharField(max_length=30)

		class Meta:
        db_table = 'myapp_person'

 

ORM (object-relational mapping)

  • SQL을 사용하지 않고 데이터베이스 스키마를 구성하고 접근할 수 있다
  • 객체를 사용해 데이터를 처리한다

 

URL conf

  • 클라이언트로부터 요청을 받으면 django는 가장 먼저 요청에 들어있는 url이 [urls.py] 파일에 정의된 url 패턴과 매칭되는지 체크
  • url 확인 후 매핑되는 view 호출
# urls.py
from django.urls import path
from . import views

urlpatterns = [
		path('articles/2003/', views.special_case_2003),
		path('articles/<int:year>/', views.year_archive),
		path('articles/<int:year>/<int:month>', views.month_archive),
		path('articles/<int:year>/<int:month>/<slug:slug>', views.archive_detail),
]

 

 

view

  • 요청을 받고 응답을 반환
  • 응답메세지는 HTML, json, XML, 404 등
  • [views.py]에서 함수 또는 클래스의 메소드로 정의=
# veiws.py
from django.http import HttpResponse
import datetime

def current_datetime(request):
		now = datetime.datetiem.now()
		html = '<html><body>It is now %s.</body></html>' % now
		
		return HttpResponse(html)

 

Template

클라이언트에게 반환되는 HTML을 작성

Django에서  template 파일을 찾을때는 settings.py의 TEMPLATES 및 INSTALLED_APPS에서 지정된 앱의 디렉토리에서 *.html 파일을 찾음

'Dev > Web' 카테고리의 다른 글

[FastAPI] 서버 실행할때  (1) 2023.10.04
로컬에서 CORS policy 관련 에러 해결 방법  (0) 2023.04.24

댓글