Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

MyPrograming

인스타그램 클론코딩 (좋아요) 본문

Python/python 클론코딩

인스타그램 클론코딩 (좋아요)

SeongWon 2020. 4. 20. 17:20
반응형

2. 좋아요 기능 구현

urls.py

re_path(r'^like/(?P<post_id>\d+)/$', likeView, name='like'),

 

likeView.py

def likeView(request, post_id):
    user = request.user

    cursor = connection.cursor()

    is_like = "SELECT COUNT(*)"
    is_like += " FROM like_post"
    is_like += " WHERE user_id = (%s) and post_id = (%s)"

    is_like_result = cursor.execute(is_like, (user.username, post_id))
    is_like_datas = cursor.fetchall()

    if is_like_datas[0][0] == 0:
        like_sql = "INSERT INTO like_post(post_id, user_id)"
        like_sql += " VALUES (%s, %s)"

        like_sql_result = cursor.execute(like_sql, (post_id, user.username))
        like_check = 1

    elif is_like_datas[0][0] == 1:
        unlike_sql = "DELETE"
        unlike_sql += " FROM like_post"
        unlike_sql += " WHERE user_id = (%s) AND post_id = (%s)"

        unlike_sql_result = cursor.execute(unlike_sql, (user.username, post_id,))
        like_check = 0

    like_count = "SELECT COUNT(user_id)"
    like_count += " FROM like_post"
    like_count += " WHERE post_id = (%s)"

    like_count_result = cursor.execute(like_count, (post_id,))
    like_count_datas = cursor.fetchall()
    likeCount = like_count_datas[0][0]

    connection.commit()
    connection.close()



    return HttpResponse(json.dumps({"like_check": like_check, "likeCount": likeCount}), content_type="application/json")

 

main.html

{% if cate.is_like == 0  %}
 <i class="far fa-heart" onclick="like(this, '{{ cate.post_id }}')"></i>
{% endif %}
{% if cate.is_like == 1 %}
 <i class="fas fa-heart" onclick="like(this, '{{ cate.post_id }}')"></i>
{% endif %}

좋아요 버튼에 해당하는 html 코드이다. 이것도 팔로우 / 언팔로우와 같이 현재 로그인된 유저가 해당 게시글에 대하여 좋아요를 눌렀는지, 이미 누른 상태인지를 판단하기 위해 경우에 따라 0과 1의 데이터를 주어서 구분하였다.

 

훈이의 게시글 하나를 보면 현재 나는 이 게시글에 좋아요를 누르지 않았기 때문에 빈 하트로 나타난다.

물론 좋아요 데이터테이블에도 들어가있지 않은 상태이다.


좋아요 기능 또한, 팔로우와 같이 일부분만 재로드되는 것이 효율적이기 때문에 Ajax를 이용하였다.

function like(elm, n) {
    $.ajax({
      url: "{% url 'instagram:like' 1  %}". replace('1',n),
      data: {'csrfmiddlewaretoken': '{{ csrf_token}}'},
      type: "POST",
      dataType: "json",
      success: function(response) {
        if (response.like_check == 0) {
          $(elm).attr("class", "far fa-heart");
          $(elm).attr("onclick", "like(this, '" + n + "')");
          $(elm).parent().parent().next().children().first().children().text(response.likeCount);
        }
        else if (response.like_check ==1 ) {
          $(elm).attr("class", "fas fa-heart");
          $(elm).attr("onclick", "like(this, '" + n + "')");
          $(elm).parent().parent().next().children().first().children().text(response.likeCount);
        }
      },
      error: function(xhr){
        alert("좋아요를 하는 과정에서 에러가 발생하였습니다.");
      }
    });
  }

훈이의 게시글에 좋아요를 누른 뒤, 하트가 채워진 색으로 변하였고, 좋아요의 수도 1이 증가하였다.

내 계정이 훈이의 게시글 (post_id = 21)을 좋아요하여 데이터 테이블에 추가되었다.

반응형