11. Ajax

12. Ajax + DB

13. Join

 


11. Ajax

 : ajax 송부한 데이터에 문자열 더하여 수신 받기.

 : ajax 요청하여 수신 받은 데이터 출력하기.

 

 = django_test10_ajax

 * settings

INSTALLED_APPS = [
    
    ...
    
    'myajaxapp',
]

 => application 연결

 

 * urls

from django.contrib import admin
from django.urls import path
from myajaxapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.indexFunc),
    path('startajax', views.func1),
    path('goajax', views.func2),
]

 => url -> function 연결

     url '' -> indexFunc

     url 'startajax' -> func1

     url 'goajax' -> func2

 

 

 * views

from django.shortcuts import render
import json
from django.http.response import HttpResponse

lan = {
    'id':111,
    'name':'파이썬',
    'history':[
        {'date':'2021-2-12','exam':'basic'},
        {'date':'2021-2-22','exam':'django'},
    ]
}

def test(): # json encoding/decoding
    print(type(lan)) # dict
    jsonString  = json.dumps(lan)
    jsonString  = json.dumps(lan, indent = 4) # 들어쓰기
    print(jsonString)
    #{"id": 111, "name": "\ud30c\uc774\uc36c", 
    #"history": [{"date": "2021-2-12", "exam": "basic"}, {"date": "2021-2-22", "exam": "django"}]}
    print(type(jsonString)) # str
    
    print('----------------------------------------------------------')
    
    dic = json.loads(jsonString)
    print(dic)
    print(type(dic)) # dict
    print(dic['name'])
    for h in dic['history']:
        print(h['date'], h['exam'])
    #2021-2-12 basic
    #2021-2-22 django
    
def indexFunc(request):
    test()
    return render(request,'abc.html')
	
    ...

 => import jason

 => json.dumps(data, indent = 들여쓰기) : json encoding. python object(Dict, List, Tuple..)를 문자열로 변경하는 작업

 => json.loads(data) : json decoding. 문자열을 python object(Dict, List, Tuple..)로 변경하는 작업

 => indexFunc() -> abc.html

 

 * abc.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	$("#btn1").click(function(){
		let msg = $("#txtMsg").val()
		$("#showData").empty();
		$.ajax({
			url:'startajax',
			type:'get',
			data:{'msg':msg}, /* msg=msg */
			dataType:'json',
			success:function(data){
				let str = '';
				for(let k in data){
					let str = k + '<br>' + data[k];
				}
				str += "<br><b>"+data['key']+"</b>";
				$("#showData").html(str);
			},
			error:function(){
				$("#showData").text("에러");
			}
		});
	});
	
	$("#btn2").click(function(){
		//$("#showData2").text("<i>1</i>"); // <i> 그대로 출력
		$("#showData2").html("<i>1</i>");
		$.ajax({
			url:'goajax',
			type:'get',
			dataType:'json',
			success:function(data){
				//alert(data);
				let str = '';
				$.each(data, function(ind, entry){ //jquery 반복문
					str += entry['name'] + ', ' + entry['age'] + '<br>';
				});
				$("#showData2").html(str);
			},
			error:function(){
				$("#showData2").text("에러");
			}
		});
	});
});
</script>
</head>
<body>
<h2>Ajax test</h2>
자료입력 : <input type="text" id="txtMsg" value="홍길동">
<button id="btn1">버튼1 클릭</button>
<br>
<div id="showData">실습결과1</div>
<hr>
<button id="btn2">버튼2 클릭</button>
<br>
<div id="showData2">실습결과2</div>
</body>
</html>

$.ajax({

    url:'요청명',

    type:'get/post',

    dataType:'json',

    success:function(x){

        // 성공 시 실행문

    }

    error:function(){

        // 에러 발생 시 실행문

    }

});

=> ajax 처리

 

$.each(x, function(idx, entry){

    // for entry in x: 과 동일

    // 반복문

});

 => json 반복문

 * views

...

import time
def func1(request):
    msg = request.GET['msg']
    #print(msg) # 홍길동
    time.sleep(1);
    context = {'key':msg + ' ajax 요청 처리'} # dict - 홍길동 ajax 요청 처리
    return HttpResponse(json.dumps(context), content_type="application/json") # dict -> str

def func2(request):
    datas = [
        {'name' : '고길동', 'age':25},
        {'name' : '김길동', 'age':27},
        {'name' : '나길동', 'age':28},
    ]
    return HttpResponse(json.dumps(datas), content_type="application/json")

 => request.GET['msg'] : 요청의 'msg' key의 값을 get.

 => HttpResponse(json.dumps(context), content_type="application/json") : context를 dict 타입에서 str로 변환 후

       json형식의 str을 send.


12. Ajax + DB

 : ajax 요청 시 DB의 직원 테이블 data 조회하여 출력하기.

 

 = django_test11_ajax

 => create application - myajax

 

 * settings

...

INSTALLED_APPS = [
    
    ...
    
    'myajax',
]

...

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'test',                # DB명 : db는 미리 작성되어 있어야 함.       
        'USER': 'root',                # 계정명 
        'PASSWORD': '123',             # 계정 암호           
        'HOST': '127.0.0.1',           # DB가 설치된 컴의 ip          
        'PORT': '3306',                # DBMS의 port 번호     
    }
}

...

 => application 연결.

 => DB 설정

 

 

 * anaconda prompt

cd C:\work\psou\django_test11_ajax
python manage.py inspectdb > aaa.py

 

 

 * models

from django.db import models

# Create your models here.
class Sangdata(models.Model):
    code = models.IntegerField(primary_key=True)
    sang = models.CharField(max_length=20, blank=True, null=True)
    su = models.IntegerField(blank=True, null=True)
    dan = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'sangdata'

 => aaa.py의 사용할 table을 models.py에 복사 붙여넣기. (제작된 Table을 Django 형식으로 자동 생성)

 

 Make migrations - myajax

 Migrate

 

 

 * urls

