코딩공부/Python Django

KKU likelion django project (4)

integerJI 2020. 1. 2. 11:42

---
title: "LikeLion KKU like class"
date: 2019-10-09 00:00:00 -0400
categories: jekyll update
---

# like 추가하기.

 - 유저는 여러 개의 메모에 좋아요를 할 수 있고, 메모는 여러 유저로부터 좋아요를 받을 수 있다.

### models.py 추가 및 수정

```
from django.contrib.auth.models import User

name_id = models.ForeignKey(User, on_delete = models.CASCADE)
likes = models.ManyToManyField(User, related_name='likes')

@property
def total_likes(self):
  return self.likes.count()
```

#### property란?

- 기본적으로 property는 어떤 값을 나타낸다. 그런데 이 값이 다른 값과 연관을 가지고 있을 때 property라고 부릅니다.

### views.py 추가
```
try:
    from django.utils import simplejson as json
except ImportError:
    import json
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST

@login_required
@require_POST
def like(request):
    if request.method == 'POST':
        user = request.user 
        post_id = request.POST.get('pk', None)
        post = Post.objects.get(pk = post_id)

        if post.likes.filter(id = user.id).exists():
            post.likes.remove(user) 
            message = '좋아요 취소'
        else:
            post.likes.add(user)
            message = '좋아요'

    context = {'likes_count' : post.total_likes, 'message' : message}
    return HttpResponse(json.dumps(context), content_type='application/json')
    
```

### urls.py 추가
```
path('like', views.like, name='like'),
```

### detail.html 추가
```



- 하단



```


 ### 참고자료 1 [ajax 통신을 이용한 좋아요 기능]
 ### 참고자료 2 [ajax를 사용하는 이유]
 ### 예시 1 [예시 1]
 ### 예시 2 [예시 2]

[ajax 통신을 이용한 좋아요 기능]: https://wayhome25.github.io/django/2017/03/01/django-99-my-first-project-4/
[ajax를 사용하는 이유]: https://wayhome25.github.io/django/2017/06/25/django-ajax-like-button/

[예시 1]: https://loving992.herokuapp.com/
[예시 2]: http://siwabada.pythonanywhere.com/

'코딩공부 > Python Django' 카테고리의 다른 글

KKU likelion django project (5) 번외  (0) 2020.01.02
KKU likelion django project (5)  (0) 2020.01.02
KKU likelion django project (3)  (0) 2020.01.02
KKU likelion django project (2)  (0) 2020.01.02
KKU likelion django project (1)  (0) 2020.01.02