본문 바로가기

SK네트웍스 Family AI캠프 10기/Daily 회고

73일차. Django

더보기

 

73일 차 회고.

 

 .

 

 

 

 

1. Django

 

 

1-1. Multi App

 

가상환경 생성

uv venv .venv -p 3.13
.\.venv\Scripts\activate

uv pip install -r .\requirements.txt
# requirements.txt

django

 

Django 프로젝트 생성

django-admin startproject config .

 

Django 앱 생성 - user

python manage.py startapp user

 

templates 생성

mkdir templates
mkdir .\templates\user

 

static 설정

mkdir static
mkdir .\static\css
mkdir .\static\js

 

코드 작성

  • STATIC
/* static/css/index.css */

p {
    color: lightseagreen;
}
// static/js/index.js

alert("Hello, World!");
  • TEMPLATE
<!--templates/user/index.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>
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/index.css' %}">
</head>
<body>
    <h1>Welcome to the User Page</h1>
    <p>This is the user page content.</p>
    {% load static %}
    <script src="{% static 'js/index.js' %}"></script>
</body>
</html>
  • VIEW
# user/view.py

from django.shortcuts import render

def index(request):
    return render(request, 'user/index.html')
  • URL RESOLUTION
# user/urls.py

from django.urls import path
from .views import index

urlpatterns = [
    path('index/', index, name='user-index'),
]
# config/urls.py

from django.urls import path, include

urlpatterns = [
    path('user/', include('user.urls')),
]
  • SETTING
import os						# 추가
from pathlib import Path

...

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'user',						# 추가
]

...

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],				# 추가
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

...

# DATABASES = {						# 주석 처리
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': BASE_DIR / 'db.sqlite3',
#     }
# }

...

STATIC_URL = 'static/'
STATIC_PATH = os.path.join(BASE_DIR, 'static')		# 추가
STATICFILES_DIRS = (STATIC_PATH,)			# 추가

 

서버 실행

python manage.py runserver

 

Django 앱 생성 - todolist

python manage.py startapp todolist

 

templates 생성

mkdir .\templates\todolist

 

코드 작성

  • TEMPLATE
<!--templates/todolist/index.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>
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/index.css' %}">
</head>
<body>
    <h1>Welcome to the Template Page</h1>
    <p>This is the template page content.</p>
    {% load static %}
    <script src="{% static 'js/index.js' %}"></script>
</body>
</html>
  • VIEW
# todolist/views.py

from django.shortcuts import render

def index(request):
    return render(request, 'todolist/index.html')
  • URL RESOLUTION
# todolist/urls.py

from django.urls import path
from .views import index

urlpatterns = [
    path('', index, name='todolist-index'),
]
# config/urls.py

from django.urls import path, include

urlpatterns = [
    path('', include('todolist.urls')),			# 추가
    path('user/', include('user.urls')),
]
  • SETTING
# config/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'todolist',						# 추가
    'user',
]

 

서버 실행

python manage.py runserver

 

데이터 전달 - user

# user/views.py

from django.shortcuts import render

def index(request):
    context = {
        'name': 'Django',
        'age': 3,
        'hobby': 'coding',
    }
    return render(request, 'user/index.html', context)
<!--templates/user/index.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>
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/index.css' %}">
</head>
<body>
    <h1>Welcome to the User Page</h1>
    <p>This is the user page content.</p>
    <!--------------------추가-------------------->
    <br>
    <p><b>Name</b>: {{name}}</p>
    <p><b>Age</b>: {{age}}</p>
    <p><b>Hobby</b></p>
    <ul type="circle">
        {% for item in hobby %}
            <li>{{item}}</li>
        {% endfor %}
    </ul>
    <!-------------------------------------------->
    {% load static %}
    <script src="{% static 'js/index.js' %}"></script>
</body>
</html>

 

서버 실행

python manage.py runserver

 

도메인 이름 바꾸기

  • hosts 파일은 메모장의 관리자 권한으로 수정한다.
# C:\Windows\System32\drivers\etc\hosts

# localhost name resolution is handled within DNS itself.
#	127.0.0.1       localhost
127.0.0.1	www.localhost.com			# 추가
#	::1             localhost
# config/settings.py

ALLOWED_HOSTS = ["www.localhost.com"]			# 추가
  • 설정한 도메인으로 접속이 안된다면, 컴퓨터를 다시 시작한다.

 

파일 구조