from django.contrib import admin
from django.urls import path
from myajax import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.MainFunc),
    path('list', views.ListFunc),
    path('calldb', views.ListDbFunc),
]

 => url -> function 연결.

 => url '' -> MainFunc()

 => url 'list' -> ListFunc()

 => url 'calldb' -> ListDbFunc()

 

 

 * views

from django.shortcuts import render
from myajax.models import Sangdata
from django.http.response import HttpResponse
import json

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

def ListFunc(request):
    return render(request, 'list.html')

def ListDbFunc(request):
    sdata = Sangdata.objects.all() # db sangdata 전체 읽기
    datas = []
    for s in sdata:
        #print(s.code)
        dict ={'code':s.code, 'sang':s.sang, 'su':s.su,'dan':s.dan}
        datas.append(dict)
    #print(datas)
    #[{'code': 1, 'sang': '장갑', 'su': 3, 'dan': 10000},
    # {'code': 2, 'sang': '벙어리장갑', 'su': 2, 'dan': 12000},
    # {'code': 3, 'sang': '가죽장갑', 'su': 10, 'dan': 50000}, 
    # {'code': 4, 'sang': '가죽점퍼', 'su': 5, 'dan': 650000}, 
    # {'code': 6, 'sang': '신상', 'su': 11, 'dan': 3000}, 
    # {'code': 7, 'sang': '아메리카노', 'su': 2, 'dan': 1}, 
    # {'code': 8, 'sang': '가방', 'su': 22, 'dan': 300}]
    return HttpResponse(json.dumps(datas), content_type='application/json')

 => MainFunc() -> main.html

 => ListFunc() -> list.html

 => ListDbFunc() : db data 읽은 후 json data send.(dict -> list -> str로 변환)

 

 

 * main.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>메인</h2>
<a href="/list">상품 보기</a>
</body>
</html>

 

 * list.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.js"></script>

<script type="text/javascript">
$(document).ready(function(){
	$("#btnOk").click(function(){
		$("#showData").empty();
		
		$.ajax({
			url:'calldb',
			type:'get',
			dataType:'json',
			success:function(data){
				//alert(data);
				let str = "<table border='1'>";
				str += "<tr><th>코드</th><th>상품명</th><th>수량</th><th>단가</th></tr>";
				let count = 0;
				$.each(data, function(ind, entry){
					str += "<tr>";
					str += "<td>" + entry['code'] + "</td>";
					str += "<td>" + entry['sang'] + "</td>";
					str += "<td>" + entry['su'] + "</td>";
					str += "<td>" + entry['dan'] + "</td>";
					str += "</tr>";
					count += 1;
				});
				
				str += "</table>";
				$("#showData").append(str);
				$("#showData").append("건수 : "+count);
			},
			errorLfunction(){
				$("#showData").text("로딩 실패");
			}
		});
	});
});
</script>

</head>
<body>
<h2>상품 목록</h2>
<button id="btnOk">상품자료 출력(Ajax)</button><br><br>
<div id="showData"></div>
<hr>
</body>
</html>

 => button click 시 ajax로 'calldb' 요청명 send 후 성공 시 table 형태로 조회된 DB 데이터 출력.


13. Join

 * views

SearchJikwonFunc(request):
    jikwon_jik = request.GET["jikwon_jik"]
    jikwonList = Jikwon.objects.extra(select={'buser_name':'buser_name'}, tables=['Buser'],
    where =['Buser.buser_no=Jikwon.buser_num']).filter(jikwon_jik = jikwon_jik)
    data = []
    for j in jikwonList:
        dict ={}
        dict['jikwon_no'] = j.jikwon_no
        dict['jikwon_name'] = j.jikwon_name
        dict['buser_name'] = j.buser_name
        data.append(dict)
    print(data)
    return HttpResponse(json.dumps(data), content_type = "application/json")

5. sqlite

6. where, group by

7. 원격 DB

8. DB - ForeignKey

9. DB - CRUD, 페이징

10. 게시판


5. sqlite

: 장고의 ORM(Object Relational Mapping) 사용하여 내장 함수로 DB의 DML, DDL .. 등을 실행.

 

 = django_test04_sqlite

 * settings

INSTALLED_APPS = [
	...
    'sqlapp',
]

 

 * url

from django.contrib import admin
from django.urls import path
from sqlapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.Main),
    path('show/', views.DbTestFunc),
]

path('admin/', admin.site.urls) : admin 요청명 admin.py와 연결

 

 * models : db table 작성

from django.db import models

# Create your models here.
# ORM
# 논리적인 테이블 설정
class Article(models.Model):
    code = models.CharField(max_length=10)
    name = models.CharField(max_length=20)
    price = models.IntegerField()
    pub_date = models.DateTimeField()

class 테이블명(models.Model) : 테이블 생성

column명 = models.CharField(maxlength= ) : 문자타입 칼럼 생성.

column명 = models.IntegerField() : 숫자타입 칼럼 생성.

column명 = models.DateTimeField() : 날짜타입 칼럼 생성.

 

explore 창 - 프로젝트 오른쪽 클릭 - Django - Make Migrations - sqlapp

explore 창 - 프로젝트 오른쪽 클릭 - Django - Migrate

 

 

 * admin계정 id 생성
 - anconda prompt 창 실행

cd C:\work\psou\django_test04_sqlite
python manage.py createsuperuser
=> id / e-mail / password 설정

 - http://127.0.0.1/admin/ 접속 후 login

 - table data 입력

 

 

 * admin

from django.contrib import admin
from sqlapp.models import Article

# Register your models here.
class ArticleAdmin(admin.ModelAdmin):
    list_display = ('id', 'code', 'name', 'price', 'pub_date')

admin.site.register(Article, ArticleAdmin)

class 클래스명(admin.ModelAdmin):

     list_display = ('칼럼명1', ... )

admin.site.register(테이블명, 클래스명)

 => 테이블과 admin계정 연결

 

 

 * views

from django.shortcuts import render
from sqlapp.models import Article

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

