poetry new myproject
cd myproject
poetry add django
poetry shell
django-admin startproject config .
python manage.py startapp core
config/settings.py에 앱 등록:
INSTALLED_APPS = [
...,
'core',
]
templates 경로 지정하기templates/ 폴더 생성 settings.py에 다음과 같이 지정:TEMPLATES = [
{
...
'DIRS': [BASE_DIR / 'templates'],
...
},
]
static 경로 지정하기static/ 폴더 생성 settings.py에 다음과 같이 지정:STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
media 경로 지정하기media/ 폴더 생성 settings.py에 다음과 같이 지정:MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
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)
# 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 | 날짜/시간 정보 |
| BooleanField | True/False |
| ForeignKey | 다른 모델과 연결 |
| ImageField | 이미지 업로드 |
모델을 데이터베이스에 반영하는 과정
python manage.py makemigrations
python manage.py migrate
Django의 템플릿 언어는 Jinja2와 매우 유사합니다.
{{ 변수명 }} <!-- 출력 -->
{% if 조건문 %} ... {% endif %} <!-- 조건문 -->
{% for item in list %} ... {% endfor %} <!-- 반복문 -->
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 %}
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
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'),
]
지금은 아무리 보고 또 봐도 익숙해지지 않지만 언젠가는 익숙해지는 날이 올거라 믿어요...