관리 메뉴

거니의 velog

231109_Django 과제 1 본문

대덕인재개발원_파이썬 프로그래밍

231109_Django 과제 1

Unlimited00 2023. 11. 9. 17:24


[HELLO_DJ_MEM.settings]

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

[HELLO_DJ_MEM.daoMem]

import pymysql # PyMySQL-1.1.0

class DaoMem:
    def __init__(self):
        print("생성자")
        self.conn = pymysql.connect(host='127.0.0.1', port=3305, user='root', password='python', db='python', charset='utf8') # 접속 정보
        self.cur = self.conn.cursor(pymysql.cursors.DictCursor)
    
    def selectList(self):
        sql = "select * from member"
        self.cur.execute(sql)
        
        lists = self.cur.fetchall()
        return lists
    
    def selectOne(self, m_id):
        sql = f"""
            select * from member 
            where m_id = '{m_id}'
        """
        self.cur.execute(sql)
        
        vo = self.cur.fetchone()
        return vo
    
    def insert(self, m_id, m_name, tel, email):
        sql = f"""
            INSERT INTO member (m_id, m_name, tel, email) 
                 VALUES ('{m_id}', '{m_name}', '{tel}', '{email}')
        """
        cnt = self.cur.execute(sql)
        self.conn.commit()
        return cnt
    
    def update(self, m_id, m_name, tel, email):
        sql = f"""
            UPDATE member SET 
                m_name = '{m_name}'
                , tel = '{tel}'
                , email = '{email}'
                WHERE m_id = '{m_id}'
        """
        cnt = self.cur.execute(sql)
        self.conn.commit()
        return cnt
    
    def delete(self, m_id):
        sql = f"""
            DELETE FROM member 
            WHERE m_id = '{m_id}'
        """
        cnt = self.cur.execute(sql)
        self.conn.commit()
        return cnt
        
    # 소멸자 : destroyer
    def __del__(self):
        print("소멸자")
        self.cur.close()
        self.conn.close()
        
if __name__ == '__main__':
    dm = DaoMem()
    
    list = dm.selectList()
    print(list)
    
    vo = dm.selectOne('10')
    print(vo)
    
    # cnt = dm.insert('10', '10', '1', '10')
    # print(cnt)
    
    # cnt = dm.update('10', '이순신', '010-1234-1234', '대전시 서구')
    # print(cnt)
    
    # cnt = dm.delete('10')
    # print(cnt)

[HELLO_DJ_MEM.views]

from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
import pymysql # PyMySQL-1.1.0
from HELLO_DJ_MEM.daoMem import DaoMem


def mem_list(request):
    de = DaoMem()
    list = de.selectList()
    print(list)
    
    data = {
        'list' : list
    }
    
    return render(request, "mem_list.html", data)

def mem_detail(request):
    m_id = request.GET['m_id']
    
    de = DaoMem()
    vo = de.selectOne(m_id)
    
    data = {
        'vo' : vo
    }
    
    return render(request, "mem_detail.html", data)

def mem_mod(request):
    m_id = request.GET['m_id']
    
    de = DaoMem()
    vo = de.selectOne(m_id)
    
    data = {
        'vo' : vo
    }
    
    return render(request, "mem_mod.html", data)

def mem_mod_act(request):
    m_id = request.POST['m_id']
    m_name = request.POST['m_name']
    tel = request.POST['tel']
    email = request.POST['email']
    
    de = DaoMem()
    modCnt = de.update(m_id, m_name, tel, email)
    
    data = {
        'modCnt' : modCnt
    }
    
    return render(request, "mem_mod_act.html", data)
    
def mem_del_act(request):
    m_id = request.POST['m_id']
    
    de = DaoMem()
    delCnt = de.delete(m_id)
    
    data = {
        'delCnt' : delCnt
    }
    
    return render(request, "mem_del_act.html", data)

def mem_add(request):
    return render(request, "mem_add.html")

