Hi, so i have succesfully added a like button and it likes and unlikes a post succesfully.
But the problem is that it loads the home page everytime someone likes or unlikes a post.
Now ajax/Async fetch can do it without reloading the post, but how can i achive it ?
My models File
from django.db import models
from django.utils import timezone
from django_extensions.db.fields import AutoSlugField
class retailer(models.Model):
links = models.CharField(max_length=9999, unique = True)
title = models.CharField(max_length=300)
slug = AutoSlugField(populate_from=['title'])
date_posted = models.DateTimeField(default=timezone.now)
no_of_likes = models.IntegerField(default=0)
def __str__(self):
return self.title
def count(self):
return self.count()
class LikePost(models.Model):
post_id = models.CharField(max_length=500)
username = models.CharField(max_length=100)
def __str__(self):
return self.username
My Views File
def home(request):
prods = retailer.objects.all()
context = {
"prods":prods,
}
if request.method == 'POST':
username = request.user.username
post_id = request.POST.get("item-id")
post = retailer.objects.get(id=post_id)
like_filter = LikePost.objects.filter(post_id=post_id, username=username).first()
if like_filter == None:
new_like = LikePost.objects.create(post_id=post_id, username=username)
new_like.save()
post.no_of_likes+=1
post.save()
return render(request, 'testing/home.html', context)
else:
like_filter.delete()
post.no_of_likes-=1
post.save()
return render(request, 'testing/home.html', context)
return render(request, 'testing/home.html', context)
My HTML Template File
<form action = "" method = "POST">
{% csrf_token %}
<button type="submit" name = "item-id" value = "{{item.id}}" class = 'btn btn-primary btn-sm'> {{item.no_of_likes}} Like </button>
</form>
Thanks