클라이언트 라이브러리 설치
pip install mysqlclient
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '[DB 이름]',
'USER': '[DB 접속 ID]',
'PASSWORD': '[DB 접속 PW]',
'HOST': '[DB 서버 IP주소]',
'PORT': '[DB 서버 포트번호]',
'OPTIONS': {
'init_command': 'SET sql_mode="STRICT_TRANS_TABLES"'
}
}
}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': BASE_DIR / 'web',
'USER' : 'root',
'PASSWORD' : 'qwer1234',
'HOST' : '192.168.xx.xx',
'PORT' : '3306',
'OPTIONS' : {'init_command' : 'SET sql_mode="STRICT_TRANS_TALBES"'}
}
}
ORM : Object Relational Mapping
models.py
from django.db import models
# Create your models here.
class Fruits(models.Model):
name = models.CharField(max_length=50)
descript = models.TextField()
price = models.FloatField()
quantity = models.IntegerField()
cdate = models.DateTimeField(auto_now_add=True)
def __str__(self):
return 'id : {},name : {},description : {}'.format(self.id ,self.name, self.descript)
DB 생성 (Database 컴퓨터에서)
Terminal에서 migrate하기
python manage.py makemigrations [App 이름]
python .\manage.py migrate
views.py
from django.shortcuts import render
# Create your views here.
from product.models import Fruits
def createFruitGet(request): # 입력 페이지 띄워주는 함수
return render(request, 'product/create.html')
def createFruitPost(request): # db에 과일 정보 데이터 저장
fruit = Fruits()
fruit.name = request.POST.get('fname',None)
fruit.descript = request.POST.get('fdescript',None)
fruit.price = request.POST.get('fprice',None)
fruit.quantity = request.POST.get('fquantity',None)
fruit.save() # DB에 저장시켜줌
return render(request, 'product/createResult.html')
def readFruitGet(request): # 읽기
fruits = Fruits.objects.all() # Fruits 모델의 모든 객체들 불러옴
context = {
'fruits' : fruits
}
return render(request, 'product/read.html', context)
html 파일 생성
create.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action = 'createPost' method="post">
{% csrf_token %}
<input type="text" name="fname" />
<input type="text" name="fdescript" />
<input type="text" name="fprice" />
<input type="text" name="fquantity" />
<button></button>
</form>
</body>
</html>
createResult.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
잘 보내졌어요.
</body>
</html>
read.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for fruit in fruits%}
{{ fruit.name }}
{{ fruit.price }} <br/>
{% endfor %}
</body>
</html>
urls.py
from django.contrib import admin
from django.urls import path
import board.views
import product.views
urlpatterns = [
path('admin/', admin.site.urls),
path('',board.views.mainPage),
path('product/create',product.views.createFruitGet),
path('product/createPost',product.views.createFruitPost),
path('product/list',product.views.readFruitGet),
]