navbar를 위와 같은 이미지로 만들어서 목록별로 정렬을 할 수 있도록 만드려고 한다.
class LiquorListView(ListCreateAPIView):
# 인증된 회원(회원or관리자)만 가능 or 누구나 이용 가능
permission_classes = [IsAuthenticatedOrReadOnly]
# 주류 목록 조회
serializer_class = LiquorListSerializer
pagination_class = RecordPagination
def get_queryset(self):
liquor = Liquor.objects.all()
# classification 필터링 추가
classification = self.request.query_params.get('classification', 'all')
if classification != 'all':
liquor = liquor.filter(classification=classification)
return liquor
view에서 적용하고 있는 코드를 수정해서 params값으로
분류를 받아 분류 값이 주어지면 그에 맞는 목록을 보여주려고 했다.
let nextUrl = 'http://localhost:8000/api/v1/liquor/';
let isLoading = false;
// URL에서 쿼리 파라미터 가져오기 함수
function getQueryParam(param) {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(param);
}
// API에서 주류 정보를 가져오는 함수
async function fetchLiquors(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('서버 상태가 이상합니다.');
}
return await response.json();
} catch (error) {
console.error('error:', error);
}
}
// 주류 정보를 화면에 표시하는 함수
function displayLiquors(liquors) {
const liquorList = document.getElementById('liquor-list');
liquors.forEach(liquor => {
const liquorItem = document.createElement('div');
liquorItem.className = 'liquor-item';
liquorItem.innerHTML = `
<img src="${liquor.img}" alt="${liquor.name}" class="liquor-img" data-id="${liquor.id}">
<h3>${liquor.name}</h3>
<p>Price: ${liquor.price} 원</p>
`;
liquorList.appendChild(liquorItem);
});
// 클릭 시 상세 페이지로 이동하는 이벤트 추가
document.querySelectorAll('.liquor-img').forEach(img => {
img.addEventListener('click', function () {
const liquorId = this.getAttribute('data-id');
window.location.href = `/pages/liquor_detail.html?id=${liquorId}`; // 상세 페이지로 이동
});
});
}
// 더 많은 주류 데이터를 로드하는 함수 (페이지네이션 적용)
async function loadMoreLiquors() {
if (isLoading || !nextUrl) return;
isLoading = true;
document.getElementById('loading').style.display = 'block';
const classification = getQueryParam('classification');
let url = new URL(nextUrl, window.location.origin);
if (classification) {
url.searchParams.set('classification', classification);
}
try {
const data = await fetchLiquors(url.toString());
if (data && data.data) {
displayLiquors(data.data.records);
nextUrl = data.data.next;
}
} catch (error) {
console.error('error:', error);
} finally {
isLoading = false;
document.getElementById('loading').style.display = 'none';
}
}
// 화면 하단 근처에 도달했는지 체크하는 함수
function isNearBottom() {
return window.innerHeight + window.scrollY >= document.body.offsetHeight - 300;
}
// 스크롤 이벤트 핸들러
function handleScroll() {
if (isNearBottom()) {
loadMoreLiquors();
}
}
// 초기 주류 데이터를 로드
loadMoreLiquors();
// 스크롤 이벤트 추가
window.addEventListener('scroll', handleScroll);
html 파일에서도 쿼리를 추가하는 부분을 넣어주고,
liquor_list를 요청했을 때 url에서 쿼리 파라미터를 가져와 백엔드에 함께 넘겨주려고 했다.
위에 코드에 에러는 나지 않았지만 이미지를 불러오지 못해서 이유를 찾았다.
url에는 값이 영문으로 적혀있는 것에 비해서 DB에는 한글로 값이 들어가 있어서 이미지가 나오지 않았다.
DB의 값을 나중에 바꾸기로 하고 우선 테스트 데이터를 넣어서 잘 나오는지 확인을 해보려고 했다.
테스트 데이터가 잘 나오는 것을 확인하고 나니 걱정이 좀 덜어졌지만 페이지네이션이 제대로 적용되는지는 모르겠다.
다음에 DB에 있는 값을 수정하고 추가적으로 로직을 확인해 봐야겠다.
'웹 개발' 카테고리의 다른 글
[프로젝트] s3 경로 설정 (0) | 2024.10.16 |
---|---|
[프로젝트] 배포 준비 (0) | 2024.10.15 |
[프로젝트] 커서 페이지네이션 (0) | 2024.10.11 |
[프로젝트] API key를 숨기기 위한 처리 (2) | 2024.10.09 |
[프로젝트] 카카오 지도 API로 주변 주류 매장 출력 (0) | 2024.10.07 |