[Django] 강의 내용 정리하기

dongmo jeon·2025년 8월 4일

1. Django 프로젝트 세팅

가상환경 구축 (with Poetry)

poetry new myproject
cd myproject
poetry add django
poetry shell

Django 프로젝트 및 앱 구성

django-admin startproject config .
python manage.py startapp core

config/settings.py에 앱 등록:

INSTALLED_APPS = [
    ...,
    'core',
]

templates 경로 지정하기

  1. 프로젝트 루트에 templates/ 폴더 생성
  2. settings.py에 다음과 같이 지정:
TEMPLATES = [
    {
        ...
        'DIRS': [BASE_DIR / 'templates'],
        ...
    },
]

static 경로 지정하기

  1. 프로젝트 루트에 static/ 폴더 생성
  2. settings.py에 다음과 같이 지정:
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']

media 경로 지정하기

  1. 프로젝트 루트에 media/ 폴더 생성
  2. settings.py에 다음과 같이 지정:
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
  1. config/urls.py에 다음 내용 추가:
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

2. Database Model

모델 정의 예시

# core/models.py

from django.db import models

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

주요 필드 정리

필드명설명
CharField짧은 문자열 (max_length 필수)
TextField긴 문자열
DateTimeField날짜/시간 정보
BooleanFieldTrue/False
ForeignKey다른 모델과 연결
ImageField이미지 업로드

마이그레이션 정리

모델을 데이터베이스에 반영하는 과정

python manage.py makemigrations
python manage.py migrate

3. Jinja 문법

Django의 템플릿 언어는 Jinja2와 매우 유사합니다.

기본 문법

{{ 변수명 }}                     <!-- 출력 -->
{% if 조건문 %} ... {% endif %} <!-- 조건문 -->
{% for item in list %} ... {% endfor %} <!-- 반복문 -->

block / extends 사용법

templates/base.html:

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>

templates/index.html:

{% extends 'base.html' %}

{% block title %}Home{% endblock %}

{% block content %}
<h1>Hello Django</h1>
{% endblock %}

4. FBV (Function Based View)

FBV란?

FBV(Function Based View)는 Django의 기본적인 뷰 방식으로, 하나의 함수가 하나의 URL 요청을 처리합니다.

render() 사용 예시

# core/views.py

from django.shortcuts import render

def home(request):
    return render(request, 'home.html', {'message': 'Hello, Django!'})

redirect() 사용 예시

from django.shortcuts import redirect

def go_to_home(request):
    return redirect('home')  # 'home'은 URL name

5. URL 설정

URL 엔드포인트란?

URL 엔드포인트는 사용자가 웹 브라우저에서 접근하는 경로이며, views 함수와 매핑됩니다.

urlpatterns 예시

# config/urls.py

from django.urls import path
from core import views

urlpatterns = [
    path('', views.home, name='home'),
]

include를 활용한 URL 분리

config/urls.py:

from django.urls import path, include

urlpatterns = [
    path('', include('core.urls')),
]

core/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
]

지금은 아무리 보고 또 봐도 익숙해지지 않지만 언젠가는 익숙해지는 날이 올거라 믿어요...

profile
안녕하세요~~

0개의 댓글