
本文旨在帮助开发者使用 Django 框架和 JavaScript 实现一个流畅、无需页面刷新的点赞/取消点赞功能。我们将探讨如何正确处理图标切换、避免点赞计数在所有帖子中同步更新的问题,并提供一个更简洁、高效的代码实现方案,包括前后端代码示例和注意事项。
首先,我们需要在 HTML 模板中渲染帖子列表,并为每个帖子添加一个点赞/取消点赞按钮。关键在于,在页面初次加载时,根据用户是否已点赞该帖子,正确显示相应的图标。
{% for post in posts %}
<p>{{post.title}}</p>
<p>{{post.body}}</p>
<button id="like_button_{{post.id}}" onclick="LikeOrUnlike('{{post.id}}')">
{% if post.id in user_liked_posts %}
<i class="fa-solid fa-thumbs-down"></i>
{% else %}
<i class="fa-solid fa-thumbs-up"></i>
{% endif %}
</button>
<span id="likes_count_{{post.id}}">{{ post.postLiked.count }}</span> Likes
{% endfor %}
<script>
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const LikeOrUnlike = async (id) => {
const thumbs_up = '<i class="fa-solid fa-thumbs-up"></i>';
const thumbs_down = '<i class="fa-solid fa-thumbs-down"></i>';
const csrftoken = getCookie("csrftoken");
const user = "{{request.user.id}}";
const response = await fetch("/post/like/", {
method: "POST",
headers: {
"X-CSRFToken": csrftoken,
'Content-Type': 'application/json'
},
body: JSON.stringify({ user_id: user, post_id: id }),
});
const data = await response.json();
const like_button_element = document.getElementById(
`like_button_${id}`
);
const likes_count_element = document.getElementById(
`likes_count_${id}`
);
let num_likes = parseInt(likes_count_element.innerHTML);
if (data.liked) {
like_button_element.innerHTML = thumbs_down;
likes_count_element.innerHTML = num_likes + 1;
} else {
like_button_element.innerHTML = thumbs_up;
likes_count_element.innerHTML = num_likes - 1;
}
};
</script>关键点:
在 Django 的 views.py 中,我们需要编写两个函数:一个用于渲染帖子列表,另一个用于处理点赞/取消点赞的请求。
立即学习“Java免费学习笔记(深入)”;
from django.shortcuts import render
from django.contrib.auth import get_user_model
from django.http import JsonResponse
from .models import Post, LikeOrUnlike
import json
def list_posts(request):
posts = Post.objects.all()
user_liked_posts = request.user.likeByUser.all().values_list("post", flat=True)
context = {"posts": posts, "user_liked_posts": user_liked_posts}
return render(request, "posts/list.html", context)
def like_or_unlike_fetch(request):
data = json.loads(request.body)
user_id = data.pop("user_id")
post_id = data.pop("post_id")
user = get_user_model().objects.get(pk=user_id)
post = Post.objects.get(pk=post_id)
data.update({"user": user, "post": post})
like_object = LikeOrUnlike.objects.filter(**data)
if not like_object.exists():
LikeOrUnlike.objects.create(**data)
liked = True
else:
like_object.delete()
liked = False
return JsonResponse({"liked": liked})models.py:
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
def __str__(self):
return self.title
class LikeOrUnlike(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='likeByUser')
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='postLiked')
def __str__(self):
return f'{self.user} liked this {self.post}'urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('posts/', views.list_posts, name='list_posts'),
path('post/like/', views.like_or_unlike_fetch, name='like_or_unlike_fetch'),
]关键点:
通过上述步骤,我们可以使用 Django 和 JavaScript 实现一个流畅、无需页面刷新的点赞/取消点赞功能。关键在于正确处理前端的图标切换、避免点赞计数同步更新的问题,并使用简洁、高效的代码实现方案。 记住,安全性是至关重要的,始终要验证用户输入并防止 CSRF 攻击。 此外,可以考虑使用缓存来提高性能,特别是在点赞数量非常大的情况下。
以上就是使用 Django 和 JavaScript 实现流畅的点赞/取消点赞功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号