Django기초

Sally·2026년 4월 16일

Django의 기본 폴더 구조

django-admin startproject 명령어를 실행하면 기본적으로 아래와 같은 구조가 생성된다.

myproject/                  ← 프로젝트 루트
│
├── manage.py               ← 서버 실행, 마이그레이션 등 명령어 도구
│
├── myproject/              ← 프로젝트 설정 폴더
│   ├── __init__.py         ← Python 패키지임을 알리는 파일
│   ├── settings.py         ← 전체 설정 (DB, 앱 등록 등)
│   ├── urls.py             ← 최상위 URL 관리
│   ├── wsgi.py             ← 서버 배포용
│   └── asgi.py             ← 비동기 서버 배포용
│
└── articles/               ← 앱 폴더
    ├── migrations/         ← DB 변경 이력 자동 생성
    ├── templates/          ← HTML 파일 모음
    │   └── articles/       ← 앱 이름과 동일한 폴더 (네임스페이스)
    │       └── *.html
    ├── static/             ← CSS, JS, 이미지
    ├── __init__.py
    ├── admin.py            ← 관리자 페이지 설정
    ├── apps.py             ← 앱 설정
    ├── models.py           ← DB 테이블 정의
    ├── views.py            ← 요청 처리 로직
    ├── urls.py             ← 앱 URL 관리
    └── tests.py            ← 테스트 코드

Django의 MTV 패턴

MTV : Django가 웹 요청을 처리하는 기본 설계 구조

MTV란

글자이름파일역할
MModelmodels.pyDB 테이블 정의 & 데이터 관리
TTemplatetemplates/*.html화면 출력 (HTML)
VViewviews.py요청 받아서 처리하는 로직

사용자 요청부터 브라우저 출력까지

사용자가 /search/?query=hello 요청
        ↓
    urls.py
  (어느 view로 보낼지 결정)
        ↓
    views.py  ←→  models.py
  (로직 처리)     (DB에서 데이터 가져옴)
        ↓
   templates/
  (데이터를 HTML에 끼워서 출력)
        ↓
    사용자 브라우저

실습 코드로 보는 MTV

urls.py — 교통 정리

urlpatterns = [
    path('admin/', admin.site.urls),
    path('articles/', views.index),
    path('dinner/', views.dinner),
    path('search/', views.search),   # /search/ 오면 views.search로 보냄
]

views.py — 실제 처리 (V)

def search(request):
    query = request.GET.get('query')  # URL에서 ?query=hello 꺼냄
    # articles = Article.objects.filter(title=query)  # Model로 DB 조회
    return render(request, 'articles/search.html')   # Template 반환

templates/articles/search.html — 화면 출력 (T)

{% extends 'articles/base.html' %}

{% block content %}
  <form action="#" method="GET">
    <label for="message">검색어</label>
    <input type="text" name="query" id="message">
    <input type="submit" value="submit">
  </form>
{% endblock content %}

models.py — DB 데이터 관리 (M)

class Article(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

4. Django 폴더 구조와 MTV 연결

myproject/
│
├── manage.py
│
├── myproject/
│   ├── settings.py
│   └── urls.py              ← 교통 정리
│
└── articles/
    ├── migrations/          ← DB 변경 이력
    ├── templates/
    │   └── articles/
    │       ├── base.html    ← 공통 뼈대 (T)
    │       └── search.html  ← 화면 출력 (T)
    ├── models.py            ← DB 정의 (M)
    ├── views.py             ← 로직 처리 (V)
    └── urls.py              ← 앱 URL 관리

MVC와 MTV

Django MTV는 다른 프레임워크의 MVC 패턴이랑 거의 같음.

MVCMTV역할
ModelModelDB
ViewTemplate화면
ControllerView로직

전체 흐름 한 줄 정리
URL 요청 → urls.py(연결) → views.py(처리) → models.py(DB) → templates(출력) → 브라우저

profile
sally

0개의 댓글