본문 바로가기
카테고리 없음

[62일차] Django

by GWLEE 2022. 9. 26.
FrameWork        Model   View Controller
Spring            기타나머지..    Jsp.html
 /WEB-INF/view/~
@Controller
Django (MVT) Model Template View

 

https://www.jetbrains.com/ko-kr/pycharm/download/download-thanks.html?platform=windows&code=PCC 

파이참 설치

 

PyCharm을 다운로드해주셔서 감사합니다!

 

www.jetbrains.com

 


setting - Terminal에 Shell path 설정

powershell.exe -ExecutionPolicy ByPass -NoExit -Command "& 'C:\Users\BIT\miniconda3\shell\condabin\conda-hook.ps1'

현재 폴더위치에 django 프로젝트 생성한다. django admin의 start project 

board 폴더가 장고 프로젝트 폴더이다.

ls 누른 화면 

 

여기 위치에서 프로젝트 시작하는 거!

 

기본적으로 장고의 구성은 하나의 프로젝트의 다수의 웹 애플리케이션이 포함되는 구조로 이루어져있다.

웹 애플리케이션의 단위 =>

ex) 전산규모의 시스템을 만들 때 복잡하니깐 나눈다. 인사/ 판매 / 제조

 

애플리케이션의 데이터 공유,,,? X.. 하나의 애플리케이션을 만들거기때문에 공유할 필요가 없다.

 

 

board프로젝트에 속한 noticeboard는 하나의 앱으로 되어있다. 같은 레벨로 구성.

애플리케이션 단위는 비즈니스모델로 만든다.

 

 

실제 운영하는 상황이라면 False 사용자에게 모든 기능을 할 수 없기때문..

개발시엔 True로 사용한다.

디버그 True가 Allowed_host안에 있는 값을 의미한다. [ ] 여기 안에

배포시엔 디버그 false host는 지정해줘야한다.

 

모든 상태를 다 받아주는 상태를 의미한다.

 

 

장고는 디폴트로 기본적인 것을 내장하고 있다.

기본 내장 애플리케이션

noticeboard라는 앱을 추가했으니 추가해줘야한다.

 

 

클래스를 추가해준다.

장고 프로젝트 밑에 설정파일에다가 등록해주는 것

앱을 또 추가할시 등록해줘야한다.

 

https://dev.mysql.com/downloads/connector/python/

 

MySQL :: Download Connector/Python

Select Operating System: Select Operating System… Microsoft Windows Ubuntu Linux Debian Linux SUSE Linux Enterprise Server Red Hat Enterprise Linux / Oracle Linux Fedora Oracle Solaris macOS Platform Independent Source Code Select OS Version: All Windows

dev.mysql.com

예전에는 얘를 썼당

https://pypi.org/project/PyMySQL/

 

PyMySQL

Pure Python MySQL Driver

pypi.org

요즘엔 이걸 쓴당

conda install -c anaconda pymysql 

터미널에 설치해주기

 

board - settings.py에 import해주고 DB 수정해주기

 

from pathlib import Path
import pymysql

root 계정으로 데이터베이스 만들기

refresh 하고 만들어진 것을 확인한다.

 

settings.py 파일 다시 수정하기

 

pymysql 버전을 맞춰줘야해서 info를 넣어준다.

 

로컬타임 바꾸기 USE_TZ를 false로 바꾸어줘야한다.

 

장고는 무조건 ORM을 디폴트로한다.

-> mysql DB를 만들었으면, 데이터를 select해보거나 들어가있는 데이터를 업데이트하는 정도

스키마 컬럼 테이블 타입을 정하고 스키마를 건드리는 일은 장고 ORM을 사용해서 해야한다.

mysql 에서 변경 작업을 하면 불일치가되어 문제가 발생한다. 모든 변경은 장고안에서 해야한다.

회원테이블 실제 테이블로 만들어보자

모델에 대한 내용을 데이터베이스가 알아먹도록 스크립트 생성한다.

스크립트를 데이터베이스로 쏴주면 된다.

기본적인 권한테이블은 데이터베이스로 쏘기만 하면 된다.

 

 

 

장고 migrate이 mysql로 DB를 쏴준다.

 

장고 시작 

 

 

 

 

/admin 하면 나온다.

 

 

id : root 

 

admin에 슈퍼유저 로그인 후 user 정보 확인

 

models.py 를 건드리기

 

객체를 찍으면 타이틀을 정의하겠다.

관리자 페이지에서 이 페이지를 볼 수 있게 설정 admin 사이트에서 볼 수 있겠끔.

 

스크립트를 만들어보자 터미널에 친다.

 

 

DB에 반영할 스크립트를 제작하자

 

 

 

 

DB에 반영 해주자. 모델 수정할 때마다 이 작업 반복해야한다.

 

 

DB에 제대로 들어갔는지 확인해본다.id를 지정하지 않으면 장고가 알아서 id를 만들어준다.

 

다시 서버 돌리고 admin 들어가면

 

notice 가 들어간 것을 확인 한다.

 

 

