• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

검색어로 노래 목록 필터링이 안되는 문제

24.02.14 23:10 작성 조회수 118

0

안녕하세요, 진석 님.

 

'01-03 검색 지원' 강의를 듣다가 문제가 생겨 질문을 올립니다.

 

  1. 검색어 입력폼을 구현한 후,

  2. 검색어로 '악뮤'를 입력하고 검색하면 필터링이 되지 않고 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>

 

<main01.py>

# 더 많은 노래를 보여주고 싶어요.

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

답변을 작성해보세요.

0

안녕하세요.

올려주신 코드를 살펴보니

View 코드 끝에, render 함수 호출 직전에 다시 song_list 값을 채워넣는 코드가 있네요.

response.raise_for_status()

song_list = response.json()

위 두 줄을 제거하시면 예상하신 대로 동작하실 것으로 보여집니다.

살펴보시고 댓글 남겨주세요.

화이팅입니다. ;-)

 

주먹왕님의 프로필

주먹왕

질문자

2024.02.15

앗... 그런 실수를... ㅎㅎ

이번에도 덕분에 해결했습니다! 감사합니다 :)