def mem_add_act(request):
    m_id = request.POST['m_id']
    m_name = request.POST['m_name']
    tel = request.POST['tel']
    email = request.POST['email']
    
    de = DaoMem()
    insCnt = de.insert(m_id, m_name, tel, email)
    
    data = {
        'insCnt' : insCnt
    }
    
    return render(request, "mem_add_act.html", data)

[HELLO_DJ_MEM.urls]

"""
URL configuration for HELLO_DJ_MEM project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
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 HELLO_DJ_MEM import views

urlpatterns = [
    path('', views.mem_list),
    path('mem_list', views.mem_list),
    path('mem_detail', views.mem_detail),
    path('mem_mod', views.mem_mod),
    path('mem_mod_act', views.mem_mod_act),
    path('mem_del_act', views.mem_del_act),
    path('mem_add', views.mem_add),
    path('mem_add_act', views.mem_add_act),
]

[mem_list.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>MEM_LIST</title>
		<script type="text/javascript">
			function fn_add(){
				location.href = "mem_add";
			}
		</script>
	</head>
	<body>
		<h1>MEM_LIST</h1>
		<table border="1" style="width: 100%;">
			<colgroup>
				<col width="25%" />
				<col width="25%" />
				<col width="25%" />
				<col width="25%" />
			</colgroup>
			<tr>
				<th>멤버번호</th>
				<th>이름</th>
				<th>전화번호</th>
				<th>이메일</th>
			</tr>
			{% for listObj in list %}
				<tr>
					<td><a href="mem_detail?m_id={{listObj.m_id}}">{{listObj.m_id}}</a></td>
					<td>{{listObj.m_name}}</td>
					<td>{{listObj.tel}}</td>
					<td>{{listObj.email}}</td>
				</tr>
			{% endfor %}
			<tr>
				<td colspan="4">
					<!-- <a href="emp_add">게시글 등록</a> -->
					<button type="button" onclick="fn_add()">멤버 추가</button>
				</td>
			</tr>
		</table>
	</body>
</html>

[mem_add.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>MEM_ADD</title>
		<script type="text/javascript">
			function fn_add_act() {
				document.frm_add.submit();
			}
		</script>
	</head>
	<body>
		<h1>MEM_ADD</h1>
		
		<form name="frm_add" action="mem_add_act" method="post">
			{% csrf_token %}
			<table border="1" style="width: 100%;">
				<colgroup>
					<col width="30%" />
					<col width="70%" />
				</colgroup>
				<tr>
					<th>멤버번호</th>
					<td>
						<input type="text" name="m_id" style="width: 95%;" />
					</td>
				</tr>
				<tr>
					<th>이름</th>
					<td>
						<input type="text" name="m_name" style="width: 95%;" />
					</td>
				</tr>
				<tr>
					<th>전화번호</th>
					<td>
						<input type="text" name="tel" style="width: 95%;" />
					</td>
				</tr>
				<tr>
					<th>이메일</th>
					<td>
						<input type="text" name="email" style="width: 95%;" />
					</td>
				</tr>
				<tr>
					<td colspan="2">
						<button type="button" onclick="fn_add_act()">저장</button>
						<a href="mem_list">뒤로가기</a>
					</td>
				</tr>
			</table>
		</form>
	</body>
</html>

[mem_add_act.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>EMP_ADD_ACT</title>
	</head>
	<body>
		<script type="text/javascript">
			var cnt = "{{ insCnt }}";
			
			if(cnt == "1") {
				alert("정상적으로 멤버가 등록되었습니다.");
				location.href = "mem_list";
			}else {
				alert("멤버 등록에 실패했습니다.");
				history.back();
			}
		</script>
	</body>
</html>

[mem_detail.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>MEM_DETAIL</title>
		<script type="text/javascript">
			function fn_mod(){
				//console.log("fn_mod");
				location.href = "mem_mod?m_id={{vo.m_id}}";
			}
			function fn_del(){
				//console.log("fn_mod");
				location.href = "mem_del_act?m_id={{vo.m_id}}";
			}
			function fn_del_act(){
				var flag = confirm("한번 지워진 데이터는 복구가 불가합니다.\n정말 삭제하시겠습니까?");
				if(!flag){
					return;
				}
				document.frmDel.submit();
			}
		</script>
	</head>
	<body>
		<h1>MEM_DETAIL</h1>
		<table border="1" style="width: 100%;">
			<colgroup>
				<col width="30%" />
				<col width="70%" />
			</colgroup>
			<tr>
				<th>멤버번호</th>
				<td>{{ vo.m_id }}</td>
			</tr>
			<tr>
				<th>이름</th>
				<td>{{ vo.m_name }}</td>
			</tr>
			<tr>
				<th>전화번호</th>
				<td>{{ vo.tel }}</td>
			</tr>
			<tr>
				<th>이메일</th>
				<td>{{ vo.email }}</td>
			</tr>
			<tr>
				<td colspan="2">
					<a href="mem_mod?m_id={{vo.m_id}}" onclick="fn_mod()">수정</a>
					<button type="button" onclick="fn_del_act()">삭제</button>
					<a href="mem_list">뒤로가기</a>
				</td>
			</tr>
			<form name="frmDel" action="mem_del_act" method="post">
				{% csrf_token %}
				<input type="hidden" name="m_id" value="{{vo.m_id}}" />
			</form>
		</table>
	</body>
</html>

[mem_mod.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>MEM_MOD</title>
		<script type="text/javascript">
			function fn_mod_act() {
				document.frm_mod.submit();
			}
		</script>
	</head>
	<body>
		<h1>MEM_MOD</h1>
		
		<form name="frm_mod" action="mem_mod_act" method="post">
			{% csrf_token %}
			<table border="1" style="width: 100%;">
				<colgroup>
					<col width="30%" />
					<col width="70%" />
				</colgroup>
				<tr>
					<th>멤버번호</th>
					<td>
						<input type="text" name="m_id" value="{{ vo.m_id }}" style="width: 95%;" readonly />
					</td>
				</tr>
				<tr>
					<th>전화번호</th>
					<td>
						<input type="text" name="m_name" value="{{ vo.m_name }}" style="width: 95%;" />
					</td>
				</tr>
				<tr>
					<th>이메일</th>
					<td>
						<input type="text" name="tel" value="{{ vo.tel }}" style="width: 95%;" />
					</td>
				</tr>
				<tr>
					<th>주소</th>
					<td>
						<input type="text" name="email" value="{{ vo.email }}" style="width: 95%;" />
					</td>
				</tr>
				<tr>
					<td colspan="2">
						<button type="button" onclick="fn_mod_act()">저장</button>
						<a href="mem_list">뒤로가기</a>
					</td>
				</tr>
			</table>
		</form>
	</body>
</html>

[mem_mod_act.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>EMP_MOD_ACT</title>
	</head>
	<body>
		<script type="text/javascript">
			var cnt = "{{ modCnt }}";
			
			if(cnt == "1") {
				alert("정상적으로 수정되었습니다.");
				location.href = "mem_list";
			}else {
				alert("수정에 실패했습니다.");
				history.back();
			}
		</script>
	</body>
</html>

[mem_del_act.html]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>MEM_DEL_ACT</title>
	</head>
	<body>
		<script type="text/javascript">
			var cnt = "{{ delCnt }}";
			
			if(cnt == "1") {
				alert("정상적으로 삭제되었습니다.");
				location.href = "mem_list";
			}else {
				alert("삭제에 실패했습니다.");
				history.back();
			}
		</script>
	</body>
</html>

'대덕인재개발원_파이썬 프로그래밍' 카테고리의 다른 글

231113_Django 개론 4  (0) 2023.11.13
231110_Django 개론 3  (0) 2023.11.10
231109_Django 개론 2  (0) 2023.11.09
231108_Django 개론 1  (0) 2023.11.08
231107_DB 개론 2  (0) 2023.11.07