Django-mysite만들기3 방명록 추가,삭제 기능

|

django mini project

cafe24신입사원 교육과정 - django 수업 내용 정리

강사님github


전체 코드 보기


[1] application geustbook 추가

Terminal -> python manage.py startapp guestbook

[2] settings.py app 추가

INSTALLED_APPS = [
    ...
    'guestbook',
    ...
]

[3] Model 정의

guestbook/models.py

from django.db import models

# Create your models here.
class Guestbook(models.Model):
    name = models.CharField(max_length=20)
    password = models.CharField(max_length=32)
    contents = models.TextField()
    reg_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f'Guestbook({self.name}, {self.password}. {self.contents}, {self.reg_date}'

admin.py

from django.contrib import admin

# Register your models here.
from geustbook.models import Guestbook

admin.site.register(Guestbook)

[4] migrate

python manage.py makemigrations

python manage.py migrate

[5] 방명록 기능 추가하기

urls.py 매핑 추가

from django.contrib import admin
from django.urls import path
import guestbook.views as guestbook_views

urlpatterns = [
    ...
    path('guestbook/list', guestbook_views.list),
    path('guestbook/write', guestbook_views.write),
    path('guestbook/deleteform/<int:id>', guestbook_views.deleteform),
    path('guestbook/delete', guestbook_views.delete),
	...
]

views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render

# Create your views here.
from guestbook.models import Guestbook


def list(request):
    guestbooklist = Guestbook.objects.all().order_by('-reg_date')
    data = {'guestbooklist': guestbooklist}
    return render(request, 'guestbook/list.html', data)

def write(request):
    guestbook = Guestbook()
    guestbook.name = request.POST['name']
    guestbook.password = request.POST['password']
    guestbook.contents = request.POST['contents']
    guestbook.save()

    return HttpResponseRedirect('list')

def deleteform(request, id=0):
    return render(request, 'guestbook/deleteform.html', {'id':id})

def delete(request):
    id = request.POST['no']
    password = request.POST['password']

    guestbook = Guestbook.objects.filter(id=id)
    if guestbook[0].password == password:
        guestbook.delete()

    return HttpResponseRedirect('list')

templates/guestbook/deleteform.html

deleteform.html 코드 보기

templates/guestbook/list.html

list.html 코드 보기

[6] Test

views

[장고 템플릿 기능 참고!]

1, 노란색 네모의 list index 처리를 위해서

<td>forloop.revcounter</td> 코드를 이용해, 돌고있는 loop의 count를 reverse해서 넣어주었다.

2, 초록색 네모의 날짜 데이터의 형식은

guestbook.reg_date|date:'Y-m-d H:i' 로 포맷 처리하였다.

3, 파란색 네모의 \n 처리는

guestbook.contents|linebreaks 로 처리하였다.

장고 템플릿 기능 참조

Django-mysite만들기2 회원가입 기능 추가

|

django mini project

cafe24신입사원 교육과정 - django 수업 내용 정리

강사님github


전체 코드 보기



[1] application user 추가

Terminal -> python manage.py startapp user

[2] settings.py app 추가

INSTALLED_APPS = [
    ...
    'user',
    ...
]

[3] Model 정의

user/models.py

from django.db import models

# Create your models here.
class User(models.Model):
    name = models.CharField(max_length=20)
    email = models.CharField(max_length=200)
    password = models.CharField(max_length=32)
    gender = models.CharField(max_length=10)
    joindate = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f'User({self.name}, {self.email}, {self.password}. {self.gender}, {self.joindate}'

admi.py

from django.contrib import admin

# Register your models here.
from user.models import User

admin.site.register(User)

[4] migrate

python manage.py makemigrations

python manage.py migrate

DBeaver 확인

views

[5] 회원가입 기능 추가하기

urls.py 매핑 추가

path('user/joinform', user_views.joinform),
path('user/join', user_views.join),

path variable을 받을 때는

urls.py

path('user/join/<int:id>/<str:user_id>', helloworld_views.hello2),

views.py

def hello2(request, id=0, user_id=''):
 return HttpResponse(f'id:{id}, user_id:{user_id}')
views

이런식으로 받으면 된다.

views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render
from user.models import User

def joinform(request):
    return render(request, 'user/joinform.html')

def joinsuccess(request):
    return render(request, 'user/joinsuccess.html')

def join(request):
    user = User()
    user.name = request.POST['name']
    user.email = request.POST['email']
    user.password = request.POST['password']
    user.gender = request.POST['gender']
    user.save()

    return HttpResponseRedirect('user/joinsuccess')

