하루일문

[Django] 여러 감정 표현하기 본문

django

[Django] 여러 감정 표현하기

support_u 2023. 5. 1. 10:16

Models.py


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_article')
    emote_users = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='emote_articles', through='Emote')
    title = models.CharField(max_length=80)
    content = models.TextField(null=False)

class Emote(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    emotion = models.CharField(max_length=10)

Urls.py

path('<int:article_pk>/emotes/<int:emotion>/', views.emotes, name='emotes'),

 

Views.py

# 감정 추가 삭제 가능
EMOTIONS = [
    {'label': '재밌어요', 'value': 1},
    {'label': '싫어요', 'value': 2},
    {'label': '화나요', 'value': 3},
]

def detail(request, article_pk):
    article = Article.objects.get(pk=article_pk)
 # 디테일에 이모션을 넣어주는 부분
    emotions = []
    for emotion in EMOTIONS:
        label = emotion['label']
        value = emotion['value']
        count = Emote.objects.filter(article=article, emotion=value).count()
        exist = Emote.objects.filter(article=article, emotion=value, user=request.user)
        emotions.append(
            {
                'label': label,
                'value': value,
                'count': count,
                'exist': exist,
            }
        )

    comments = article.comment_set.all()
    comment_form = CommentForm()
    context = {
        'emotions': emotions,
        'article': article,
        'comments': comments,
        'comment_form': comment_form,
    }
    return render(request, 'articles/detail.html', context)


# 이모션 표현 부분
@login_required
def emotes(request, article_pk, emotion):
    article = Article.objects.get(pk=article_pk)
    filter_query = Emote.objects.filter(
        article=article,
        user=request.user,
        emotion=emotion,
    )
    if filter_query.exists():
        filter_query.delete()
    else:
        Emote.objects.create(article=article, user=request.user, emotion=emotion)

    return redirect('articles:detail', article_pk)

Template

{% for emotion in emotions %}
<div>
  {% if request.user.is_authenticated %}
  {{emotion.queryset}}
    <form action="{% url 'articles:emotes' article.pk emotion.value %}" method="POST">
      {% csrf_token %}
      {% if emotion.exist %}
        <input type="submit" value="{{emotion.label}} 취소">
      {% else %}
        <input type="submit" value="{{emotion.label}}">
      {% endif %}
    </form>
  {% else %}
    <button disabled="disabled">{{emotion.label}}</button>
  {% endif %}
  <p>
    게시글 {{emotion.label}} 수 -
    {{ emotion.count }}
  </p>
</div>
{% endfor %}