모델링 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>
'회고록(TIL&WIL)' 카테고리의 다른 글
WIL 2022.08.05 SIDE PRO - KPT 회고 (0) | 2022.08.08 |
---|---|
TIL 2022.07.22 알고리즘 강의 정리 (0) | 2022.07.22 |
TIL 2022.07.18 Toast UI editor Javascript 구현 (0) | 2022.07.18 |
TIL 2022.07.18 AWS S3파일 업로드, IAM 생성 (0) | 2022.07.18 |
TIL 2022.07.14 DRF APIView Pagination (0) | 2022.07.14 |