点赞按钮是现代Web应用中常见的交互功能,它允许用户通过点击按钮表达对内容的喜爱或认可。使用Django后端和Ajax前端技术实现点赞功能可以提供无刷新体验,提升用户交互流畅度。
首先需要在Django模型中添加点赞相关的字段:
# models.py
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
likes = models.ManyToManyField(User, related_name='liked_posts', blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def total_likes(self):
return self.likes.count()
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('like/<int:post_id>/', views.like_post, name='like_post'),
]
# views.py
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from .models import Post
@login_required
def like_post(request, post_id):
post = Post.objects.get(id=post_id)
if request.user in post.likes.all():
post.likes.remove(request.user)
liked = False
else:
post.likes.add(request.user)
liked = True
return JsonResponse({'liked': liked, 'total_likes': post.total_likes()})
<!-- post_detail.html -->
{% extends 'base.html' %}
{% block content %}
<div class="post">
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<button id="like-btn" data-post-id="{{ post.id }}"
class="{% if request.user in post.likes.all %}liked{% endif %}">
Like (<span id="like-count">{{ post.total_likes }}</span>)
</button>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('#like-btn').click(function() {
var post_id = $(this).data('post-id');
var button = $(this);
$.ajax({
type: 'POST',
url: '/like/' + post_id + '/',
data: {
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function(response) {
if (response.liked) {
button.addClass('liked');
} else {
button.removeClass('liked');
}
$('#like-count').text(response.total_likes);
},
error: function(xhr, errmsg, err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
});
});
</script>
{% endblock %}
/* static/css/styles.css */
button#like-btn {
padding: 5px 10px;
background-color: #f0f0f0;
border: 1px solid #ccc;
border-radius: 4px;
cursor: pointer;
}
button#like-btn.liked {
background-color: #4CAF50;
color: white;
}
原因:Django默认要求所有POST请求包含CSRF令牌
解决:
@csrf_exempt
装饰器(不推荐)原因:视图函数使用了@login_required
但前端未处理未登录情况
解决:
// 在Ajax请求前检查用户是否登录
$('#like-btn').click(function() {
{% if not request.user.is_authenticated %}
window.location.href = '{% url "login" %}?next={{ request.path }}';
return;
{% endif %}
// 原有Ajax代码...
});
原因:网络延迟导致多次请求被发送
解决:
// 添加按钮禁用状态
$('#like-btn').click(function() {
var button = $(this);
if (button.hasClass('disabled')) return;
button.addClass('disabled');
// Ajax请求...
success: function(response) {
button.removeClass('disabled');
// 其他处理...
},
error: function() {
button.removeClass('disabled');
}
});
这个实现方案提供了完整的Django + Ajax点赞功能,可以根据实际需求进行调整和扩展。
没有搜到相关的文章