MULTI_APP/
├─ .env
├─ config/
│  ├─ __init__.py
│  ├─ asgi.py
│  ├─ settings.py
│  ├─ urls.py
│  └─ wsgi.py
├─ static/
│  ├─ css/
│  │  └─ index.css
│  └─ js/
│     └─ index.js
├─ templates/
│  ├─ todolist/
│  │  └─ index.html
│  └─ user/
│     └─ index.html
├─ todolist/
│  ├─ migrations/
│  │  └─ __init__.py
│  ├─ __init__.py
│  ├─ admin.py
│  ├─ apps.py
│  ├─ models.py
│  ├─ tests.py
│  ├─ urls.py
│  └─ views.py
├─ user/
│  ├─ migrations/
│  │  └─ __init__.py
│  ├─ __init__.py
│  ├─ admin.py
│  ├─ apps.py
│  ├─ models.py
│  ├─ tests.py
│  ├─ urls.py
│  └─ views.py
├─ manage.py
└─ requirements.txt

 

1-2. Admin

 

가상환경 생성

uv venv .venv -p 3.13
.\.venv\Scripts\activate

uv pip install -r .\requirements.txt
# requirements.txt

django

 

Django 프로젝트 생성

django-admin startproject config .

 

서버 실행

  • 데이터베이스 마이그레이션
python manage.py makemigrations
python manage.py migrate
  • 서버 실행
python manage.py runserver

 

SQLite

  • Extension 설치

  • Open Database
>SQLite: Open Database

 

Superuser 생성

  • Superuser 생성 후, auth_user 테이블에서 확인할 수 있다.
python manage.py createsuperuser

 

서버 실행

python manage.py runserver

 

Django 앱 생성

python manage.py startapp todolist
# config/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'todolist',						# 추가
]

 

Models(스키마) 생성

# todolist/models.py

from django.db import models
from django.contrib.auth.models import User

class TodoList(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    item = models.CharField(max_length=100)
    status = models.BooleanField(default=False)
    created_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.item
# todolist/admin.py

from django.contrib import admin
from .models import TodoList

admin.site.register(TodoList)

 

서버 실행

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

 

파일 구조

ADMIN/
├─ .venv/
├─ config/
│  ├─ __init__.py
│  ├─ asgi.py
│  ├─ settings.py
│  ├─ urls.py
│  └─ wsgi.py
├─ todolist/
│  ├─ migrations/
│  │  ├─ __init__.py
│  │  └─ 0001_initial.py
│  ├─ __init__.py
│  ├─ admin.py
│  ├─ apps.py
│  ├─ models.py
│  ├─ tests.py
│  └─ views.py
├─ db.sqlite3
├─ manage.py
└─ requirements.txt

 

 

1-3. MySQL

 

가상환경 생성

uv venv .venv -p 3.13
.\.venv\Scripts\activate

uv pip install -r .\requirements.txt
# requirements.txt

django

 

Django 프로젝트 생성

django-admin startproject config .

 

Django 앱 생성 - user

python manage.py startapp user

 

templates 생성

mkdir templates
mkdir .\templates\user

 

코드 작성

  • TEMPLATE
<!--templates/user/login.html-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Page</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/index.css' %}">
</head>
<body>
    <h1>Login</h1>
    {% load static %}
    <script src="{% static 'js/index.js' %}"></script>
</body>
</html>
<!--templates/user/register.html-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registration Page</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/index.css' %}">
</head>
<body>
    <h1>Register</h1>
    {% load static %}
    <script src="{% static 'js/index.js' %}"></script>
</body>
</html>
  • VIEW
# user/views.py

from django.shortcuts import render

def login(request):
    return render(request, 'user/login.html')

def register(request):
    return render(request, 'user/register.html')
  • URL RESOLUTION
# user/urls.py

from django.urls import path
from .views import login, register

urlpatterns = [
    path('login/', login, name='user-login'),
    path('register/', register, name='user-register'),
]

 

Django 앱 생성 - todolist

python manage.py startapp todolist

 

templates 생성

mkdir .\templates\todolist

 

코드 작성

  • TEMPLATE
<!--templates/todolist/todolist.html-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Todo List Page</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/index.css' %}">
</head>
<body>
    <h1>Todo List</h1>
    {% load static %}
    <script src="{% static 'js/index.js' %}"></script>
</body>
</html>
  • VIEW
# todolist/views.py

from django.shortcuts import render

def todolist(request):
    return render(request, 'todolist/todolist.html')
  • URL RESOLUTION
# todolist/urls.py

from django.urls import path
from .views import todolist, todo

urlpatterns = [
    path('', todolist, name='todolist-todolist'),
]
# config/urls.py

from django.urls import path, include

urlpatterns = [
    path('user/', include('user.urls')),
    path('', include('todolist.urls')),
]
  • SETTING
# config/settings

import os
from pathlib import Path

...

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'user',
    'todolist',
]

