본문 바로가기
Programming/Making django Web Page

django로 내 웹페이지 만들기(6) - MySQL 과 연동

by 지혜를 탐구하는 오딘 2022. 6. 7.
728x90
반응형

MySQL과 연동해봅시다.

 

DB 커넥터 설치

pip install mysqlclient

 

settings.py 수정

기본값은 sqlite 로 되어 있을 것이다. sqlite 내용은 삭제하자.

DATABASES = {
    'default' : {
        'ENGINE' : 'django.db.backends.mysql',      # Set Database Engine
        'NAME' : 'odin_web_db',        # MySQL Database Name
        'USER' : 'odinodinodin',		# MySQL Username
        'PASSWORD' : 'pa$$w0RdP@ssw0rd',	# Password
        'HOST' : '192.168.111.111',		# Database Server IP
        'PORT' : '3306',		# Database Server Port Number
    }
}

settings.py 코드 보기👇

더보기
"""
Django settings for wednesday1304 project.

Generated by 'django-admin startproject' using Django 4.0.3.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-5qg83)-u4_ov^nac8#u80xb4p*4amsg@g&c-xtp77cg=7ca&vz'
##################################################################################
# Probably Important for something above a line


# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

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

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'wednesday1304.urls'

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

WSGI_APPLICATION = 'wednesday1304.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default' : {
        'ENGINE' : 'django.db.backends.mysql',      # Set Database Engine
        'NAME' : 'odin_web_db',        # MySQL Database Name
        'USER' : 'odinodinodin',		# MySQL Username
        'PASSWORD' : 'pa$$w0RdP@ssw0rd',	# Password
        'HOST' : '192.168.111.111',		# Database Server IP
        'PORT' : '3306',		# Database Server Port Number
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'ko-kr'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

STATICFILES_DIRS = [
    BASE_DIR / 'static'
]

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

 

 

DB 감지를 위해서 아래 명령어를 실행하자

python manage.py inspectdb

DB를 감지하면 위와 같이 결과가 나온다. 

제일 위 주석문에 설명이 있다. 자세히 잘 읽어보자. (내가 정리를 해놓으면 사람이 안 읽을테니, 정리 안 함!)

 

 

그리고 from django.~~~~ 부터의 내용을 복사해서 models.py 파일을 만들어 입력하자.

 models.py 코드 보기👇

더보기
from django.db import models

class SkillTable(models.Model):
    num = models.AutoField(db_column='NUM', primary_key=True)  # Field name made lowercase.
    type_idx = models.ForeignKey('PlatformTable', models.DO_NOTHING, db_column='TYPE_idx', blank=True, null=True)  # Field name made lowercase.
    skill_name = models.CharField(db_column='SKILL_NAME', max_length=255)  # Field name made lowercase.
    created_at = models.DateTimeField(db_column='Created_At', blank=True, null=True)  # Field name made lowercase.

    class Meta:
        managed = False
        db_table = 'SKILL_TABLE'


class BbsTable(models.Model):
    bbs_idx = models.AutoField(primary_key=True)
    skill_idx = models.ForeignKey(SkillTable, models.DO_NOTHING, db_column='skill_idx', blank=True, null=True)
    bbs_title = models.CharField(max_length=255)
    bbs_content = models.TextField(blank=True, null=True)
    wroteat = models.DateTimeField(db_column='wroteAt')  # Field name made lowercase.
    modifiedat = models.DateTimeField(db_column='modifiedAt', blank=True, null=True)  # Field name made lowercase.
    pwd = models.CharField(db_column='PWD', max_length=255)  # Field name made lowercase.

    class Meta:
        managed = False
        db_table = 'bbs_table'


class FileTable(models.Model):
    file_idx = models.AutoField(primary_key=True)
    bbs_idx = models.ForeignKey(BbsTable, models.DO_NOTHING, db_column='bbs_idx', blank=True, null=True)
    file_path = models.TextField(blank=True, null=True)
    file_name = models.TextField(blank=True, null=True)
    file_type = models.TextField(blank=True, null=True)
    file_size = models.TextField(blank=True, null=True)
    createdat = models.DateTimeField(db_column='CreatedAt', blank=True, null=True)  # Field name made lowercase.

    class Meta:
        managed = False
        db_table = 'file_table'


class PlatformTable(models.Model):
    num = models.AutoField(db_column='NUM', primary_key=True)  # Field name made lowercase.
    type = models.CharField(db_column='TYPE', max_length=45)  # Field name made lowercase.

    class Meta:
        managed = False
        db_table = 'platform_TABLE'

 

DB에 변화가 있다면, make migrations 를 해주자. 아래 명령어를 Terminal, PowerShell 에서 입력하자.

python manage.py makemigrations ; python manage.py migrates

 

views.py 에서 코드를 추가하자

from django.shortcuts import render
from .models import PlatformTable

def index(request):
	context = { 'title' : "Odin's Website" }
	platforms = PlatformTable.objects.values()		# DB 에서 값 가져오기 type : QuerySet
	context.update({ "platforms" : platforms })		# dict 타입으로 context에 추가

	return render(request, 'wednesday1304/index.html', context)

views.py 코드 보기👇

더보기
from django.shortcuts import render
from .models import PlatformTable

# Create your views here.
def index(request):
    context = add_fixed_data()
    context.update({ 'title' : "Odin's Website" })

    platforms = PlatformTable.objects.values()

    context.update({ "platforms" : platforms })

    return render(request, 'wednesday1304/index.html', context)



def timeline(request):
    context = add_fixed_data()
    context.update({ 'title' : "Odin's Timeline" })

    return render(request, 'wednesday1304/pages/timeline.html', context)


def works(request):
    context = add_fixed_data()
    context.update({ 'title' : 'What ODIN Did' })

    return render(request, 'wednesday1304/pages/works.html', context)


def contact(request):
    context = add_fixed_data()
    context.update({'title' : 'CONTACT to ODIN' })

    return render(request, 'wednesday1304/pages/contact.html', context)



def add_fixed_data():
    fixed_data = { 'odin' : 'Odin'
                , 'odinTitle' : "About Odin"
                , 'timeline' : 'Timeline'
                , 'timelineTitle' : "See Odin's Timeline"
                , 'works' : 'Works'
                , 'worksTitle' : "See What Odin done"
                , 'contact' : 'Contact'
                , 'contactTitle' : "Contact Odin"
                , 'Odin_Word' : "미미르샘"
                , 'copyright' : '© Copryright 2022 All Rights Reserved'
                , 'web_title' : "Odin's Web"
                , 'Privacy_Policy' : 'Privacy Policy'
            }

    return fixed_data

 

 

 html 파일, template 에 for문으로 내용을 추가하자.

SECTION!!
{% for platform in platforms %}
    <p>{{ platform.num }}</p>
    <p>{{ platform.type }}</p>
{% endfor %}

index.html 코드 보기👇

더보기

 

<!--
-- File    : index.html
-- Date    : 2022. 05. 31
-- Author  : Odin
-- Last Update : 2022. 05. 31
-- Description:
--     index.html
-->
{% load static %}


<!DOCTYPE html>
<html lang="ko">
<head>
    {% include "includes/common_head.html" %}


</head>
<body>



    {% include 'includes/header.html' %}


    {% include 'includes/nav.html' %}



    <div class="wrapper">
        <main>
            <section>
                SECTION!!
                {% for platform in platforms %}
                    <p>{{ platform.num }}</p>
                    <p>{{ platform.type }}</p>
                {% endfor %}
            </section>

            <article>
                article
            </article>
        </main>

        <aside>
            aside
        </aside>

    </div>




    {% include 'includes/footer.html' %}

</body>
</html>


{% include 'includes/static_js.html' %}

 

 

결과 보기

결과가 잘 나온다! 디자인은....싫다!

 

 

 

 

 

 

 

 

728x90
반응형

댓글