my problem is i make like button with ajax but it only works for first post i need to refresh page for other posts
i'm a little new to this job, can you check where the error is caused?
Like button works but I need to refresh the page
could this be the problem id='...' or can html be affected by other scripts
my model
mymodels.py
class Post(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
content = models.ManyToManyField(PostFileContent, related_name='contents')
caption = models.TextField(max_length=1500, verbose_name='Caption')
posted = models.DateTimeField(auto_now_add=True)
tags = models.ManyToManyField(Tag, related_name='tags')
user = models.ForeignKey(User, on_delete=models.CASCADE)
likes = models.ManyToManyField(
User, related_name='like', default=None, blank=True)
like_count = models.BigIntegerField(default='0')
def get_absolute_url(self):
return reverse('postdetails', args=[str(self.id)])
def __str__(self):
return str(self.id)
myviews.py
@login_required(login_url="login")
def like(request):
if request.POST.get('action') == 'post':
result = ''
id = request.POST.get('postid')
post = get_object_or_404(Post, id=id)
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
post.like_count -= 1
result = post.like_count
post.save()
else:
post.likes.add(request.user)
post.like_count += 1
result = post.like_count
post.save()
return JsonResponse({'result': result, })
mybutton.html
{% if request.user.is_authenticated %}
<button style="margin-top: 10px;" class="btn btn-light like_button_true like-button" value="{{ post_item.id }}">
{% if post_item.like_count >= 2 %}
<img style="width: 32px; height:32px;" src="{% static 'img/likeTrue.png' %}" />
{% else %}
<img style="width: 32px; height:32px;" src="{% static 'img/likeFalse.png' %}" />
{% endif %}
<br>
<span id="like_count_{{ post_item.id }}">{{post_item.like_count}}</span>
</button>
{% endif %}
myscript
<script>
$(document).on('click', '.like-button', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "like" %}',
data: {
postid: $(this).val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success: function (json) {
document.getElementById("like_count_" + $(this).val()).innerHTML = json['result']
},
error: function (xhr, errmsg, err) {
}
});
})
</script>
Here i see more problem in project, but of course you have also a problem with the same id on html page. id for html element should be unique.
{% if request.user.is_authenticated %}
<button style="margin-top: 10px;" class="btn btn-light like_button_true like-button" value="{{ post_item.id }}">
{% if post.like_count >= 2 %}
<img style="width: 32px; height:32px;" src="{% static 'img/likeTrue.png' %}" />
{% else %}
<img style="width: 32px; height:32px;" src="{% static 'img/likeFalse.png' %}" />
{% endif %}
<br>
<span id="like_count_{{ post.id }}">{{post_item.like_count}}</span>
</button>
{% endif %}
and in script:
<script>
...
success: function (json) {
document.getElementById("like_count_" + $(this).val()).innerHTML = json['result']
},
...
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.