templates/base.html

views

templates/user/joinform.html

views

templates/user/joinsuccess.html

views

[6] Test

views

성공!

views

DB 확인

views

Django-mysite만들기1 DB 생성 및 기본 main페이지

|

django mini project

cafe24신입사원 교육과정 - django 수업 내용 정리

강사님github


전체 코드 보기



[1] db 만들기

database는 postgresql사용

linux를 이용해 posgresql 데이터 베이스 생성하기!

psql -U postgres

create database pysite;

create user pysite with password 'pysite';

권한 설정 : grant all privileges on all tables in schema public to pysite;

views
linux 화면

postgresql 종료 : \q

파일수정 -> ip추가

vi /cafe24/pgsql/data/pg_hba.conf

# "local" is for Unix domain socket connections only
local   pysite   pysite     password
...
# IPv4 local connections:
host    pysite   pysite          127.0.0.1/32        password
...
host    pysite   pysite          192.168.1.0/24      password
...

데모 restart

/etc/init.d/postgres stop

/etc/init.d/postgres start

DBeaver통해서 conntect 확인하기

views
connect 성공

[2] 가상환경에 장고 설치

pycharm을 이용하면,

프로젝트 생성시 자동으로 venv 가상환경을 만들어주며,

프로젝트를 open하면 자동으로 venv 가상환경이 실행된다.

terminal -> pip install django

[3] django start project

terminal -> django-admin startproject pysite

[4] 디렉토리 정리

views

[5] psycopg2 설치

terminal -> pip install psycopg2

[6] settings 설정

TIME_ZONE = 'Asia/Seoul'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'pysite',
        'USER': 'pysite',
        'PASSWORD': 'pysite',
        'HOST': '192.168.1.52',
        'PORT': 5432,
    }
}
TEMPLATES = [
    {
        ...
		'DIRS': [os.path.join(BASE_DIR, 'templates')],
        ...
    }
]

[7] migrate

terminal -> python manage.py migrate

[8] 관리 계정 생성

terminal -> python manage.py createsuperuser

[9] 서버실행(작업확인)

terminal -> python manage.py runserver 0.0.0.0:8888

[10] main app 만들기

terminal -> python manage.py startapp main

[11] settings -> main app 추가

INSTALLED_APPS = [
    'main',
    ...
]

[12] templates dir 추가

views

index.html

<!DOCTYPE html>
<html>
<head>
<title>mysite</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<link href="/assets/css/main.css" rel="stylesheet" type="text/css">
</head>
<body>
	<div id="container">
		<div id="header">
			<h1>MySite</h1>
			<ul>
				<li><a href="">로그인</a><li>
				<li><a href="">회원가입</a><li>
				<li><a href="">회원정보수정</a><li>
				<li><a href="">로그아웃</a><li>
				<li>님 안녕하세요 ^^;</li>
			</ul>
		</div>
		<div id="wrapper">
			<div id="content">
				<div id="site-introduction">
					<img id="profile" src="https://scontent-icn1-1.xx.fbcdn.net/v/t1.0-1/p240x240/30705531_2083087868372808_5261052926483232647_n.jpg?_nc_cat=0&oh=db97a9950eade94d765d2b566ff92fbc&oe=5BE17354">
					<h2>안녕하세요. 이정은의  mysite에 오신 것을 환영합니다.</h2>
					<p>
						이 사이트는  웹 프로그램밍 실습과제 예제 사이트입니다.<br>
						메뉴는  사이트 소개, 방명록, 게시판이 있구요. Python 수업 + 데이터베이스 수업 + 웹프로그래밍 수업 배운 거 있는거 없는 거 다 합쳐서
						만들어 놓은 사이트 입니다.<br><br>
						<a href="#">방명록</a>에 글 남기기<br>
					</p>
				</div>
			</div>
		</div>
		<div id="navigation">
			<ul>
				<li><a href="">이정은</a></li>
				<li><a href="">방명록</a></li>
				<li><a href="">게시판</a></li>
			</ul>
		</div>
		<div id="footer">
			<p>(c)opyright 2015, 2016, 2017, 2018, 2019</p>
		</div>
	</div>
</body>
</html>

[13] urls.py 매핑 추가

pysite/urls.py

import main.views as main_views

urlpatterns = [
    path('', main_views.index)
    path('admin/', admin.site.urls),
]

[14] views.py 코드 추가

main/views.py

from django.shortcuts import render

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

[15] settings.py + STATIC 디렉토리 설정

미리 준비해놓은 자료를statics/ 넣어줬다.

