class Article(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
like_users = models.ManyToManyField(settings.AUTH_USER_MODEL)
title = models.CharField(max_length=10)
content = models.TextField()
class Article(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) like_users=models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='like_articles')
title = models.CharField(max_length=10)
content = models.TextField()
article.user
article.like_users
user.article_set
user.like_articles
app_name = 'articles'
urlpatterns = [
path('', views.index, name='index'),
path('<int:article_pk/likes/', views.likes, name='likes'),
]
def likes(request,article_pk) :
#어떤 객체에 좋아요가 눌렸는지 확인
article = get_object_or_404(Article, pk=article_pk)
#누르는게 무조건 좋아요를 활성화하는 것은 아님 좋아요를 2번 누르면 취소되게 구현할 수 있음
#이 게시글에 좋아요를 누른 유저 목록에 현재 요청하는 유저가 있다면 좋아요 취소
if request.user in article.like_users.all() :
article.like_users.remove(request.user)
#아니면 좋아요
else :
article.like_users.add(request.user)
return redirect('articles:index')
def likes(request,article_pk) :
article = get_object_or_404(Article, pk=article_pk)
if article.like_users.filter(pk=request.user.pk).exists() :
article.like_users.remove(request.user)
else :
article.like_users.add(request.user)
return redirect('articles:index')
<form action="{% url 'articles:likes' article.pk %}" method='POST'>
{% csrf_token %}
<input type="submit">
</form>
class Meta :
model = Article
exclude = ('user','like_users',)
<div>
<form action="{% url 'articles:likes' article.pk %}" method='POST'>
{% csrf_token %}
{% if user in article.like_users.all %}
<button class="btn" style="background-color : transparent;">
<i class="fa regular fa-heart" style="color:red"></i>
</button>
{% else %}
<button class="btn" style="background-color : transparent;">
<i class="fa regular fa-heart" style="color:black" ></i>
</button>
{% endif %}
</form>
</div>