def DbTestFunc(request):
    datas = Article.objects.all() # 장고의 ORM. select * from Article 이 내부적으로 수행. list 타입으로 리턴.
    #print(datas) # <QuerySet [<Article: Article object (1)>, <Article: Article object (2)>, <Article: Article object (3)>]>
    #print(datas[0].name) # 아아
    return render(request, 'list.html',{'articles':datas}) # QuerySet을 전달.

models.py의 클래스명.objects.all() : select * from 테이블명(클래스명)

 

 

 * main.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>메인</h2>
<a href="show/">자료 보기</a>
</body>
</html>

 

 * list.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>


Article 자료 보기 - Djang template language 사용 <br>
{% if articles.count %}
	{% for a in articles %}
		<b>{{a.code}}</b> {{a.name}} {{a.price}} {{a.pub_date}}<br>
	{% endfor %}
{% else %}
	<p>자료가 없습니다.</p>
{% endif %}
</body>
</html>

{% if 조건 %}

{% else %}

{% endif %}

=> if 문

 

{% for 변수 in 자료 %}

{% endfor %}

=> for 문

 

6. where, group by

 * settings

INSTALLED_APPS = [
    ...
    'sql_app',
]

 => application연결

 

 

 * models

from django.db import models

# Create your models here.
class Profile(models.Model):
    name = models.CharField(max_length = 10)
    age = models.IntegerField()
    

 => DB 테이블 생성

 

 - explore 창 - 프로젝트 오른쪽 클릭 - Django - Create application - sqlapp

 - explore 창 - 프로젝트 오른쪽 클릭 - Django - Make Migrations - sqlapp

 - explore 창 - 프로젝트 오른쪽 클릭 - Django - Migrate

 

해당 프로젝트 cmd 창 : python manage.py createsuperuser 

 

 * admin

from django.contrib import admin
from sql_app.models import Profile

# Register your models here.
class ProfileAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'age')

admin.site.register(Profile, ProfileAdmin)

 => 테이블과 admin 계정 연결.

 

 - http://127.0.0.1/admin/ 접속 후 login

 - table data 입력

 

 

 * urls

from django.contrib import admin
from django.urls import path
from sql_app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.IndexFunc),
    path('calldata/', views.CallFunc),
]

 => url과 views 연결

 

 

 * views

from django.shortcuts import render
from sql_app.models import Profile
from django.db.models.aggregates import Avg, Count, Max, Min, Sum

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

def CallFunc(request):
    profile_list = Profile.objects.all() # 전체 자료 list로 리턴
    
    for row in profile_list.values_list(): # 리스트의 값들 리턴
        print(row)
        
    print(Profile.objects.aggregate(Avg('age')))  # select avg(age) from Profile
    print(Profile.objects.aggregate(Max('age')))
    print(Profile.objects.aggregate(Sum('age')))
    print(Profile.objects.aggregate(Count('age')))
    print(len(profile_list))
    print(Profile.objects.filter(name = '홍길동').aggregate(Avg('age'))) # where 조건
    qs = Profile.objects.values('name').annotate(Avg('age')) # group 별 작업
    
    for r in qs:
        print(r)
        
    pro_list = []
    
    for pro in profile_list:
        pro_dict ={}
        pro_dict['name'] = pro.name
        pro_dict['age'] = pro.age
        pro_list.append(pro_dict)
        print(pro_list)
        # [{'key1':value1, 'key2':value2, ... }, {'key1':value1, 'key2':value2, ... }, ... ]
    
    context = {'pro_list':pro_list}
        
    return render(request, 'list.html', context)

QuerySet 타입.values_list() : value list 리턴

테이블명.objects.aggregate(Avg('칼럼명')) : select avg(칼럼명) from 테이블명

테이블명.objects.aggregate(Max('칼럼명')) : select max(칼럼명) from 테이블명

테이블명.objects.aggregate(Sum('칼럼명')) : select sum(칼럼명) from 테이블명

테이블명.objects.aggregate(Count('칼럼명')) : select count(칼럼명) from 테이블명

테이블명.objects.filter(칼럼명=값) : select * from 테이블명 where 칼럼명 = 값

테이블명.objects.values('칼럼명').annotate(Avg('칼럼명')) : select avg(칼럼명) from 테이블명 group by 칼럼명

 

 

 * index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
메인(QuerySet Test)<br>
<a href="calldata/">db 자료를 읽어 dict type으로 출력</a>
<br>
<a href="admin/">장고가 지원하는 관리자 창</a>
</body>
</html>

 

 

 

 * list.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
자료 보기</p>
{{pro_list}}
</body>
</html>

7. 원격 DB

 = django_test06_mariadb

DB 접속하여 DataBase 생성

explore 창 - 프로젝트 오른쪽 클릭 - Django - Create application - myguset

 

 

 * settings

INSTALLED_APPS = [

    ...
    
    'myguest',
]

...

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'yourdb',                     # DB명 : db는 미리 작성되어 있어야 함.       
        'USER': 'root',                       # 계정명 
        'PASSWORD': '123',                    # 계정 암호           
        'HOST': '127.0.0.1',                  # DB가 설치된 컴의 ip          
        'PORT': '3306',                       # DBMS의 port 번호     
    }
}

DATABASES = {
    'default': {

        django.db.backends.mysql',

        'NAME': 'database명',                     # DB명 : db는 미리 작성되어 있어야 함.       
        'USER': 'root',                          # 계정명 
        'PASSWORD': '123',                  # 계정 암호           
        'HOST': '127.0.0.1',                   # DB가 설치된 pc의 ip          
        'PORT': '3306',                        # DBMS의 port 번호     
    }
}

 => remote DB 연결 정보.

 

 

 * models

from django.db import models

# Create your models here.
class Guest(models.Model):
    myno = models.AutoField(auto_created = True, primary_key = True)
    title = models.CharField(max_length=50)
    content = models.TextField()
    regdate = models.DateTimeField()
    
    def __str__(self):
        return self.title
    
    class Meta:
        ordering = ('-title', 'id') # title이 같으면 id로 정렬
        ordering = ('-id',) # tuple 타입만 가능. 

