models:
from django.db import models
from django.contrib.auth.models import User
class Video(models.Model):
likes = models.ManyToManyField(User, blank=True, related_name='likes')
dislikes = models.ManyToManyField(User, blank=True, related_name='dislikes')
views:
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Video
from django.views import View
from django.http import HttpResponseRedirect
from django.urls import revers
class AddLike(LoginRequiredMixin, View):
def post(self, request, pk, *args, **kwargs):
post = Video.objects.get(pk=pk)
is_dislike = False
for dislike in post.dislikes.all():
if dislike == request.user:
is_dislike = True
break
if is_dislike:
post.dislikes.remove(request.user)
is_like = False
for like in post.likes.all():
if like == request.user:
is_like = True
break
if not is_like:
post.likes.add(request.user)
if is_like:
post.likes.remove(request.user)
return HttpResponseRedirect(reverse('video', args=[str(pk)]))
class AddDislike(LoginRequiredMixin, View):
def post(self, request, pk, *args, **kwargs):
post = Video.objects.get(pk=pk)
is_like = False
for like in post.likes.all():
if like == request.user:
is_like = True
break
if is_like:
post.likes.remove(request.user)
is_dislike = False
for dislike in post.dislikes.all():
if dislike == request.user:
is_dislike = True
break
if not is_dislike:
post.dislikes.add(request.user)
if is_dislike:
post.dislikes.remove(request.user)
return HttpResponseRedirect(reverse('video', args=[str(pk)]))
urls
from django.urls import path
from . import views
urlpatterns = [
path('<int:pk>/like/', AddLike.as_view(), name='like'),
path('<int:pk>/dislike/', AddDislike.as_view(), name='dislike')
]
html:
<form method="post" action="{% url 'like' video.pk %}">
{% csrf_token %}
<div style="margin-top: 10px; width: 30px; height: 30px; margin-left: 950px;">
<input type="hidden" name="text" value="{{ request.path }}">
<button style="background: transparent; border: none; box-shadow: none;" type="submit">
<img src="{% static 'images/like.png' %}">
<span>{{ video.likes.all.count }}</span>
</button>
</div>
</form>
<form method="post" action="{% url 'dislike' video.pk %}">
{% csrf_token %}
<div style="margin-top: -30px; width: 30px; height: 30px; margin-left: 980px;">
<input type="hidden" name="text" value="{{ request.path }}">
<button style="background: transparent; border: none; box-shadow: none;" type="submit">
<img src="{% static 'images/dislike.png' %}">
<span>{{ video.dislikes.all.count }}</span>
</button>
</div>
</form>