STATICFILES_DIRS=(os.path.join(BASE_DIR, 'statics'),)
STATIC_URL = '/assets/'

static 디렉토리 추가

views


[16] 템플릿 확장 - block 설정

페이지마다 달라지는 코드들을 분리해서 block으로 만든다.

base.html

views

index.html

views

main 페이지 완성!

views

[17] DB Schema 정의

1561348145033

Django - orm(insert, select) 실습

|

전체 코드 보기


지난 포스팅에 이어서, 오늘은 기능 추가 작업


[1] html form data 받아오기

templates/emaillist/form.html 데이터를 받는 방법

<form action="/emaillist/add" method="">
    First name: <input type="text" name="fn" value="" ><br>
    Last name: <input type="text" name="ln" value=""><br>
    Email address: <input type="text" name="email" value=""><br>
    <input type="submit" value="submit">
</form>

위와 같은 form이 있다면

action의 /emaillist/add을 먼저 urls.py에 매핑을 설정한다.

python_ch3/urls.py

urlpatterns = [
    ...
    path('emaillist/add', emaillist_views.add),
	...
]

urls.py에서 설정한 url을 매핑할 add함수 정의

emaillist/views.py

아래의 코드와 같이 html의 input name값으로 데이터를 받을 수 있다.

def add(request):
    firstname = request.POST['fn']
    lastname = request.POST['ln']
    email = request.POST['email']

    return HttpResponse(f'{firstname}:{lastname}:{email}')

HttpResponse()는 text를 그대로 화면에 출력해주는 기능


CSRF verification failed. Request aborted Error!

403 Forbidden

views
CSRF verification failed

CSRF란?

장고의 기능 중 post데이터를 받을 때 CSRF보안코드가 포함되어 있지 않으면,

Error페이지를 출력


[해결] 장고에서 CSRF 처리하기

해당 form 뒤에

views

코드를 추가해주면 된다.

<form action="/emaillist/add" method="post">
    <!-- 여기에 추가 -->
    First name: <input type="text" name="fn" value="" ><br>
    Last name: <input type="text" name="ln" value=""><br>
    Email address: <input type="text" name="email" value=""><br>
    <input type="submit" value="submit">
</form>

위의 코드로 처리하면 form이 있는 page에 hidden으로 CSRF데이터가 생긴다.

views

이 처리는 상당히 보안에 취약하다.

해당 페이지의 html을 파싱해서 페이지의 csrfmiddlewaretoken값의 value를 가져와 form data와 함께 전송하면, 여전히 공격을 받기 쉬운 처리이다.

이는 장고를 좀 더 공부한 뒤, 좀 더 보안적으로 처리해보도록 하자

일단 토큰 처리를 마쳤으니, 다시 접근

views

성공!



[2] 받은 data, DB에 insert하기

emaillist/views.py

from emaillist.models import Emaillist
from django.http import HttpResponseRedirect

def add(request):
    emaillist = Emaillist()
    emaillist.first_name = request.POST['fn']
	emaillist.last_name = request.POST['ln']
    emaillist.email = request.POST['email']
    emaillist.save()

    # insert 후에는 꼭 redirect 처리!
    return HttpResponseRedirect('/emaillist')

http://localhost:8888/emaillist/form에서 submit을 한 뒤

DBeaver에서 확인해보기

views

성공!



[3] DB data select 가져오기

sample data를 몇 개 넣어보고 확인해보자!

emaillist/views.py

index에서 모든 데이터를 select해와서 list보여주기!

def index(request):
    emaillist = Emaillist.objects.all().order_by('-id')
    # for email in emaillist:
    #     print(email)
    data = {'emaillist':emaillist}
    return render(request, 'emaillist/index.html', data)

emaillist를 출력해보면 튜플 형태로 나오는 것을 확인 할 수 있다.

Emaillist(이, 바보, babo@naver.com)
Emaillist(김, 둘리, dooly@gmail.com)
Emaillist(Lee, JungEun, leeap1004@gmail.com)

이를 dict 타입으로 묶어서 render에 같이 보내주면 html에서 받을 수 있다.

templates/emaillist/index.html 수정

template tag을 이용해 보여주기

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>메일 리스트에 가입되었습니다.</h1>
	<p>입력한 정보 내역입니다.</p>
	<!-- 메일정보 리스트 -->
	
	<br>
	<p>
		<a href="/emaillist/form">추가메일 등록</a>
	</p>
	<br>
</body>
</html>
views

Django - Application 추가 작업

|

전체 코드 보기


지난 포스팅에 이어, Application 추가 작업하기

Application 기본 작업 순서

