如何使用ajax在Django中实现类似于Instagram的Like功能



hi我一直在制作一个社交媒体网站,该网站具有类似于Instagram的点赞功能,用户不需要查看个人帖子即可点赞,而是可以直接从主页点赞该帖子,我该怎么做?

我的主要模板:

{% load static %}
{% if user.is_authenticated %}
{% if obj %}
<h1 style="background:skyblue;text-align:center;">Posts</h1>
{% for obj in obj %}
<div style="background:lightgrey;border-radius:5px;margin-bottom:20px;padding:1rem;">
<form method="get">
<input  hidden  value="{{obj.id}}" name="liked_post_id">
</form>
<p>{{obj.user}}</p>
<p>{{obj.name}}</p>
<img height="250px" width="100%" src="{{  obj.image.url  }}" alt="Image ">
<p>{{obj.desription}}</p>
<!--                {% include "like_page.html" %}-->
<button id="btn_1"  name="btn_1" type="submit" value="{{ obj.id }}">like </button>
<span id="like_count">{{obj.like_count}}</span>
<h4>add a comment</h4>
{% include "comments.html" %}
</div>
{% endfor %}
{% else %}
<h1 style="background:skyblue;text-align:center;">No Posts available</h1>
{% endif %}
{% endif %}

我的网址:

from django.urls import path
from .views import index, show, LikeView, addComment
# , likeviewNumber

urlpatterns = [
path("", index, name="home"),
path("show", show, name="show"),
path("like/", LikeView, name="post_like"),
path("comment/",addComment, name="comment" ),
# path('like_num',likeviewNumber )
]

我使用的ajax:

<script src="{% static 'jquery-3.6.0.js' %}" type="text/javascript"></script>
<script>
$(document).on('click','#btn_1',function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'{% url "post_like" %}',
data:{
postid:$('post_id').val(),  // idher mene abhi name=Post_id use kia ha <like_page.html> k ander  /warna yahan par buton ki id use hoti ha #btn_1
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
action:'post'
},
success:function(json){
document.getElementById("like_count").innerHTML=json['result']
console.log(json)
},
error:function(xhr,errmsg,err){
}
});
})

</script>

现在我的主要问题是,我在for循环中显示所有帖子,当单击like按钮时,它在每个帖子中都包含相同的id,但包含单个唯一的post.id值但是ajax认为我点击了第一个按钮,即使我喜欢最后一篇文章我需要一种方式来点赞主页上的每一篇帖子,就像用户在Instagram上点赞一样,而不必制作帖子详细信息页面请帮忙。

抱歉忘了放我一直在使用的视图::

from django.shortcuts import render, HttpResponse, get_object_or_404
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login
from django.urls import reverse_lazy,reverse
from .models import Posts, Comments
from django.http import HttpResponseRedirect, JsonResponse
# Create your views here.
def LikeView(request):
if request.POST.get('action') == 'post':
# post_id = request.POST.get('post_id')
result = ''
id = request.POST.get('postid')
post = get_object_or_404(Posts, id=id)
if request.user in post.like.all():
post.like.remove(request.user)
post.like_count -= 1
result = post.like_count
post.save()
else:
post.like.add(request.user)
post.like_count += 1
result = post.like_count
post.save()
return JsonResponse({'result': result})

型号:

class Posts(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post_name = models.CharField(max_length=150)
desription = models.CharField(max_length=200)
image = models.ImageField(upload_to="images/uploads")
like = models.ManyToManyField(User, related_name="liked", blank=True, default=None)
# like_count = models.BigIntegerField(default=0)
date_added = models.DateField(auto_now_add=True, blank=True)
@property
def like_count(self):
return self.like.count()
def __str__(self):
return self.desription
class Meta:
db_table = "Posts"
ordering = ["date_added"]

您应该使用一个类来触发AJAX操作,然后您可以在data-属性中提供帖子的ID,如下所示:

<button class="likeBtn" data-post-id="{{ obj.id }}">like</button>
<span id="like_count{{ obj.id }}">{{obj.like_count}}</span>

在您的Javascript中:

<script>
$('.likeBtn').on('click', function() {
$.ajax({
type: 'POST',
url: '{% url "post_like" %}',
data: {
postid: $(this).data('postId'),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
action:'post'
},
success: (json) => {
$('#like_count' + $(this).data('postId')).html(json['result'])
console.log(json)
},
error: (xhr, errmsg, err) => {
console.error(xhr, errmsg, err)
}
})
})
</script>

相关内容

  • 没有找到相关文章

最新更新