카테고리 없음

boolean 을 사용한 클릭 이벤트(좋아요, 팔로우)

abccoco 2022. 7. 20. 20:19

백엔드에서 boolean 을 사용해 좋아요, 팔로우 버튼을 누르면 이벤트가 생기도록 해보자.

프로젝트 특성상 좋아요, 팔로우 버튼을 누르면 window.location.reload() 을 통해 이벤트가 반영되도록 하였다.

before
after


백엔드

models.py

먼저 코드의 이해를 위해 models.py 의 모델과 필드 사진을 보고 시작해보자.

User 모델 안에 필트로 follow 와 like 가 있다.

m to m 필드는 기본적으로 symmetrical=True 이기 때문에 False로 바꾸어 주어서 좋아요 버튼을 누르면

누른 사람, 받는 사람 모두의 id 가 추가 되지 않도록 했다.

이제 views.py 로 돌아가서 boolean 코드를 작성해 보도록 하자.

 

views.py

views.py 에서는 db에 저장된 좋아요와 팔로우의 id를 찾아서 follow id 가, user id 안에 있다면 True를 보내주는 식으로 구현했다.

그렇게 하기 위해서 user의 serializer 안에 data로 들어가서 해당 유저의 좋아요, 팔로우의 id를 뽑아오는 작업이 필요했다.

그리고 데이터가 OrderedDict 형식으로 저장 되어 있어서 반복문을 리스트 형태로 저장해주는 리스트 컴프리헨션을 사용했다.

# OrderedDict
OrderedDict([('A', 1), ('B', 2), ('C', 3)])

db에 저장된 데이터

 views.py 코드

class UserInfoView(APIView):
    permission_classes = [permissions.IsAuthenticated]
	
    # owner_id 는 좋아요를 누른 곳의(마이룸 주인) 아이디이다.
    def get(self, request, owner_id):
        user_id = request.user.id    
        user = UserInfoModel.objects.filter(user_id=owner_id)
        profile = UserInfoModelSerializer(user, many=True)
    
        if request.user:
            like_data = profile.data[0]["user"]
            like_user_id = [x['id'] for x in profile.data[0]["user"]["like"]]

            follow_data = profile.data[0]["user"]
            follow_user_id = [x['id'] for x in profile.data[0]["user"]["follow"]]
            
            # 데이터 안에 follow_user, like_user 라는 이름으로 Ture/Fales 를 보내준다.
            # 보내준 데이터를 프론트에서 받아서 if문을 사용해 조건 별로 temp 를 붙여주려 한다.
            follow_data["follow_user"] = bool(user_id in follow_user_id)
            like_data["like_user"] = bool(user_id in like_user_id)
            return Response(profile.data, status=status.HTTP_200_OK)

 

프론트 엔드

# boolean 의 정보가 담긴 데이터를 가저온다.
const like_user = data[i]["user"]["like_user"]
const follow_user = data[i]["user"]["follow_user"]


...
    if (follow_user == true) {
        content_temp = `
        <script>
            $(".btn_like").click(function () {
                $(this).toggleClass("done");
            })
        </script>
        <div id="buttons_div" style="float:right;">
            <button class="fs-3 btn_like badge rounded-pill" onclick="follow()" style="color: inherit; padding: 7px;"><i class="bi bi-person-plus"></i></button>
        </div>
        `
        $("#show_profile").append(content_temp)
    }
    else {
        content_temp = `
        <script>
            $(".btn_like").click(function () {
                $(this).toggleClass("done");
            })
        </script>
        <div id="buttons_div" style="float:right;">
            <button class="fs-3 btn_like badge rounded-pill" onclick="follow()" style="padding: 7px;"><i class="bi bi-person-plus"></i></button>
        </div>
        `
        $("#show_profile").append(content_temp)

 

좋아요 버튼 누를 때의 함수

// 좋아요
async function like() {
    let owner_id = window.location.search.split('=')[1]
    const contentData = {
        content: document.getElementById('guestBookData').value,
    }

    const response = await fetch(`${backend_base_url}/myroom/like/${owner_id}/`, {
        headers: {
            Authorization: 'Bearer ' + localStorage.getItem('access'),
            Accept: "application/json",
            'Content-type': 'application/json'
        },
        withCredentials: true,
        method: 'POST',

        body: JSON.stringify(contentData)
    }
    )
    response_json = await response.json()
    window.location.reload(true);
}

 

 


결과