...

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

...

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': BASE_DIR / 'db.sqlite3',
#     }
# }

...

STATIC_URL = 'static/'
STATIC_PATH = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (STATIC_PATH,)

 

서버 실행

python manage.py runserver

 

MySQL

  • Image & Container 생성
# docker-compose.yml

version: "3"

services:
    db-mysql:
        image: mysql
        restart: always
        command:
            - --character-set-server=utf8mb4
            - --collation-server=utf8mb4_unicode_ci
        volumes:
            - ./database/mysql:/var/lib/mysql
        environment:
            MYSQL_ROOT_PASSWORD: 
            MYSQL_DATABASE: django_db
            MYSQL_USER: 
            MYSQL_PASSWORD: 
        ports:
            - "3306:3306"
docker-compose up -d
  • 드라이버 설치
# requirements.txt

django
mysqlclient
uv pip install -r .\requirements.txt
  • MySQL 연결
# config/settings.py

...

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_db',
        'USER': '',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

...
python manage.py makemigrations
python manage.py migrate

 

Models(스키마) 생성

# todolist/models.py

from django.db import models

class Todo(models.Model):
    item = models.CharField(max_length=100)
    status = models.BooleanField(default=False)

    def __str__(self):
        return self.todo_name
python manage.py makemigrations
python manage.py migrate

 

코드 작성

# todolist/views.py

from django.shortcuts import render
from django.contrib import messages
from .models import TodoList

def todolist(request):
    if request.method == 'POST':
        task = request.POST.get('task').strip()
        
        todo = TodoList.objects.filter(item=task).exists()
        if todo:
            messages.error(request, 'Task already exists!')
        elif not len(task):
            messages.error(request, 'Please enter a task.')
        else:
            new_task = TodoList(item=task)
            new_task.save()

    todo_list = TodoList.objects.all()
    context = {
        'todo_list': todo_list,
    }
    return render(request, 'todolist/todolist.html', context)
<!--templates/todolist/todolist.html-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Todo List Page</title>
    <script src="//d.bablic.com/snippet/6288d4c3c4c5800001a91242.js?version=3.9"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
    <h1 class="fs-1 p-2">Todo List</h1>
    <section class="vh-100" style="background-color: #eee;">
        <div class="container py-5 h-100">
            <div class="row d-flex justify-content-center align-items-center h-100">
            <div class="col col-lg-9 col-xl-7">
                <div class="card rounded-3">
                <div class="card-body p-4">
                    {% if messages %}
                    {% for message in messages %}
                        <h4 style="color: #b22222;">{{message}}</h4>
                    {% endfor %}
                    {% endif %}

                    <h4 class="text-center my-3 pb-3">Todo List</h4>
                    <form method="POST" class="row row-cols-lg-auto g-3 justify-content-center align-items-center mb-4 pb-2">
                    {% csrf_token %}
                        <div class="col-12">
                            <div class="form-outline">
                            <input type="text" id="form1" class="form-control" name="task" placeholder="Enter a task here"/>
                            </div>
                        </div>

                        <div class="col-12">
                            <button type="submit" class="btn btn-primary">Add Task</button>
                        </div>
                    </form>
                    <table class="table mb-4">
                        <thead>
                            <tr>
                            <th scope="col">Todo Item</th>
                            <th scope="col">Status</th>
                            <th scope="col">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for i in todo_list %}
                            <tr>
                            <td>{{i.item}}</td>

                            {% if i.status == True %}
                                <td>Completed</td>
                            {% else %}
                                <td>In progress</td>
                            {% endif %}

                            <td>
                                <a href=""><button type="submit" class="btn btn-success ms-1">Finished</button></a>
                                <a href=""><button type="submit" class="btn btn-danger">Delete</button></a>
                            </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                </div>
            </div>
            </div>
        </div>
    </section>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>
</body>
</html>
SHOW DATABASES;
SHOW TABLES;

INSERT todolist_todolist(item, status) VALUES ("Python 공부하기", True);
INSERT todolist_todolist(item, status) VALUES ("MySQL 공부하기", True);
INSERT todolist_todolist(item, status) VALUES ("Django 공부하기", False);

SELECT * FROM todolist_todolist

 

 

'SK네트웍스 Family AI캠프 10기 > Daily 회고' 카테고리의 다른 글

75일차. Django  (0) 2025.04.28
74일차. Django  (0) 2025.04.25
72일차. JavaScript & Django  (0) 2025.04.23
71일차. JavaScript  (0) 2025.04.22
70일차. HTML & CSS  (0) 2025.04.21