칼럼명 = models.AutoField(auto_created = True, primary_key = True) : 자동 증가하는 index 기본키 생성.

칼럼명 = models.TextField() : text타입 칼럼 생성

 

class Meta:

ordering = ('-칼럼명1', '칼럼명2')

 => 칼럼명1 기준 desc 정렬 후 데이터가 같은 정보에 대해 칼럼명2 기준 asc정렬.

 

 

 - explore 창 - 프로젝트 오른쪽 클릭 - Django - Make Migrations - myguset

 - explore 창 - 프로젝트 오른쪽 클릭 - Django - Migrate

 

 

 * admin

from django.contrib import admin
from myguest.models import Guest

# Register your models here.
class GuestAdmin(admin.ModelAdmin):
    list_display = ('id', 'title', 'content', 'regdate')

admin.site.register(Guest, GuestAdmin)

 => 테이블과 admin계정 연결.

 

 

 * admin계정 id 생성 및 table data 입력

 

 

 * urls(django_test06_mariadb)

from django.contrib import admin
from django.urls import path
from myguest import views
from django.urls.conf import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.MainFunc),
    path('guest/', include("myguest.urls")),
]

 => url과 views 연결

 

 

 * urls(myguest)

from django.urls import path
from myguest import views

urlpatterns = [
    path('', views.ListFunc),
    path('insert', views.InsertFunc),
    path('insertok/', views.InsertOkFunc),
]

 => url과 views 연결

 

 

 * views

from django.shortcuts import render
from myguest.models import Guest
from datetime import datetime
from django.http.response import HttpResponseRedirect

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

def ListFunc(request):
    gdata = Guest.objects.all()                       # 전체 자료 읽기
    gdata = Guest.objects.all().order_by('title')    # order_by ascending
    gdata = Guest.objects.all().order_by('-title')   # order_by descending
    gdata = Guest.objects.all().order_by('-id')[0:2] # 정렬 후 슬라이싱
    print('gdata type : ', type(gdata))               # <class 'django.db.models.query.QuerySet'>
    return render(request, 'list.html', {'gdatas' : gdata})

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

def InsertOkFunc(request):
    if request.method =='POST':
        print(request.POST.get('title'))
        print(request.POST['title'])
        # 입력자료로 테이블에 저장 : ORM
        Guest(
            title = request.POST.get('title'),
            content = request.POST.get('content'),
            regdate = datetime.now()
        ).save()
    return HttpResponseRedirect('/guest') # 추가후 목록 보기
'''
# 수정
g = Guest.objects.get(id=1)
g.title = "하하"
g.content = '하하하'
g.save()

# 삭제
g = Guest.objects.get(id=1)
g.delete
'''

테이블명.objects.all().order_by('칼럼명') : order by 칼럼명 asc

테이블명.objects.all().order_by('-칼럼명') : order by 칼럼명 desc

 

 - insert

테이블명(

    변수명 = request.POST.get('칼럼명'),

     ...

    변수명 = datetime.now()

).save()

 

 - update

temp = 테이블명.objects.get(조건)

temp.칼럼명 = "수정값"

temp.save()

 

 - delete

temp = 테이블명.objects.get(조건)

temp.delete()

 

 

 * main.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>메인</h2>
<a href="guest/">미니 방명록 보기</a>
</body>
</html>

 

 * list.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>글 목록</h2>

<a href="/guest/insert">자료 추가</a>
<table border="1">
	<tr>
		<th>아이디</th><th>제목</th><th>내용</th><th>등록일</th>
	</tr>
	{% if gdatas %}
	{% for g in gdatas %}
	<tr>
		<td>{{g.id}}</td>
		<td>{{g.title}}</td>
		<td>{{g.content}}</td>
		<td>{{g.regdate}}</td>
	</tr> 
	{% endfor %}
	{% else %}
	<tr>
		<td colspan ="4">자료가 없습니다.</td>
	</tr>
	{% endif %}
</table>
</body>
</html>

 

 * insert.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>방명록 글 입력</h2>
<form action="/guest/insertok/" method="post">{% csrf_token %}
<table>
	<tr>
		<td>제목</td>
		<td><input type="text" name="title" size="48"/></td>
	</tr>
	<tr>
		<td>내용</td>
		<td><textarea rows="5" cols="50" name="content"></textarea></td>
	</tr>
	<tr>
		<td colspan="2" style="text-align: center;"><input type="submit" value="등록" /></td>
	</tr>

</table>
</form>
</body>
</html>

8. DB - ForeignKey

 = django_test07

Django - create application - sangpumapp

 

 * settings

INSTALLED_APPS = [
    ...
    'sangpumapp',
]

...

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'sanpumdb',            # DB명 : db는 미리 작성되어 있어야 함.       
        'USER': 'root',                # 계정명 
        'PASSWORD': '123',             # 계정 암호           
        'HOST': '127.0.0.1',           # DB가 설치된 컴의 ip          
        'PORT': '3306',                # DBMS의 port 번호     
    }
}

 => application 연결 및 dataBase 연결 설정.

 

 

 * models

from django.db import models

# Create your models here.
class Maker(models.Model):
    mname = models.CharField(max_length=10)
    tel = models.CharField(max_length=20)
    addr = models.CharField(max_length=50)
    
    class Meta:
        ordering = ('-id',)
        
    def __str__(self):
        return self.mname
    
class Product(models.Model):
    pname = models.CharField(max_length=50)
    price = models.IntegerField()
    maker_name = models.ForeignKey(Maker, on_delete = models.CASCADE) # Maker table의 id와 연결

칼럼명 = models.ForeignKey(연결할 테이블명, on_delete = models.CASCADE) : 다른 테이블의 id를 Foreign Key로 사용

 

 

Django - make migrations - sangpumapp

Django - migrate

 

anaconda 접속 - cd C:\work\psou\django_test07 - python manage.py createsuperuser

 

 * admin

from django.contrib import admin
from sangpumapp.models import Maker, Product