board 에 urls 를 만든다.

여기에 다 때려박으면 관리하기 힘들다.

각 애플리케이션을 담당하게 하면 더 깔끔하지 않을까,,,

각 애플리케이션 쪽으로 토스시켜버리겠다.

 

noticeboard\urls를 만들고 작성해주기

views index라는 함수를 호출하겠다

 

spring의 컨트롤러가 views.py

뷰가 위치할 곳에 설정해준다.

 

 

base_dir이 boardproject를 말한다. ?? 맞는지 확인하기

 

templates 폴더 생성

 

html 파일도 생성해주기

 

 

 

index.html django 코드 

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
    <style>
    @font-face {
        font-family: 'LeeSeoyun';
        src:
            url('https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_2202-2@1.0/LeeSeoyun.woff')
            format('woff');
        font-weight: normal;
        font-style: normal;
    }

    * {
        font-family: 'LeeSeoyun';
    }

    .cls1 {
        text-decoration: none;
    }

    .cls2 {
        text-align: center;
        font-size: 30px;
        display: block;
    }

    a:hover {
        color: #153acf;
    }

    button:hover{
        background-color: #c0d9fc;
    }

    h1{
      position: relative;
      animation: mymove infinite;
      animation-duration: 3s;
      color: blue;
      animation-fill-mode: forwards;
    }

    @keyframes mymove {
      from {top: 0px;}
      to {top: 30px; color: #c0d9fc;}
    }


    /* width */
    ::-webkit-scrollbar {
        width: 25px;
    }

    /* Track */
    ::-webkit-scrollbar-track {
        box-shadow: inset 0 0 3px #c0d9fc;
        border-radius: 5px;
    }

    /* Handle */
    ::-webkit-scrollbar-thumb {
        background: #c0d9fc;;
        border-radius: 5px;
    }
    </style>
</head>
<body>
	<h1 style="text-align: center; color: blue;">글 목록</h1>
	<br><br>
	<table align="center" border="1" width="80%">
		<thead>
			<tr height="10" align="center" bgcolor="#c0d9fc">
				<th>글번호</th>
				<th>작성자</th>
				<th>제목</th>
				<th>작성일</th>
			</tr>
		<thead />
	    {% if not article_list %}
            <tbody>
            <tr height="10">
                <td colspan="4">
                    <p align="center">
                        <b><span style="font-size: 9pt;">등록된 글이 없습니다.</span></b>
                    </p>
                </td>
            </tr>
            </tbody>
        {% else %}
            <tbody>
                {% for article in article_list %}
                    <tr align="center">
					    <td width="5%">{{forloop.counter}}</td>
                        <td width="10%">{{article.writeId}}</td>
                        <td align="left" width="35%"><span
						style="padding-right: 30px"></span>
						<a class="cls1" href="">
						{{article.title}}
						</a>
						</td>
						<td width="10%">{{article.writeDate}}</td>
                    </tr>
                {% endfor %}
				</tbody>
			{% endif %}
	</table>
	<a class="cls1" href="{% url 'noticeboard:write_article' %}">
	<br><br>
        <center>
			<button>
				<span class="clas2">글쓰기</span>
            </button></center>
	</a>
	</a>
</body>
</html>

https://anaconda.org/anaconda/pymysql

 

Pymysql :: Anaconda.org

Description This package contains a pure-Python MySQL client library. The goal of PyMySQL is to be a drop-in replacement for MySQLdb and work on CPython, PyPy and IronPython.

anaconda.org

 

 

 action="${contextPath}/board/addArticle">

조금 더 세련된 방법으로 제공한다.

 

 

 

CSRF (Cross-site request forgery)

 

 

csrftoken= "flkalfkalfkl"

 

get방식이든 post방식이든

"csrfmiddlewaretoken" = "flkalfkalfkl"

 

이런 이름 넘겨줘야하는게 힘드니깐 장고에서는 한 줄로 해결할 수 있도록 해준다.

 

writeArticle

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>write</title>
    <script>
        function backToList(frm) {
            frm.action="{%url 'noticeboard:index' %}";
            frm.submit();
        }
    </script>
    <style>
        .class-caption {
            width: 100px;
        }

        .class-content {
            width: 500px;
        }

        @font-face {
            font-family: 'LeeSeoyun';
            src:
                url('https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_2202-2@1.0/LeeSeoyun.woff')
                format('woff');
            font-weight: normal;
            font-style: normal;
        }

        * {
            font-family: 'LeeSeoyun';
        }


        h1{
          position: relative;
          animation: mymove infinite;
          animation-duration: 3s;
          color: blue;
          animation-fill-mode: forwards;
        }

        @keyframes mymove {
          from {top: 0px;}
          to {top: 20px; color: blue;}
        }

        input:focus { background-color: #c0d9fc; }
        textarea:focus { background-color: #c0d9fc; }
        textarea:focus { background-color: #c0d9fc; }
    </style>
</head>
<body>
	<h1 style="text-align: center; color:#c0d9fc;">새 글 쓰기</h1>
	<form name="articleForm" method="post" action="{% url 'noticeboard:add_article' %}">
		{% csrf_token %}
		<table boarder="0" align="center">
			<tbody>
				<tr>
					<td align="right" class="class-caption">글제목:</td>
					<td colspan="2">
						<input type="text" maxlength="100" name="title" class="class-content" />
					</td>
				</tr>
				<tr>
					<td align="right" valign="top" class="class-caption"><br>글내용:</td>
					<td colspan="2">
						<textarea name="content" rows="10" maxlength="2000" class="class-content" ></textarea>
					</td>
				</tr>
				<tr>
					<td align="right"></td>
					<td colspan="2">
						<input type="submit" value="글쓰기" />
						<input type="button" value="목록보기" onclick = "backToList(articleForm)" />
					</td>
				</tr>
			</tbody>
		</table>
	</form>
</body>
</html>

 

 views

 

 

수정하기 / 삭제하기

 

 

 

 

detail.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>글보기</title>
    <style>
        #tr_btn_modify {
            display: none;
        }
        @font-face {
            font-family: 'LeeSeoyun';
            src:
                url('https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_2202-2@1.0/LeeSeoyun.woff')
                format('woff');
            font-weight: normal;
            font-style: normal;
        }

        * {
            font-family: 'LeeSeoyun';
        }

        .cls1 {
            text-decoration: none;
        }

        .cls2 {
            text-align: center;
            font-size: 30px;
            display: block;
        }

        a:hover {
            color: #153acf;
        }

        h1{
          position: relative;
          animation: mymove infinite;
          animation-duration: 3s;
          color: blue;
          animation-fill-mode: forwards;
        }

        @keyframes mymove {
          from {top: 0px;}
          to {top: 20px; color: blue;}
        }
        button:hover{
            background-color: #c0d9fc;
        }
    </style>
    <script type="text/javascript">
        function backToList(frm) {
            frm.action="{%url 'noticeboard:index' %}";
            frm.submit();
        }

        function fn_enable() {
            document.querySelector("#i_title").disabled = false;
            document.querySelector("#i_content").disabled = false;
            document.querySelector("#tr_btn_modify").style.display = "table-row";
            document.querySelector("#tr_btn").style.display = "none";
        }

        function fn_modify_article(frm) {
            frm.action = "{% url 'noticeboard:update' article.id %}";
            frm.submit();
        }

        function fn_remove_article(frm) {
            frm.action = "{% url 'noticeboard:delete' article.id %}";
            frm.submit();
        }

    </script>
</head>
<body>
<h1 style="text-align: center; color:#c0d9fc;">새 글쓰기</h1>
	<form name="frmArticle" method="post" action="">
		{% csrf_token %}
			<table border="0" align="center">
				<tbody>
					<tr>
						<td width="150" align="center" bgcolor="#c0d9fc">글번호</td>
						<td><input name="articleNo" type="text"
								   value="{{article.id}}" disabled /> </td>
					</tr>
					<tr>
						<td width="150" align="center" bgcolor="#c0d9fc">작성자ID</td>
						<td><input name="writer" type="text"
							value="{{article.writeId}}" disabled /></td>
					</tr>
					<tr>
						<td width="150" align="center" bgcolor="#c0d9fc">제목</td>
						<td><input name="title" type="text" value="{{article.title}}"
							id="i_title" disabled /></td>
					</tr>
					<tr>
						<td width="150" align="center" bgcolor="#c0d9fc">내용</td>
						<td><textarea name="content" rows="20" cols="60"
								id="i_content" disabled>{{article.contents}}</textarea></td>
					</tr>
					<tr>
						<td width="20%" align="center" bgcolor="#c0d9fc">등록일자</td>
						<td><input type="text" value="{{article.writeDate}}" disabled />
						</td>
					</tr>
					<tr id="tr_btn_modify">
						<td colspan="2" align="center"><input type="button"
							value="수정반영하기" onclick="fn_modify_article(frmArticle)" /> <input
							type="button" value="취소" onclick="backToList(frmArticle)" /></td>
					</tr>
					<tr id="tr_btn">
						<td colspan="2" align="center">
							<input type="button" value="수정하기" onclick="fn_enable()" />
							<input type="button" value="삭제하기" onclick="fn_remove_article(frmArticle)" />
							<!-- <input type="button" value="삭제하기" onclick="fn_remove_article(frmArticle)" />  -->
							<input type="button" value="리스트로 돌아가기" onclick="backToList(frmArticle)" />
						</td>
					</tr>
				</tbody>
			</table>
		</form>
	</body>
</html>

수정하기

삭제하기 

 

https://stackoverflow.com/questions/62416617/add-csrf-in-fetch-js-for-django

 

Add CSRF in Fetch JS for Django

I have the following JS code in my django template: fetch("http://127.0.0.1:8000/api/endpoint", { method: "POST", body: $("#form").serializeArray(), }).then(function(data) { })...

stackoverflow.com

body : {
   // Other stuff
   csrfmiddlewaretoken: '{{ csrf_token }}'
}

댓글