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:34
반응형

3. 콜렉션 (공유) 기능구현

urls.py

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

게시글의 주키인 id만 필요하므로 "d+" 패턴을 주었다.

 

collectionView.py

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

    cursor = connection.cursor()

    is_collection = "SELECT COUNT(*)"
    is_collection += " FROM collection"
    is_collection += " WHERE user_id = (%s) AND post_id = (%s)"

    is_collection_result = cursor.execute(is_collection, (user.username, post_id))
    is_collection_datas = cursor.fetchall()

    if is_collection_datas[0][0] == 0:
        collection_sql = "INSERT INTO collection(post_id, user_id)"
        collection_sql += "VALUES ((%s), (%s))"

        collection_sql_result = cursor.execute(collection_sql, (post_id, user.username,))
        collection_check = 1

    elif is_collection_datas[0][0] == 1:
        uncollection_sql = "DELETE"
        uncollection_sql += " FROM collection"
        uncollection_sql += " WHERE user_id = (%s) AND post_id = (%s)"

        uncollection_sql_result = cursor.execute(uncollection_sql, (user.username, post_id,))
        collection_check = 0

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

 

main.html

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

좋아요와 같이 현재 콜렉션을 한 상태에 따라 버튼의 색깔 여부를 나누게 하였다.

 

현재 훈이의 게시글을 콜렉션하지 않았기 떄문에 빈 하트 상태로 나타난다.


이 또한 좋아요와 같이 일부분만 재로드되는 것이 효율적이기 때문에 Ajax를 통해 구현한다.

function collection(elm, n){
    $.ajax({
      url: "{% url 'instagram:collection' 1 %}". replace('1',n),
      data: {'csrfmiddlewaretoken': '{{ csrf_token }}'},
      dataType: 'json',
      type: 'POST',
      success: function(response){
        if (response.collection_check == 0) {
          $(elm).attr("class", "far fa-bookmark");
          $(elm).attr("onclick", "collection(this, '"+ n +"')");
        }
        else if (response.collection_check == 1) {
          $(elm).attr("class", "fas fa-bookmark");
          $(elm).attr("onclick", "collection(this, '"+ n +"')");
        }
      },
      error: function(xhr) {
        alert("콜렉션을 하는 과정에서 에러가 발생하였습니다.");
      }
    });
  }

콜렉션 버튼을 누른후, 해당 버튼의 색깔이 채워진 것을 확인할 수 있다.

새롭게 콜렉션한 훈이의 게시글이 데이터베이스에 추가 된것을 확인하였다. 

또한 콜렉션된 게시글은 나의 유저페이지에서 "저장됨"이라는 카테고리에 새롭게 추가되도록 하였다.

반응형