# Register your models here.
class MakerAdmin(admin.ModelAdmin):
    list_display =('id', 'mname', 'tel', 'addr')
admin.site.register(Maker, MakerAdmin)

class ProductAdmin(admin.ModelAdmin):
    list_display =('id', 'pname', 'price', 'maker_name')
admin.site.register(Product, ProductAdmin)

 => 테이블에 admin 계정 연결.

 

http://127.0.0.1/admin/ 접속

Maker/Product table에 data 추가

 

 * urls

from django.contrib import admin
from django.urls import path
from sangpumapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    
    path('', views.Main),
    path('list1', views.List1), # maker
    path('list2', views.List2), # product
    path('list3', views.List3), # list1 -> list2
]

 => url과 views 연결.

 

 

 * views

from django.shortcuts import render
from sangpumapp.models import Maker, Product

# Create your views here.
def Main(request):
    return render(request, 'main.html')
    
def List1(request):
    makers = Maker.objects.all() # select
    return render(request, 'list1.html', {'makers':makers})
    
def List2(request):
    products = Product.objects.all() # select
    pcount = len(products)
    return render(request, 'list2.html', {'products':products, 'pcount':pcount})
    
def List3(request):
    mid = request.GET.get("id")
    products = Product.objects.all().filter(maker_name = mid)
    pcount = len(products)
    return render(request, 'list2.html',{'products':products, 'pcount':pcount})

변수1 = request.GET.get("key값")

테이블1.objects.all().filter(칼럼1 = 변수1) : 테이블1의 칼럼1에서 key의 value와 동일값의 list 출력.

 

 

 * main.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>메인화면</h2>
<ul>
	<li><a href="list1">상품 제조사 보기</a></li>
	<li><a href="list2">상품 목록 보기</a></li>
	<li>묻고 답하기</li>
</ul>
</body>
</html>

 * list1.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>제조사 목록</h2>
	<table border="1">
		<tr>
			<th>아이디</th><th>제조사</th><th>전화번호</th><th>주소</th>
		</tr>
		{% if makers %}
		{% for m in makers %}
		<tr>
			<td>{{m.id}}</td>
			<td><a href="list3?id={{m.id}}">{{m.mname}}</a></td>
			<td>{{m.tel}}</td>
			<td>{{m.addr}}</td>
		</tr>
		{% endfor %}
		{% else %}
		<tr>
			<td colspan="4">자료가 없습니다.</td>
		</tr>
		{% endif %}
	</table>
</body>
</html>

 

 * list2.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>상품 목록</h2>
	<table border="1">
		<tr>
			<th>아이디</th><th>상품명</th><th>가격</th><th>제조사</th>
		</tr>
		{% if products %}
		{% for p in products %}
		<tr>
			<td>{{p.id}}</td>
			<td>{{p.pname}}</td>
			<td>{{p.price}}</td>
			<td>{{p.maker_name}}</td>
		</tr>
		{% endfor %}
		<tr>
			<td colspan="4">건수{{pcount}}</td>
		<tr>
		{% else %}
		<tr>
			<td colspan="4">자료가 없습니다.</td>
		</tr>
		{% endif %}
	</table>
</body>
</html>


9. DB - CRUD, 페이징

① 메인 페이지

 = django_test08_sangdata

 * settings

...

INSTALLED_APPS = [

    ...
    
    'mysangpum',
]

...

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'test',                # DB명 : db는 미리 작성되어 있어야 함.       
        'USER': 'root',                # 계정명 
        'PASSWORD': '123',             # 계정 암호           
        'HOST': '127.0.0.1',           # DB가 설치된 컴의 ip          
        'PORT': '3306',                # DBMS의 port 번호     
    }
}

...

TIME_ZONE = 'Asia/Seoul'
USE_TZ = False

TIME_ZONE = 'Asia/Seoul'
USE_TZ = False

 => admin 페이지에 표시되는 시간은 기본적으로 UTC(UTC+9)이므로, 입력을 해도 9시간 전으로 표시된다.
      이에 표시되는 시간과 실제 DB에 입력되는 시간을 모두 Local시간(UTC)으로 맞춰 주어야 한다

 

 

 * remote DB의 데이터를 Django 형식으로 불러오기

anconda 접속

cd C:\work\psou\django_test08_sangdata
python manage.py inspectdb > abc.py

 => 이미 생성되어 있는 DB를 django 형식으로 abc.py에 코드 자동 작성.

 

 

 * models

from django.db import models

# Create your models here.
class Sangdata(models.Model):
    code = models.IntegerField(primary_key=True)
    sang = models.CharField(max_length=20, blank=True, null=True)
    su = models.IntegerField(blank=True, null=True)
    dan = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'sangdata'

 => abc.py의 sangdata table 내용 입력

 

 

 - Django - Make migrations - mysangpum

 - Django - Migrate

 

 

 * urls(django_test08_sangdata)

from django.contrib import admin
from django.urls import path
from mysangpum import views
from django.urls.conf import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.MainFunc),
    path('sangpum/', include('mysangpum.urls')), # 요청 위임
]

 => url과 views 연결.

 

 

 * views

def MainFunc(request):
    return render(request, 'main.html')

 

 

 * main.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>메인</h2>
<a href="sangpum/list">상품보기(MariaDB)</a>
</body>
</html>

 

 

② list 출력

 

 * urls(mysangpum)

from django.urls import path
from mysangpum import views

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

 => url, views 연결

 

 

 * views

def ListFunc(request):
    
    #SQL 직접사용해 보기
    conn = MySQLdb.connect(**config)
    sql = 'select * from sangdata'
    cursor = conn.cursor()
    cursor.execute(sql)
    datas = cursor.fetchall()
    print(type(datas)) # tuple
    
    
    # Django ORM
    datas = Sangdata.objects.all()
    return render(request, 'list.html', {'sangpums':datas})
    
    ...

 

 

* list.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<h2>상품자료</h2>
<div style="width:80%; text-align:right;">
	<a href="/sangpum/insert">상품 추가</a>
