I have 2 models:
class User(AbstractUser):
pass
class Post(models.Model):
poster = models.ForeignKey('User', on_delete=models.CASCADE, related_name='posts')
body = models.TextField()
likes = models.IntegerField(default=0)
likers = models.ManyToManyField('User', blank=True, null=True, related_name='liked_posts')
Post model has a manytomany field to User model. I try to add a user object to the field with the view function below but it doesn’t work. Basically, when I check the post in the admin page, the user is not added to the likers.
The view I user to add the object:
@csrf_exempt
def likepost(request, like, post_id):
if (request.method == 'PUT'):
post = Post.objects.get(pk=post_id)
if like:
post.likers.add(request.user)
else:
post.likers.remove(request.user)
post.save()
print(post.likers)
return HttpResponse(status=204)
else:
return JsonResponse({
'error': 'PUT request required.'
}, status=400)
Url path:
path('likepost/<int:like>/<int:post_id>', views.likepost, name='likepost')
JavaScript:
fetch(`likepost/${likeValue}/${postId}`, {
method: 'PUT'
});