// 공부 or 휴식 게시판 클릭 시 html에 있는 카테고리 이름을 가져와서 postCategory 함수를 실행함
function handleClickCategory(e) {
const categoryName = e
console.log(categoryName)
postCategory(categoryName);
}
핸들클릭카테고리 함수를 정의했다
categoryName에 html에서 받아온 id값을 담는다
공부 클릭했을 때 study가 들어가고 휴식 클릭했을 때 rest가 들어간다
콘솔로그를 통해 원하는 값이 categoryName에 들어갔음을 확인했다
이제 categoryName에 들어있는 study는 postCategory() 함수의 매개변수로 들어간다
// url에 카테고리 이름을 담기 위한 작업
function postCategory(category_name) {
window.location.href = `${frontend_base_url}/posts/post_list.html?category=${category_name}`
}
이 함수는 url에 카테고리명을 담기 위한 함수다
window.location.href를 통해 위 url로 이동하게 된다
현재 동작은 위 빨간 네모 부분을 클릭했을 때 일어나는 과정이다
// 카테고리별 게시글 리스트 보기
window.onload = async function loadPosts() {
// url에서 카테고리 이름을 가져옴
const urlParams = new URLSearchParams(window.location.search);
const categoryName = urlParams.get("category");
console.log(categoryName)
// 카테고리 이름을 매개변수로 백엔드에서 해당 카테고리의 글들을 가져옴
posts = await getPosts(categoryName)
console.log(posts)
// 게시글 목록 UI
const postCategoryList = document.getElementById("post-category-list")
// 불러온 게시글들을 하나씩 카드 형식으로 붙이는 작업
posts.forEach(post => {
const newCol = document.createElement("div");
newCol.setAttribute("class", "col")
newCol.setAttribute("onclick", `postDetail(${post.pk})`)
const newCard = document.createElement("div")
newCard.setAttribute("class", "card h-100")
newCard.setAttribute("id", `post-${post.pk}`)
newCol.appendChild(newCard)
const postImage = document.createElement("img")
postImage.setAttribute("class", "card-img-top")
if (post.image) {
postImage.setAttribute("src", `${backend_base_url}${post.image}`)
} else {
postImage.setAttribute("src", "https://cdn11.bigcommerce.com/s-1812kprzl2/images/stencil/original/products/426/5082/no-image__12882.1665668288.jpg?c=2")
}
newCard.appendChild(postImage)
const newCardBody = document.createElement("div")
newCardBody.setAttribute("class", "card-body")
newCard.appendChild(newCardBody)
const newCardTile = document.createElement("h5")
newCardTile.setAttribute("class", "card-title")
newCardTile.innerText = post.title
newCardBody.appendChild(newCardTile)
postCategoryList.appendChild(newCol)
});
}
백엔드에서 지정한 url을 부르면 나오는 response를 json 형태로 바꿔서 반환한다
이렇게 카테고리별 게시글 목록 보기가 완성됐다
- 이미지 엑박 오류
위 캡쳐를 보면 알겠지만 문제가 있다
이미지가 없는 게시글은 대체 이미지가 잘 나오고 있는데 정작 이미지를 넣은 게시글은 이미지가 안 나온다
도대체 뭐가 문제인걸까...
이미지 주소도 맞게 잘 인식하고 있는 것을 확인할 수 있었다
DRF에서는 잘만 되던 게 우리 프로젝트에서는 안 된다..
주소를 직접 쳐서 들어가니 이런 오류가 나온다
원래 나와야 하는데....하면서 화면을 뚫어지게 보다가 알았다
url 설정이 안 되어 있다...!!!
이미지 업로드 부분은 다른 팀원분이 하신 건데 settings.py에만 경로를 알려주고 정작 urls.py에는 경로 설정을 안 한 것이었다..! (이렇게 말하는 게 맞나...? 여튼 이미지 업로드 하면 정해둔 폴더에 잘 저장이 되는데 이렇게 page not found가 뜬 건 urls.py가 문제였던 것이었다)
# 프로젝트폴더/urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('posts/', include('posts.urls')),
path('users/', include('users.urls')),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # 바로
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROO) # 이 부분!
아래 2줄이 추가되어 있지 않아서 발생한 문제였다
추가하고 새로고침하니 이미지가 제대로 나오는 걸 확인할 수 있었다!!
- 게시글 pk 값이 undefined 되는 문제
문제가 더 있었다
게시글 목록을 차곡차곡 붙일 때 게시글을 클릭하면 상세페이지를 여는 함수가 실행되게끔 코드를 짰다