</div>
<table class="table" style="width:80%;">
	<tr>
		<th>code</th><th>상품</th><th>수량</th><th>단가</th><th>기타</th>
	</tr>
	{% if sangpums %}
	{% for s in sangpums%}
	<tr>
		<!-- <td>{{s.0}}</td> -->
		<td>{{s.code}}</td>
		<td>{{s.sang}}</td>
		<td>{{s.su}}</td>
		<td>{{s.dan}}</td>
		<td>
			<a href="/sangpum/update?code={{s.code}}">수정</a> /
			<a href="/sangpum/delete?code={{s.code}}">삭제</a>
			</td>
	</tr>
	{% endfor%}
	{% else %}
	<tr>
		<td colspan="5">자료가 없습니다.</td>
	</tr>
	{% endif%}
</table>
</body>
</html>

 

 

③ 페이징 처리

 

 * views

def ListFunc(request):
    ...
    # 페이지 나누기 처리 - Paginator 클래스
    datas = Sangdata.objects.all().order_by('-code') # order by code desc
    paginator = Paginator(datas, 3) # 페이지당 출력 행수를 생성자로 전달
    try:
        page = request.GET.get('page') # page 값을 read
    except:
        page = 1 # page 값이 없을 경우 1 page 출력
    
    try:
        data = paginator.page(page)
    except PageNotAnInteger: # page가 숫자가 아닐 경우
        data = paginator.page(1)
    except EmptyPage:
        data = paginator.page(paginator.num_pages()) # 현재 페이지 출력
    
    # 클라이언트 화면에 개별 페이지 번호 표시용
    allPage = range(paginator.num_pages + 1)
    #print('allPage : ', allPage) # range(0, 5)
    return render(request, 'list2.html', {'sangpums':data, 'allPage':allPage}) 

paginator = Paginator(데이터, 출력행수) : 객체 생성. 페이지당 출력 행수를 생성자로 전달

paginator.page(출력페이지) : 나눠진 페이지에서 출력할 페이지 입력.

paginator.num_pages : 총페이지 수

 

* list2.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
	function func(){
		//alert("aa");
		let result = confirm("정말 삭제 할까요?")
		if(result){
			frm.submit();
		}
	}
</script>
</head>
<body>
<h2>상품자료</h2>
<div style="width:80%; text-align:right;">
	<a href="/sangpum/insert">상품 추가</a>
</div>
<table class="table" style="width:80%;">
	<tr>
		<th>code</th><th>상품</th><th>수량</th><th>단가</th><th>기타</th>
	</tr>
	{% if sangpums %}
	{% for s in sangpums%}
	<tr>
		<!-- <td>{{s.0}}</td> -->
		<td>{{s.code}}</td>
		<td>{{s.sang}}</td>
		<td>{{s.su}}</td>
		<td>{{s.dan}}</td>
		<td>
			<a href="/sangpum/update?code={{s.code}}">수정</a> /
			<!-- 삭제 전에 묻는 작업이 필요 -->
			<form action="/sangpum/delete" name="frm" method="get" style="display:inline;">
				<input type="hidden" name="code" value="{{s.code}}">
				<a href="javascript:void(0); onclick=func()">삭제</a>
			</form>
			</td>
	</tr>
	{% endfor%}
	<!-- paging -->
	<tr>
		<td colspan="5">
		{% if sangpums.paginator.num_pages > 1 %}
			<ul class="pager">
				{% if sangpums.has_previous %}
					<li class="previous"><a href="/sangpum/list?page={{sangpums.previous_page_number}}">Previous</a></li>
					<!-- <li><a href="/sangpum/list?page={{sangpums.previous_page_number}}">&laquo;이전</a></li> -->
				{% endif %}
				
				{% if sangpums.has_next %}
					<li class="next"><a href="/sangpum/list?page={{sangpums.next_page_number}}">Next</a></li>
					<!-- <li><a href="/sangpum/list?page={{sangpums.next_page_number}}">다음&raquo;</a></li> -->
				{% endif %}
				&nbsp; &nbsp;
				<li>(페이지 : {{sangpums.number}} / {{sangpums.paginator.num_pages}})</li>
			</ul>
			<hr>
			
			{% for p in allPage%}
				{% if p > 0 %}
					{% if p == sangpums.number %}
						[{{p}}]
					{% elif p != sangpums.number %}
						<a href="/sangpum/list?page={{p}}]"> {{p}} </a>
					{% endif %}
				{% endif %}
			{% endfor%}
		{% endif %}
		</td>
	</tr>
	{% else %}
	<tr>
		<td colspan="5">자료가 없습니다.</td>
	</tr>
	{% endif%}
</table>
</body>
</html>

data.number : 현재페이지

data.paginator.num_pages : 총 페이지

 

④ 게시물 추가

 * views

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