기본적으로 장고 프로젝트 한 개당 한 개의 DB를 사용한다.
Application 작업 순서
	1. 어플리케이션 추가
        [터미널]
        python manage.py startapp 앱이름
        
	2. 어플리커이션 등록 (settings.py)
        INSTALLED_APPS = [
               '앱이름',
                ...,
        ]
        
   	3. template
        |--- 앱이름
        어플리케이션 template 디렉토리 생성
    	
   	4-1. Model 정의 (db:postgresql 사용)
   	4-2. admin.py에 모듈 추가
   	4-3. migrations 이름의 DDL python 모듈 생성
   	4-4. 물리DB와 스키마 동기화 작업
   	
   	5. urls.py에서 url-view의 handler 매핑
   	
   	6. views.py에서 핸들러 함수 구현(요청처리, 모델작업)
   	
   	7. 화면이 필요한 경우, 해당 template 작업


1. emaillist app 추가

터미널에서 manage.py 명령어를 이용해 Application 추가!

[terminal] - python manage.py startapp emaillist

2. python settings.py APP 추가

INSTALLED_APPS = [
    'emaillist',
    'helloworld',
    'django.contrib.admin',
    ...
]

3. emaillist template 디렉토리 추가

해당 디렉토리 하위에 html 파일들을 추가 할 예정

views

4-1. 모델 정의

emaillist/models.py

모든 Model은 models.Model을 상속받아야 한다.

from django.db import models

class Emaillist(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=100)
    email = models.CharField(max_length=200)

    def __str__(self):
        return f'Emaillist({self.first_name}, {self.last_name}, {self.email})'

4-2. admin.py에 모듈 추가

emaillist/admin.py

from django.contrib import admin
from emaillist.models import Emaillist

admin.site.register(Emaillist)

/admin 사이트에서 모델 관리가 가능해지는 기능!

views

4-3. migrations 이름의 DDL python 모듈 생성

terminal : python manage.py makemigrations

(venv) D:\dowork\PycharmProjects\python_ch3>python manage.py makemigrations

Migrations for 'emaillist':
  emaillist\migrations\0001_initial.py
    - Create model Emaillist

emaillist/migrations/ 디렉토리 밑에 DDL 정보가 담겨있는 파일이 생성된다.

4-4. 물리DB와 스키마 동기화 작업

terminal : python manage.py migrate

(venv) D:\dowork\PycharmProjects\python_ch3>python manage.py migrate

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, emaillist, sessions
Running migrations:
  Applying emaillist.0001_initial... OK

DBeaver를 통해 데이터 베이스 확인해보기

views

application이름_table이름

5. urls.py에서 url-view의 handler 매핑등록

python_ch3/urls.py

import emaillist.views as emaillist_views
import helloworld.views as helloworld_views

urlpatterns = [
    path('emaillist/', emaillist_views.index),
    path('emaillist/form', emaillist_views.form),

    path('helloworld/', helloworld_views.hello),

    path('admin/', admin.site.urls),
]

6. views.py에서 핸들러 함수 구현

emaillist/views.py

from django.shortcuts import render

def index(request):
    return render(request, 'emaillist/index.html')

def form(request):
    return render(request, 'emaillist/form.html')

7. 해당 template 작업

views

index.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>메일 리스트에 가입되었습니다.</h1>
	<p>입력한 정보 내역입니다.</p>
	<!-- 메일정보 리스트 -->
	<table border="1" cellpadding="5" cellspacing="2">
		<tr>
			<td align=right>First name: </td>
			<td></td>
		</tr>
		<tr>
			<td align=right width="110">Last name: </td>
			<td width="110">정은</td>
		</tr>
		<tr>
			<td align=right>Email address: </td>
			<td>leeap1004@gmail.com</td>
		</tr>
	</table>
	<br>
	<p>
		<a href="/emaillist/form">추가메일 등록</a>
	</p>
	<br>
</body>
</html>

form.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>메일 리스트 가입</h1>
	<p>
		메일 리스트에 가입하려면,<br>
		아래 항목을 기입하고 submit 버튼을 클릭하세요.
	</p>
	<form action="" method="">
	    First name: <input type="text" name="fn" value="" ><br>
	    Last name: <input type="text" name="ln" value=""><br>
	    Email address: <input type="text" name="email" value=""><br>
	    <input type="submit" value="submit">
	</form>
	<br>
	<p>
		<a href="/emaillist">리스트 바로가기</a>
	</p>
</body>
</html>

8. server띄워서 확인

terminal : python manage.py runserver 0.0.0.0:8888

views
views