S
S
serhiops2022-02-20 17:41:46
Django
serhiops, 2022-02-20 17:41:46

How to make a like system in Django?

I want to add the ability to put likes on the site. I read a lot of information, but I did not find a definite answer to the question. Do I need to write a form? How to arrange the view correctly so that the user can like it only once? And so on. Can you explain how it all happens and preferably with code examples (the ability to add publications and register already exists)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robert Goodman, 2022-02-21
@Robertgoodman

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>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question