본문 바로가기

회고록(TIL&WIL)

TIL 2022.07.21 Django 북마크(좋아요)기능

모델링 ManyToMany

# article/models.py
class Project(models.Model):
    ...
    bookmark = models.ManyToManyField(User, related_name="bookmarks", blank=True)
    ...

API 작성

# project/<int:project_id>/bookmark/
class BookmarkAPIView(APIView):
    # 북마크 클릭 시
    def post(self, request, project_id):
        project = Project.objects.get(id=project_id)
        bookmark = project.bookmark.all()
        if request.user in bookmark:
            project.bookmark.remove(request.user)
            return Response({"msg:": "북마크 해제 완료!"})
        else:
            project.bookmark.add(request.user)        
        return Response({"msg": "북마크 등록 완료!"})

FE JavaScript

<script>
    function viewer() {
        const Editor = toastui.Editor;

        // 게시물 상세 조회 (id=54인 게시물 테스트용)
        fetch(`${backend_base_url}/project/54`,{
            headers: {
                Accept: "application/json",
                'content-type': "application/json",
                "Authorization": "Bearer " + localStorage.getItem("access")
            },
            method: 'GET',
        })
        .then(response=>{
            return response.json()
        })
        .then(json=>{
            // toast ui viewer
            const viewer = Editor.factory({
                el: document.querySelector('#viewer'),
                viewer: true,
                height: '500px',
                initialValue: json["content"]
            });

            // 북마크 버튼
            const payload = JSON.parse(localStorage.getItem("payload"));
            const bookmark_div = document.querySelector("#bookmark");
            bookmark_div.innerHTML = ``
            const bookmark_btn = document.createElement('div');
            bookmark_btn.className = 'bookmark_btn';
            
            if (json["bookmark"].includes(payload.user_id)){
                bookmark_btn.innerHTML = `<button type="button" onclick="bookmark(${json["id"]})">♥</button>`
            } else {
                bookmark_btn.innerHTML = `<button type="button" onclick="bookmark(${json["id"]})">♡</button>`
            }
            bookmark_div.append(bookmark_btn)

        })
    }
    viewer()

    function bookmark(project_id) {
        fetch(`${backend_base_url}/project/${project_id}/bookmark/`,{
            headers: {
                Accept: "application/json",
                'content-type': "application/json",
                "Authorization": "Bearer " + localStorage.getItem("access")
            },
            method: 'POST',
        })
        viewer()
    }
    </script>