반응형
자바스크립트를 활용해 좋아요 구현
- base.html
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
- _like.html
{% if user in article.like_users.all %}
<i class="fas fa-thumbs-down like-button" data-id="{{ article.id }}" style="color : tomato"></i>
{% else %}
<i class="fas fa-thumbs-up like-button" data-id="{{ article.id }}" style="color : black" ></i>
{% endif %}
<span class="like-count-{{ article.id }}"> {{ article.like_users.count }}</span>
{% if user in article.recommend_users.all %}
<a href="{% url 'articles:recommend' article.pk %}"> 추천 취소 </a>
{% else %}
<a href="{% url 'articles:recommend' article.pk %}"> 추천 </a>
{% endif %}
- index.html
{% load static %}
...
<script src="{% static 'articles/js/like.js' %}">
- detail.html
{% load static %}
...
<script src="{% static 'articles/js/like.js' %}">
- like.js
const likeButton = document.querySelectorAll('.like-button')
likeButton.forEach(button =>{
button.addEventListener('click', function(event){
const articleId = event.target.dataset.id
const likeCount = document.querySelector(`.like-count-${articleId}`)
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'
axios.post(`/articles/${articleId}/like/`)
.then(response => {
likeCount.innerText = response.data.count
if(response.data.liked){
event.target.className = 'fas fa-thumbs-up like-button'
event.target.style.color = 'crimson'
} else{
event.target.className = 'fas fa-thumbs-down like-button'
event.target.style.color = 'black'
}
})
})
})
=> csrf를 쓰기 위해선 httpcsrftoken을 사용하면 된다!
- views.py
from django.http import JsonResponse
@login_required
def like(request, article_pk):
# 특정 게시물에 대한 정보
article = get_object_or_404(Article, pk=article_pk)
# 좋아요를 누른 유저에 대한 정보
user = request.user
# 사용자가 게시글의 좋아요 목록에 있으면 지우고 없으면 추가한다.
if user in article.like_users.all():
article.like_users.remove(user)
liked = False
else:
article.like_users.add(user)
liked = True
context = {
'liked' : liked,
'count' : article.like_users.count()
}
return JsonResponse(context)
반응형
'웹 프로그래밍 > [ Django ]' 카테고리의 다른 글
[ Django ] 07. Django relation M:N (profile, follow, paging) (0) | 2020.08.11 |
---|---|
[ Django ] 06. Django relation 1:N 복습 (0) | 2020.08.11 |
[ Django ] 05. Django relation 1:N (사용자 분할) (0) | 2020.08.11 |
[ Django ] 04. Django 로그인/회원가입 구현 (0) | 2020.08.11 |
[ Django ] 03. Django Model-Form 알아보기 (0) | 2020.08.11 |