def InsertokFunc(request):
    if request.method == 'POST':
        code = request.POST.get("code")
        #print('code : ', code)
        # 새로운 상품 code 유무 검증 작업 후 insert 진행
        try:
            Sangdata.objects.get(code=code) # where
            #print('code 있음')
            return render(request, 'insert.html', {'msg':'이미 등록된 번호입니다.'})
        except Exception as e:
            #print('code 없음')
            Sangdata(
                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') # 추가 후 목록 보기

 

 * insert.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
	window.onload = function(){
		document.getElementById("btnSummit").onclick = function(){
			chkData()
		}
	}
	function chkData(){
		//alert('a');
		if(frm.code.value === "" | frm.sang.value === ""){ // 입력자료 오류 검사
			alert("입력자료를 모두 채우시오.")
			return;
		}
		frm.submit();
	}
</script>

</head>
<body>
<h2>상품 추가</h2>
<form action="/sangpum/insertok" method="post" name="frm">{% csrf_token %}
	<table class="table" style="width:80%;">
		<tr>
			<td>코드 : </td>
			<td><input class="form-control" type="text" name="code"/>{{msg}}</td>
		</tr>
		<tr>
			<td>품명 : </td>
			<td><input class="form-control" type="text" name="sang"/></td>
		</tr>
		<tr>
			<td>수량 : </td>
			<td><input class="form-control" type="text" name="su"/></td>
		</tr>
		<tr>
			<td>단가 : </td>
			<td><input class="form-control" type="text" name="dan"/></td>
		</tr>
		<tr>
			<td colspan="4">
				<input class="btn-primary" type="button" value="저장" id="btnSummit">
			</td>
		</tr>
	</table>
</form>
</body>
</html>

 

⑤ 게시물 수정

 

 * views

def UpdateFunc(request):
    data = Sangdata.objects.get(code = request.GET.get('code'))
    return render(request, 'update.html', {'sang_one':data})

def UpdateokFunc(request):
    if request.method == 'POST':
        upRec = Sangdata.objects.get(code=request.POST.get('code'))
        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') # 수정 후 목록 보기

 

 * update.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<h2>상품 수정</h2>
<form action="/sangpum/updateok" method="post">{% csrf_token %}
	<table class="table" style="width:80%;">
		<tr>
			<td>코드 : </td>
			<td>
				{{sang_one.code}}
				<input class="form-control" type="hidden" name="code" value="{{sang_one.code}}"/>
			</td>
		</tr>
		<tr>
			<td>품명 : </td>
			<td><input class="form-control" type="text" name="sang" value="{{sang_one.sang}}"/></td>
		</tr>
		<tr>
			<td>수량 : </td>
			<td><input class="form-control" type="text" name="su" value="{{sang_one.su}}"/></td>
		</tr>
		<tr>
			<td>단가 : </td>
			<td><input class="form-control" type="text" name="dan" value="{{sang_one.dan}}"/></td>
		</tr>
		<tr>
			<td colspan="4">
				<input class="btn-primary" type="submit" value="수정">
				<input type="button" value="이전화면" onclick="history.back()">
			</td>
		</tr>
	</table>
</form>
</body>
</html>

 

⑥ 게시물 삭제

 * views

def DeleteFunc(request):
    delRec = Sangdata.objects.get(code=request.GET.get('code'))
    delRec.delete()
    return HttpResponseRedirect('/sangpum/list') # 삭제 후 목록 보기

10. 게시판

 = django_test09_board

 

 

0. Django

1. 환경구축

2. 외부파일 사용하기

3. url 연결

4. session


0. Django : 파이썬 웹 제작 프레임워크

model, template, view Pattern의 프로그램 작성

(model, view, controller과 대응)

 

1. 환경구축

Django 설치

 anaconda prompt 접속 후 명령어 입력

pip install Django==3.1.6

 

Django 프로젝트 생성

① 명령어 창 사용

anaconda prompt 접속 후 명령어 입력

cd C:\work\psou
django-admin startproject django_ex

explorer창 - import - General - Existing Projects into Workspace - [Brows] 경로 설정, [Copy projects into workspace] Check

 

서버 실행

cd C:\work\psou\django_ex
python manage.py migrate
type db.sqlite3
python manage.py runserver

서버실행(ip, port설정)

cd C:\work\psou\django_test1
python manage.py runserver 7777
python manage.py runserver 192.168.0.3:7777

 

server port 변경

C:\anaconda3\Lib\site-packages\django\core\management\commands\runserver.py

default_port = '80'
=> port 번호 변경

서버 종료 : ctrl + c 두번

 

 

② 이클립스 사용

 - [File] - [New] - [other] - [PyDev Project] - name입력, 3.8 선택, python 선택 - finish
 - explorer창 - project 오른쪽 클릭 - Django - Migrate

 - explorer창 - project 오른쪽 클릭 - Django - Create application - myapp
 - explorer창 - project 오른쪽 클릭 - Run as - PyDev
 - http://127.0.0.1:8000/ 접속


2. 외부파일 사용하기

 = django_test1

 * settings.py : 설정

...

ALLOWED_HOSTS = ['*']

...

INSTALLED_APPS = [
	...
    
    'myapp',
]

...

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

STATICFILES_DIRS = (   os.path.join(BASE_DIR, 'static'), ) : base경로의 static folder의 외부파일 불러올 수 있도록 연결.

 

 * urls.py : 모든 클라이언트의 요청을 받음

from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    
    path('', views.index),
    path('hello', views.hello_func),
    path('hello_tem', views.hello_template),
    path('world', views.world_func)
]

 path('url명', views.메소드명) : 요청명 연결

 

 * views.py : 요청에 대한 기능 구현

from django.shortcuts import render
from django.http.response import HttpResponse

# Create your views here.
def index(request):
    return HttpResponse("기본요청 처리")

def hello_func(request):
    msg = '장고 '
    ss = "<html><body>장고프로젝트 작성 메세지 : %s</body></html>"%msg
    return HttpResponse(ss)

def hello_template(request):
    mymsg = '홍길동'
    return render(request, 'show.html',{'msg':mymsg})

def world_func(request):
    return render(request, 'disp.html')

HttpResponse(응답 메시지) : Http 응답 메시지 send.

render(request, '연결페이지.html', {'key':value, ... }, ... ) : 연결페이지에 dict타입 정보 send

 * show.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
hi {{msg}} &lt;- 장고의 template 변수 태그
<br>
<a href="world">world 문서</a>
</body>
</html>

 {{key}} : dict타입 key의 value 값 출력

 * disp.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel='stylesheet' type='text/css' href='/static/css/test.css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="/static/js/test.js"></script>
<script type="text/javascript">
/*
window.onload = function(){
	alert("good");
}
 */
$(document).ready(function(){
	//alert("nice");
	$("#myImg").click(function(){
		abc();
	});
});

 
</script>
</head>
<body>
<span style="color: #ff0000; font-size: 24px;">성공</span>
<br>
<b>자원관리는 static</b><strong>폴더 </strong>사용
<br>
<img src = "/static/images/pic.png" id="myImg" />
</body>
</html>

 * test.js

function abc(){
	alert("test");
	history.back();
}

