{# 장고 템플릿 엔진 주석 문법 : templates/index.html 경로의 파일 #}
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8"/>
<title>Melon List</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1 class="fw-bold">Melon List</h1>
<!-- autocomplete는 자동완성 기능 끄는 것-->
<form action="" method="get" autocomplete="off" class="my-4">
<input type="text" name="query" placeholder="검색어를 입력해주세요 : " autofocus
value="{{ query }}" class="form-control">
<!-- django의 템플릿 문법-->
</form>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>곡명</th>
<th>가수</th>
</tr>
</thead>
<tbody>
{% for song in song_list %}
<tr>
<td>{{ song.곡명 }}</td>
<td>{{ song.가수 }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
ctrl
+ alt
+ 'L`
: 지정 범위 코드 포맷 정리
{# 장고 템플릿 엔진 주석 문법 : templates/index.html 경로의 파일 #}
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8"/>
<title>Melon List</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<div class="container mx-auto">
<h1 class="font-bold text-2xl">Melon List</h1>
<!-- autocomplete는 자동완성 기능 끄는 것-->
<form action="" method="get" autocomplete="off" class="my-4">
<input type="text" name="query" placeholder="검색어를 입력해주세요 : " autofocus
value="{{ query }}" class="w-full p-2 border rounded focus:outline-none focus:ring">
<!-- django의 템플릿 문법-->
</form>
<table class="min-w-full bg-white border border-gray-300 divide-y divide-gray-300">
<thead>
<tr class="text-center">
<th class="py-2 px-4 border-b">곡명</th>
<th class="py-2 px-4 border-b">가수</th>
</tr>
</thead>
<tbody>
{% for song in song_list %}
<tr class="hover:bg-gray-200">
<td class="py-2 px-4">{{ song.곡명 }}</td>
<td class="py-2 px-4">{{ song.가수 }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
<!-- SCR -->
<script>
// textContent는 안에 내용을 뜻함
const songList = JSON.parse(document.querySelector("#song-list-json").textContent);
songList.forEach(song => {
const tr = document.createElement("tr");
tr.innerHTML = `
<td>${song['곡명']}</td>
<td>${song['가수']}</td>
`;
document.querySelector("#song-list-table tbody").append(tr);
});
</script>
# pip install "django~=4.2.0"
# import sqlite3
# mydjango.py
import sys
import django
import requests
from django.db import models
from django.conf import settings
from django.core.management import execute_from_command_line
from django.db import connection
from django.db.models import Q
from django.http import JsonResponse
# from django.http import HttpResponse
from django.shortcuts import render
from django.urls import path
settings.configure(
ROOT_URLCONF=__name__,
DEBUG=True,
SECRET_KEY="secret",
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "melon-20230906.sqlite3", # 파일 경로
}
},
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": ["templates"],
}
],
)
django.setup()
class Song(models.Model):
id = models.AutoField(primary_key=True)
가수 = models.CharField(max_length=100)
곡명 = models.CharField(max_length=200)
곡일련번호 = models.IntegerField()
순위 = models.IntegerField()
앨범 = models.CharField(max_length=200)
좋아요 = models.IntegerField()
커버이미지_주소 = models.URLField()
class Meta:
db_table = "songs"
app_label = "mydjango"
# View 함수 : HTTP 요청이 올 때마다 호출 되어, 요청을 처리하여 응답을 생성/반환하는 함수
def index(request):
# query = request.GET.get("query", "").strip() # (검색어) 장고에서는 쿼리스트링을 가공한 값을 이렇게 가져올 수 있음
# # 검색어가 없더라도 디폴트 값 "" 반환
#
# song_list = Song.objects.all() #QuerySet type
# if query:
# song_list = song_list.filter(
# Q(곡명__icontains=query) | Q(가수__icontains=query)
# )
# song_list_data = list(song_list.values())
# index.html을 렌더
return render(request, "index.html")
def song_list_api(request):
query = request.GET.get("query", "").strip() # (검색어) 장고에서는 쿼리스트링을 가공한 값을 이렇게 가져올 수 있음
# 검색어가 없더라도 디폴트 값 "" 반환
song_list = Song.objects.all() #QuerySet type
if query:
song_list = song_list.filter(
Q(곡명__icontains=query) | Q(가수__icontains=query)
)
song_list_data = list(song_list.values())
return JsonResponse(song_list_data,
safe=False,
json_dumps_params={"ensure_ascii": False},
content_type="application/json; charset=utf-8")
# def get_song_list(query: str):
# # connection = sqlite3.connect("melon-20230906.sqlite3")
# cursor = connection.cursor()
# # connection.set_trace_callback(print)
#
# # query가 비었을 겨우 처리
# if query:
# param = '%' + query + '%'
# sql = "SELECT * FROM songs WHERE 가수 LIKE %s OR 곡명 LIKE %s"
#
# cursor.execute(sql, [param, param])
# else:
# cursor.execute("SELECT * FROM songs")
#
# column_names = [desc[0] for desc in cursor.description]
# print(column_names)
#
# songs_list = []
# for song_tuple in cursor.fetchall():
# song_dict = dict(zip(column_names, song_tuple))
# songs_list.append(song_dict)
# list comperhensior
# songs_list = [dict(zip(column_names, song_tuple))
# for song_tuple in cursor.fetchall()]
# connection.close()
# return songs_list
urlpatterns = [
path("", index), # http://localhost:8000 요청에 매핑
path("api/song-list.json", song_list_api)
]
execute_from_command_line(sys.argv)
{# 장고 템플릿 엔진 주석 문법 : templates/index.html 경로의 파일 #}
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8"/>
<title>Melon List</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<div class="container mx-auto">
<h1 class="font-bold text-2xl">Melon List</h1>
<!-- autocomplete는 자동완성 기능 끄는 것-->
<form action="" method="get" autocomplete="off" class="my-4">
<input type="text" name="query" placeholder="검색어를 입력해주세요 : " autofocus
value="{{ query }}" class="w-full p-2 border rounded focus:outline-none focus:ring">
<!-- django의 템플릿 문법-->
</form>
<table class="min-w-full bg-white border border-gray-300 divide-y divide-gray-300"
id="song-list-table">
<thead>
<tr class="text-center">
<th class="py-2 px-4 border-b">곡명</th>
<th class="py-2 px-4 border-b">가수</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
// CSR 방식
fetch("api/song-list.json")
.then(response => response.json())
.then(songList => {
songList.forEach(song => {
const tr = document.createElement("tr");
tr.innerHTML = `
<td>${song['곡명']}</td>
<td>${song['가수']}</td>
`;
document.querySelector("#song-list-table tbody").append(tr);
});
})
// textContent는 안에 내용을 뜻함
// const songList = JSON.parse(document.querySelector("#song-list-json").textContent);
// songList.forEach(song => {
// const tr = document.createElement("tr");
// tr.innerHTML = `
// <td>${song['곡명']}</td>
// <td>${song['가수']}</td>
// `;
// document.querySelector("#song-list-table tbody").append(tr);
// });
</script>
</div>
</body>
</html>