Python - Django를 사용하여 DB 불러오기 예제





오늘은 Python을 활용하여 SQL DB를 표 형식으로 불러오는 예제를 리뷰합니다. JAVA랑 비슷하지만 많이 다릅니다. 

Django 설치 및 연동은 아래의 글을 참조해주세요.
Django 프로젝트 생성 및 세팅 : http://note.espriter.net/1275





dj_ex7_crud

** settings.py **
아래에서 my_sangpum 추가

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

** urls.py **
urlpatterns에서 경로 추가

"""dj_ex7_crud URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from my_sangpum import views
import my_sangpum
from django.urls.conf import include

urlpatterns = [
    path('admin/', admin.site.urls),
    
    path('', views.Main),
    path('sangpum/', include('my_sangpum.urls')),
    
    ]




my_sangpum

** 0001_initial **
# Generated by Django 2.0.5 on 2018-05-14 06:07

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='SangTab',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('code', models.CharField(max_length=20)),
                ('sang', models.CharField(max_length=30)),
                ('su', models.IntegerField()),
                ('dan', models.IntegerField()),
            ],
        ),
    ]

** admin.py **
from django.contrib import admin
from my_sangpum.models import SangTab

# Register your models here.
class SangTabAdmin(admin.ModelAdmin):
    list_display = ('id','sang','su','dan')
    
admin.site.register(SangTab, SangTabAdmin)


**models.py **
from django.db import models

# Create your models here.
class SangTab(models.Model):
    code = models.CharField(max_length=20)
    sang = models.CharField(max_length=30)
    su = models.IntegerField()
    dan = models.IntegerField()

** urls.py **
from django.urls import path
from my_sangpum import views

urlpatterns = [
    path('list', views.ListFunc),
    path('insert', views.InsertFunc),
    path('insertok', views.InsertFuncOk),
    path('update', views.UpdateFunc),
    path('updateok', views.UpdateFuncOk),
    path('delete', views.DeleteFunc),
    
]

** views.py **
from django.shortcuts import render
from my_sangpum.models import SangTab
from _mysql import connection
from django.http.response import HttpResponseRedirect

# Create your views here.
def Main(request):
    return render(request, 'main.html')

def ListFunc(request):
    datas = SangTab.objects.all()
    return render(request, 'list.html', {'sangpums':datas})
    ''' (데이터 받을 때 튜플로 받아야 됨)
    sql = "select * from my_sangpum_sangtab"
    cursor = connection.cursor()
    cursor.execute(sql)
    datas = cursor.fetchall()
    return render(request, 'list.htlm', {'sangpums':datas})
    '''

def InsertFunc(request):
    return render(request, 'insert.html')

def InsertFuncOk(request):
    if request.method == 'POST':
        SangTab(
            code = request.POST.get('code'),
            sang = request.POST.get('sang'),
            su = request.POST.get('su'),
            dan = request.POST.get('dan'),
        ).save()
    return HttpResponseRedirect('/sangpum/list') #추가 후 목록보기

def UpdateFunc(request):
    #print(request.GET.get('id'))
    data = SangTab.objects.get(id=request.GET.get('id'))
    #print(data)
    return render(request, 'update.html', {'sang_one': data})

def UpdateFuncOk(request):
    if request.method == 'POST':
        upRec = SangTab.objects.get(id=request.POST.get('id'))
        upRec.code = request.POST.get('code')
        upRec.sang = request.POST.get('sang')
        upRec.su = request.POST.get('su')
        upRec.dan = request.POST.get('dan')
        upRec.save()
    return HttpResponseRedirect('/sangpum/list') #추가 후 목록보기

def DeleteFunc(request):
    delRec = SangTab.objects.get(id=request.GET.get('id'))
    delRec.delete()
    return HttpResponseRedirect('/sangpum/list') #추가 후 목록보기



templates

** insert.html **
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function chkData() {
    //alert("aa");
    if(frm.code.value == "" ||
        frm.sang.value == "" ||
        frm.su.value == "" ||
        frm.dan.value == ""){
        alert("입력자료를 모두 채우시오");
        return;
    }
    frm.submit();
}

</script>
</head>
<body>
<h2>자료 입력</h2>
<form name="frm" action="/sangpum/insertok" method="post">{% csrf_token%}
<table border="1">
    <tr><td>코드 : </td><td><input type="text" name="code"></td></tr>
    <tr><td>품명 : </td><td><input type="text" name="sang"></td></tr>
    <tr><td>수량 : </td><td><input type="text" name="su"></td></tr>
    <tr><td>단가 : </td><td><input type="text" name="dan"></td></tr>
    <tr>
     <td colspan="2" style="text-align:center;">
     <input type="button" value="저장" onclick="chkData()">
     </td>
    </tr>
</table>
</form>
</body>
</html>

** list.html **
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>* 상품 목록 *</h2>
<a href="/sangpum/insert?id={{s.id}}">상품 추가</a>
<table border="1">
<tr>
    <th>id</th><th>코드</th><th>상품</th><th>수량</th><th>단가</th>
    <th>변경</th>
</tr>
{% if sangpums %}
{% for s in sangpums %}
<tr>
    <td>{{s.id}}</td>
    <td>{{s.code}}</td>
    <td>{{s.sang}}</td>
    <td>{{s.su}}</td>
    <td>{{s.dan}}</td>
    <td>
        <a href="/sangpum/update?id={{s.id}}">수정</a> /
        <a href="/sangpum/delete?id={{s.id}}">삭제</a>
    </td>
</tr>
{% endfor %}
{% else %}
    <tr><td colspan="5"> 자료가 없음 </td></tr>
{% endif %}
</table>
</body>
</html>

** main.html **
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Main<p/>
<a href="sangpum/list">상품목록</a>
</body>
</html>

** update.html **
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function chkData() {
    //alert("aa");
    if(frm.code.value == "" ||
        frm.sang.value == "" ||
        frm.su.value == "" ||
        frm.dan.value == ""){
        alert("입력자료를 모두 채우시오");
        return;
    }
    frm.submit();
}

</script>
</head>
<body>
<h2>* 자료 수정 * </h2>
<form name="frm" action="/sangpum/updateok" method="post">{% csrf_token %}
<input type="hidden" name="id" value="{{sang_one.id}}">
<table border="1">
    <tr>
        <td>코드 : </td>
        <td><input type="text" name="code" value="{{sang_one.code}}"></td>
    </tr>
    <tr>
        <td>품명 : </td>
        <td><input type="text" name="sang" value="{{sang_one.sang}}"></td>
    </tr>
    <tr>
        <td>수량 : </td>
        <td><input type="text" name="su" value="{{sang_one.su}}"></td>
    </tr>        
    <tr>
        <td>단가 : </td>
        <td><input type="text" name="dan" value="{{sang_one.dan}}"></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="button" value="수정하기" onclick="chkData()">
            <input type="button" value="수정취소" onclick="history.back()">
    </tr>    
</table>
</form>
</body>
</html>




결과 이미지 및 파일





본 포스팅은 KIC 캠퍼스에서 박영권 강사의 지도하에 공부하며 작성한 리포트입니다.
혹시 잘못된 내용이 있거나 문제 소지시 댓글 남겨주시면 조치하겠습니다.







댓글(0)

Designed by JB FACTORY