`I want to implement the search function with the Django Web framework. I’m working on fetching public data (API) and fetching the data corresponding to the search results and showing it on the index.html page
is it search view!
def search(request):
base_url = "http://apis.data.go.kr/5710000/benlService/nltyArtList"
image_api_url = "http://apis.data.go.kr/5710000/benlService/artImgList"
# 검색어 가져오기
search_query = request.GET.get('q', '')
params = { "serviceKey":"gKat/nvnmi8i9zoiX+JsGzCTsAV75gkvU71APhj8FbnH3yX4kiZMuseZunM0ZpcvKZaMD0XsmeBHW8dVj8HQxg==",
"pageNo": "1",
"numOfRows": "5",
"returnType": "json",
"artNm": search_query
}
response = requests.get(base_url, params=params)
if response.status_code == 200:
data = response.json()
art_list = data['response']['body']['items']['item']
# 작품 이미지 정보
for art in art_list:
image_params = {
"serviceKey":"gKat/nvnmi8i9zoiX+JsGzCTsAV75gkvU71APhj8FbnH3yX4kiZMuseZunM0ZpcvKZaMD0XsmeBHW8dVj8HQxg==",
"pageNo": "1",
"numOfRows": "5",
"returnType": "json",
"artNm": art["artNm"] # 'art_name' 대신 'art["artNm"]' 사용
}
image_response = requests.get(image_api_url, params=image_params)
if image_response.status_code == 200:
image_data = image_response.json()
if 'item' in image_data['response']['body']['items']:
art["image_url"] = image_data["response"]["body"]["items"]["item"]["imgUrl"]
else:
art["image_url"] = None
else:
art["image_url"] = None
else:
# 에러 처리
print("API 요청 실패:", response.status_code)
art_list = []
return render(request, 'index.html', {'art_list': art_list, 'search_query': search_query})
is it urls.py path setting
urlpatterns = [# path('', views.index, name='index'), # 예를 들어, index view로 연결path('', views.openapi_view, name='index'),path('search/<str:query>/', views.search, name='search'),]
New contributor
haenshi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.