검색어로 노래 목록 필터링이 안되는 문제
244
작성한 질문수 18
안녕하세요, 진석 님.
'01-03 검색 지원' 강의를 듣다가 문제가 생겨 질문을 올립니다.
검색어 입력폼을 구현한 후,
검색어로 '악뮤'를 입력하고 검색하면 필터링이 되지 않고 song_list 전체 목록이 뜹니다.
쿼리 값을 사용해서 song_list 필터링을 못하는 것 같은데...
원인을 파악하지 못한채 진석 님 코드로 덮어 쓰기에는 제가 너무 답답해서, 진석 님 코드랑 제 코드도 비교를 해보았는데 코드 까막눈이라 어디서 잘못된지 못 찾겠습니다...
우선 제 코드들과 검색 창을 캡처한 이미지를 같이 첨부했습니다. 도움 부탁 드립니다!
<mydjango.py>
# mydjango.py
import sys
import django
import requests
from django.conf import settings
from django.core.management import execute_from_command_line
# 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",
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": ["templates"],
}
],
)
django.setup()
def index(request):
# qurery 있으면 가져오고, 없으면 빈 문자열로 가져오기
# => 사전에 지정 키가 없더라도 KeyError 예외를 발생시키지 않고 디폴트값 반환
query = request.GET.get("query", "").strip() # 검색어
json_url = "https://raw.githubusercontent.com/pyhub-kr/dump-data/main/melon/melon-20230906.json"
response = requests.get(json_url)
'''
#예외 발생 처리 코드
.ok 속성이 내부에서 raise_for status 함수를 사용하지만.
예외 발생이 아닌 True/False를 반환
- True: 서버 응답의 상태코드가 400 미만일 경우
- False: 서버 응답 상태코드가 400 이상, 600 미만일 경우
'''
if response.ok:
song_list = response.json()
else:
song_list = []
if query:
song_list = filter(
lambda song: query in song["가수"],
song_list,
)
response.raise_for_status()
song_list = response.json()
return render(request, "index.html", {"song_list": song_list})
urlpatterns = [
path("", index),
]
execute_from_command_line(sys.argv)
<index.html>
{# 장고 템플릿 엔진 주석 문법 : templates/index.html 경로의 파일 #}
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>Melon List</title>
<style>
body {
width: 400px;
margin: 0 auto;
}
table {
width: 100%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
form {
margin-bottom: 10px;
}
form input { width: 100% }
</style>
</head>
<body>
<h1>Melon List</h1>
<form action="" method="get" autocomplete="off">
<input type="text" name = "query" placeholder="검색어를 입력해주세요." autofocus/>
</form>
<table>
<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>
</body>
</html>
# 더 많은 노래를 보여주고 싶어요.
import requests # pip install requests
from pprint import pprint # 가독성좋게 출력하기 위한 모듈
json_url = "https://raw.githubusercontent.com/pyhub-kr/dump-data/main/melon/melon-20230906.json"
response = requests.get(json_url)
response.raise_for_status() # 비정상 응답을 받았다면, HTTPError를 발생시킵니다.
song_list = response.json()
print(type(song_list), len(song_list), type(song_list[0]))
pprint(song_list)
<검색어에 '악뮤' 입력 시, 나오는 화면>

답변 1
Django의 View나 URL의 네이밍 컨벤션
0
60
1
08-14 FormView 관련 질문
0
72
1
07-01 IPv4AddressIntegerField 질문
0
82
1
14-08 수업 확인 요청 드립니다.
0
91
2
nextjs git 관리?
0
75
1
14-07에서 SESSION_COOKIE_DOMAIN = None 처리 필요.
0
75
2
고민
0
219
3
django-component==0.139 실행 시 오류
0
167
2
django-csp 4.0 migration 관련
0
122
2
01 윈도우 개발환경 설치 문의
0
99
1
강의 자료 문의
0
129
2
선생님 학습 방법 질문이 있습니다.
0
154
2
bulk_update에서 updated_at 필드
0
124
1
정규표현식
0
107
2
선생님 질문 있습니다.
0
80
1
공유자님 이 강의 공부 방법에 대한 질문입니다.
0
181
2
mydjango.py 질문 있습니다.
0
147
3
Django-Components의 0.128 세팅
0
226
3
질문 아님.
0
127
1
mydjango.py 실습 질문있습니다.
0
87
2
pycharm 개발환경 설정 오류
0
182
2
강의 듣다가 유료pycharm에 비해 vscode지원기능이 아쉬워서 확장프로그램 만들었는데 여기 공유해도 될까요?
0
167
1
중단점에 대한 질문 있습니다.
0
133
2
todo / react 붙이는 깃주소를 받고 싶습니다.
0
179
6





