将 Ajax 添加到 Django 中的 like 按钮中



我需要一些帮助为喜欢按钮编写ajax代码,而不是每次发布喜欢时刷新。我尝试了几个代码,但都失败了。关于如何在不刷新页面的情况下添加喜欢的任何建议?

这是模板:

<form action="{% url 'score:like_post' post.pk %}" method='POST'>
{% csrf_token %}
{% if user.is_authenticated %}
{% if liked %}
<button type='submit' name='post_id' class= "btn btn-danger btn-sm" value="{{post.id}}"> Unlike </button>                            
{% else %}
<button type='submit' name='post_id' class= "btn btn-primary btn-sm" value="{{post.id}}"> Like </button>                            
{% endif  %}
{% else %}
<small><a href="{% url 'login' %}"> Login</a> to Like </small>
{% endif %}
<strong>{{total_likes}} Likes </strong>                    
</form>      

以下是网址:

path('like/<int:pk>', LikeView, name='like_post'),

以下是视图:

def LikeView(request, pk):
post = get_object_or_404(Post, id=request.POST.get('post_id'))
like = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
like = False
else:
post.likes.add(request.user)
like = True
return redirect('score:post-detail', pk=pk)
class PostDetailView(DetailView):
model = Post
template_name = "post_detail.html"
def get_context_data(self, *args, **kwargs):
context = super(PostDetailView, self).get_context_data()
stuff = get_object_or_404(Post, id=self.kwargs['pk'])
total_likes = stuff.total_likes()
liked = False
if stuff.likes.filter(id=self.request.user.id).exists():
liked = True
context["total_likes"] = total_likes
context["liked"] = liked
return context

这是我尝试过的

<form action="{% url 'score:like_post' post.pk %}" method='POST'>
{% csrf_token %}
{% if user.is_authenticated %}
{% if liked %}
<button type='submit' name='post_id' class= "btn btn-danger btn-sm" Onclick="Onclick()" value="{{post.id}}"> Unlike </button>                            
{% else %}
<button type='submit' name='post_id' class= "btn btn-primary btn-sm" Onclick="Onclick()" value="{{post.id}}"> Like </button>                            
{% endif  %}
{% else %}
<small><a href="{% url 'login' %}"> Login</a> to Like </small>
{% endif %}
<strong>{{total_likes}} Likes </strong>                    
</form> 
<input id= "post_id" type= "hidden" name="name" value= "{object.id}">
<script>
function Onclick(){
var i=document.getElementById(‘post_id’).value
$.ajax({
url:”/ajax/likes/”,
data:{‘i’:i},
datatype:’json’
success:function(data){
document.getElementById(‘like’).innerHTML=data.i
}
})
}
</script>

这是网址:

path('ajax/like/<int:pk>', LikeView, name='like_post'),

以下是视图:

def LikeView(request, pk):
post = get_object_or_404(Post, id=request.POST.get('post_id'))
like = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
like = False
else:
post.likes.add(request.user)
like = True
return redirect('score:post-detail', pk=pk)
  • 这个答案会有所帮助。 https://stackoverflow.com/a/6960586/13499618。
  • 您基本上不希望默认行为,即表单提交和页面刷新,但您想要 Ajax 提交。
  • 你在 django 中实现它就像实现它一样纯 html,因为最终 django 模板呈现为纯 html 文件。

最新更新