Changed Upvote and Downvote Functionality to be unique

This commit is contained in:
2024-04-12 18:00:52 -04:00
parent 5d4551e4fa
commit af9340c54f
3 changed files with 48 additions and 4 deletions

View File

@@ -0,0 +1,32 @@
# Generated by Django 4.2.11 on 2024-04-12 21:47
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("api", "0006_file_points_peeruser_points"),
]
operations = [
migrations.RemoveField(
model_name="file",
name="points",
),
migrations.AddField(
model_name="file",
name="downvotes",
field=models.ManyToManyField(
related_name="downvoted_file", to=settings.AUTH_USER_MODEL
),
),
migrations.AddField(
model_name="file",
name="upvotes",
field=models.ManyToManyField(
related_name="upvoted_file", to=settings.AUTH_USER_MODEL
),
),
]

View File

@@ -58,7 +58,13 @@ class File(models.Model):
Course, on_delete=models.SET_NULL, null=True, related_name="files"
)
created_at = models.DateTimeField(auto_now_add=True)
points = models.IntegerField(default=0, blank=False)
upvotes = models.ManyToManyField(PeerUser, related_name="upvoted_file")
downvotes = models.ManyToManyField(PeerUser, related_name="downvoted_file")
@property
def points(self):
return self.upvotes.count() - self.downvotes.count()
def __str__(self):
return self.filename

View File

@@ -112,11 +112,14 @@ class UpvoteFile(APIView):
permission_classes = [IsAuthenticated]
def post(self, request, file_id):
user = request.user
update_user_ip(request)
try:
file = File.objects.get(id=file_id)
file.points += 1
if file.downvotes.contains(user):
file.downvotes.remove(user)
file.upvotes.add(user)
file.save()
return Response(
{"msg": f"Upvoted {file.filename}", "file_points": file.points},
@@ -135,11 +138,14 @@ class DownvoteFile(APIView):
permission_classes = [IsAuthenticated]
def post(self, request, file_id):
user = request.user
update_user_ip(request)
try:
file = File.objects.get(id=file_id)
file.points -= 1
if file.upvotes.contains(user):
file.upvotes.remove(user)
file.downvotes.add(user)
file.save()
return Response(
{"msg": f"Downvoted {file.filename}", "file_points": file.points},