history.back() : 뒤로가기 수행


3. url 연결

 - Function views 방법
 - Class-base views 방법
 - Including another URL conf 방법

 

 = django_test2

 * settings.py

INSTALLED_APPS = [
    'gpapp',
]

 

 * urls.py(django_test2)

from django.contrib import admin
from django.urls import path
from gpapp import views
from gpapp.views import CallView
from django.urls.conf import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.MainFunc, name='MainFunc'), # Function views 방법
    path('gpapp/callget', CallView.as_view()), # Class-base views 방법
    path('sangpum/', include('gpapp.urls')),   # Including another URLconf 방법
    
]

path('url명', views.메소드명) : 해당 url이 수신 시 view.py의 해당 메소드 실행.

path('url명', 클래스명.as_view()) : 해당 url 수신 시 해당 클래스 실행.

path('url명', include('application명.urls')) : 해당 url이 포함됨 url 수신 시 해당 application의 urls 파일에서 나머지 url 연결하여 실행. 

 

 * views

from django.shortcuts import render
from django.views.generic.base import TemplateView

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

class CallView(TemplateView):
    template_name = "callget.html"
    
def InsertFunc(request):
    #return render(request, "insert.html") # get/post 모두 처리
    if request.method == 'GET':
        print('GET 요청')
        return render(request, "insert.html")
    elif request.method == 'POST':
        print('POST 요청')
        name = request.POST.get("name")
        name = request.POST.["name"]
        return render(request,"list.html", {"name":name})
    else:
        print('요청 에러')

def SelectFunc(request):
    pass

def UpdateFunc(request):
    pass

request.method : 요청의 method를 get한다. ('GET', 'POST', ... )

request.GET.get('key값') : GET 요청에서 key의 value를 get한다.

request.POST.get('key값') : POST 요청에서 key의 value를 get한다.

 

 * index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
두번째 프로젝트 메인화면
<p/>
GET/POST 연습<br>
<a href="/gpapp/callget">callget 파일 요청 (get 방식)</a>
</body>
</html>

 

 * callget.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
GET/POST 연습<br>
<a href="/sangpum/insert">자료입력</a><br>
<a href="/sangpum/select">자료보기</a><br>
<a href="/sangpum/update">자료수정</a><br>
</body>
</html>

 

 * urls.py(gpapp)

# 메인 urls가 각 app에 처리 위임
from django.urls import path
from gpapp import views

urlpatterns = [
    path('insert', views.InsertFunc),
    path('select', views.SelectFunc),
    path('update', views.UpdateFunc),
]

 urls.py(django_test2)  ->  urls.py(gpapp)  -> views.py  -> insert.html  -> urls.py(django_test2)  ->  urls.py(gpapp)  -> views.py  ->list.html

 

 * insert.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
자료입력<p/>
<form action="/sangpum/insert" method="post">{% csrf_token %}<!-- 해킹 방지 -->
이름 : <input type="text" name="name">
<input type="submit" value="등록 확인">
</form>
</body>
</html>

{% csrf_token %} : 해킹방지 코드

 

 * list.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
결과 출력 : {{name}} {{123}} {{'문자열'}} {#주석#}
</body>
</html>


4. session

 = django_test3_session

 * settings

INSTALLED_APPS = [
    ...
    'sessionapp'
]

 

 * urls

from django.contrib import admin
from django.urls import path
from sessionapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.mainFunc),       # 1
    path('setos', views.setosFunc), # 2
    path('shows', views.showsFunc), # 3
]

 

 * views

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

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

def setosFunc(request): # 2
    if "favorite_os" in request.GET:
        print(request.GET['favorite_os'])
        request.session['f_os'] = request.GET["favorite_os"] # f_os 라는 키로 세션에 저장
        return HttpResponseRedirect('/shows') # 클라이언트를 통해서 shows 요청을 발생
    else:
        print('a')
        return render(request, 'setos.html')
    
def showsFunc(request): # 3
    context = {} # dict type 변수 생성
    
    if "f_os" in request.session:
        context['f_os'] = request.session['f_os'] # request.session.get('f_os')
        context['message'] = "선택된 운영체제 %s"%request.session['f_os']
    else:
        context['f_os'] = None
        context['message'] = "운영체제를 선택하지않았습니다."
        
    request.session.set_expiry(5); # session 유효 기간 5초 설정 
    
    return render(request, 'show.html', context)

 

HttpResponseRedirect('url명') : 클라이언트를 통해서 url요청명을 send.

 => session

request.session['key'] = value : session에 key값에 value값 set.

value = request.session.get('key값') : session에 key값에 value값 get.

value = request.session['key값'] : session에 key값에 value값 get.

request.session.set_expiry(초) : session 유효 시간 초 단위로 설정.

 

 * main.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
메인화면<p/>
session 연습 : 세션이란 일정시간 동안 같은 사용자로 부터 들어오는 여러 가지 요구들을 하나의 상태를 보고 그 상태를 일정하게 유지 시킨 기술.
클라이언트와 서버 사이의 연결이 유지되는 것 처럼 하기 위해 클라이언트의 정보를 서버 컴퓨터의 일정 공간을 확보해 정보를 기억시킬 수 있다.
<br>
<a href="/setos/">운영체제 선택하기</a>
</body>
</html>

 

 * setos.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>2. 세션 이해하기</h2>
<p>운영체제 선택</p>
<a href="/setos?favorite_os=window">윈도우</a><br>
<a href="/setos?favorite_os=mac">mac</a><br>
<a href="/setos?favorite_os=linux">리눅스</a><br>
</body>
</html>

=> url : setos, key : favorite_os, value : window, mac, linux

 

 * show.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>3. 세션 결과보기</h2>
<p>반환된 context의 message : {{message}}</p>
<p>반환된 context의 f_os : {{f_os}}</p>
<p>session의 f_os 값 직접 출력: {{request.session.f_os}}</p>
<a href="/setos">운영체제 다시 선택</a>
<a href="/">main page</a>
</body>
</html>

 

+ Recent posts

1