Anaconda Prompt
properties 참고하여 경로이동
python manage.py inspectdb > aa.py
생성된 aa.py에서 Sangdata 복사 후 models.py에 복사
settings.py
"""
Django settings for django11_ajax_db project.
Generated by 'django-admin startproject' using Django 4.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-)+i!6!611b&$93wyj+vjr614yog1y72sn$1h4orv2n&h(sr4t("
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"myajax",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "django11_ajax_db.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "django11_ajax_db.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'USER': 'root',
'PASSWORD': '123',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",},
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = "ko-kr"
TIME_ZONE = "Asia/Seoul"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = "static/"
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
models.py
위의 과정에서 생성된 aa.py에서 Sangdata 복사 후 models.py에 복사
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'
urls.py
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('calldb1',views.ListDbFunc),
path('calldb2',views.ListDbFunc),
]
views.py
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()
datas = []
for s in sdata:
dic = {'code':s.code, 'sang':s.sang, 'su':s.su, 'dan':s.dan,}
datas.append(dic)
print(datas)
return HttpResponse(json.dumps(datas), content_type="application/json")
main.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
메인<p/>
부서 직원 고객 <a href="/list">상품</a>
</body>
</html>
list.html
기본 방식과 fetch 방식
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
let xhr;
window.onload = function(){
// 자바스크립트 객체(XMLHttpRequest)를 사용한 ajax 기본 방식
document.querySelector("#btnOk1").onclick = function(){
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
process1();
}
}
}
url = "calldb1"
xhr.open("GET", url, true);
xhr.send();
}
// fetch 방식
document.querySelector("#btnOk2").onclick = function(){
const url = "calldb2";
fetch(url).then(res => {
if(res.status === 200){
return res.json()
}else{
console.error(`HTTP 에러! status:$(res.status)`);
}
})
.then(jsonData => {
process2(jsonData);
})
.catch(err =>{
console.error(err);
});
}
}
function process1(){
let parseData = JSON.parse(xhr.responseText);
// alert(parseData);
let str = "<table border='1'>"
str += "<tr><th>코드</th><th>품명</th><th>수량</th><th>단가</th></tr>";
let count = 0;
for(let i = 0; i < parseData.length; i++){
str += "<tr>";
str += "<td>" + parseData[i].code + "</td>";
str += "<td>" + parseData[i].sang + "</td>";
str += "<td>" + parseData[i].su + "</td>";
str += "<td>" + parseData[i].dan + "</td>";
str += "</tr>";
count++;
}
str += "</table>";
document.querySelector("#showData1").innerHTML = str;
}
function process2(jsonData){
let str = "<table border='1'>"
str += "<tr><th>코드</th><th>품명</th><th>수량</th><th>단가</th></tr>";
let count = 0;
for(let i = 0; i < jsonData.length; i++){
str += "<tr>";
str += "<td>" + jsonData[i].code + "</td>";
str += "<td>" + jsonData[i].sang + "</td>";
str += "<td>" + jsonData[i].su + "</td>";
str += "<td>" + jsonData[i].dan + "</td>";
str += "</tr>";
count++;
}
str += "</table>";
document.querySelector("#showData2").innerHTML = str;
}
</script>
</head>
<body>
Ajax 연습 : 원격 DB 자료 보기<p/>
<button id="btnOk1">상품자료 출력 1</button>
<br>
<div id="showData1"></div>
<hr>
<button id="btnOk2">상품자료 출력 2</button>
<br>
<div id="showData2"></div>
</body>
</html>
'Django' 카테고리의 다른 글
django10 - ajax (0) | 2022.10.20 |
---|---|
고객 정보 찾기 예제 (0) | 2022.10.19 |
django9 - DB, 게시판, 댓글 (0) | 2022.10.19 |
django project 과정 정리 (0) | 2022.10.18 |
django8 - DB, 표, CRUD, 페이징 (0) | 2022.10.18 |