在Django类ListView中添加"like"按钮,可以通过以下步骤实现:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
from django.views.generic import ListView
from .models import Post
class PostListView(ListView):
model = Post
template_name = 'post_list.html'
from django.urls import path
from .views import PostListView
urlpatterns = [
path('posts/', PostListView.as_view(), name='post_list'),
]
{% extends 'base.html' %}
{% block content %}
<h1>Posts</h1>
<ul>
{% for post in object_list %}
<li>
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<button class="like-button">Like</button>
</li>
{% endfor %}
</ul>
{% endblock %}
{% extends 'base.html' %}
{% block content %}
<h1>Posts</h1>
<ul>
{% for post in object_list %}
<li>
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<button class="like-button" data-post-id="{{ post.id }}">Like</button>
</li>
{% endfor %}
</ul>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('.like-button').click(function() {
var postId = $(this).data('post-id');
$.ajax({
url: '/like/',
method: 'POST',
data: { 'post_id': postId },
success: function(response) {
alert('Post liked!');
},
error: function(xhr, status, error) {
alert('An error occurred while liking the post.');
}
});
});
});
</script>
{% endblock %}
from django.http import JsonResponse
def like_post(request):
if request.method == 'POST':
post_id = request.POST.get('post_id')
# 根据post_id执行喜欢的逻辑,例如增加喜欢计数或将用户添加到喜欢列表中
return JsonResponse({ 'status': 'success' })
else:
return JsonResponse({ 'status': 'error' })
from django.urls import path
from .views import PostListView, like_post
urlpatterns = [
path('posts/', PostListView.as_view(), name='post_list'),
path('like/', like_post, name='like_post'),
]
现在,当访问/posts/路径时,将显示帖子列表,并且每个帖子都有一个"like"按钮。当用户点击"like"按钮时,将通过AJAX请求将喜欢的状态发送到服务器,并显示相应的提示信息。请注意,这只是一个简单的示例,实际的喜欢功能可能需要更复杂的逻辑和数据模型。
领取专属 10元无门槛券
手把手带您无忧上云