Python 如何使用AJAX在django中实现喜欢/不喜欢按钮(针对登录用户)
我尝试实现喜欢(对于那些不喜欢的用户)和不喜欢(对于那些已经喜欢帖子的用户)按钮,但我无法让它工作。我试图寻找一些过去的问题,但我无法解决这个问题。如果以前有人这样做过,请帮忙 发布模型的my blog/models.pyPython 如何使用AJAX在django中实现喜欢/不喜欢按钮(针对登录用户),python,django,ajax,post,Python,Django,Ajax,Post,我尝试实现喜欢(对于那些不喜欢的用户)和不喜欢(对于那些已经喜欢帖子的用户)按钮,但我无法让它工作。我试图寻找一些过去的问题,但我无法解决这个问题。如果以前有人这样做过,请帮忙 发布模型的my blog/models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
likes = models.ManyToManyField(User, related_name='likes', blank=True)
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def total_likes(self):
return self.likes.count()
我的博客/views.py
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
is_liked = False
if post.likes.filter(id=request.user.id).exists():
is_liked = True
return render(request, 'blog/post_detail.html', {'post': post, 'is_liked': is_liked, 'total_likes': post.total_likes(), })
def like_post(request):
post = get_object_or_404(Post, id=request.POST.get('id'))
is_liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
is_liked = False
else:
post.likes.add(request.user)
is_liked = True
context = {
'post': post,
'is_liked': is_liked,
'total_likes': post.total_likes(),
}
if request.is_ajax():
html = render_to_string('blog/like_section.html', context, request=request)
return JsonResponse({'form': html})
我的HTML和AJAX代码(本节在post_detail.HTML中提供)
我的博客应用程序的URL.py代码:-
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/login/', auth_views.LoginView.as_view(), name='login'),
path('accounts/logout/', auth_views.LogoutView.as_view(next_page='/'), name='logout'),
path('', include('blog.urls')),
]
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
path('post/new/', views.post_new, name='post_new'),
path('post/<int:pk>/edit/', views.post_edit, name='post_edit'),
path('drafts/', views.post_draft_list, name='post_draft_list'),
path('post/<pk>/publish/', views.post_publish, name='post_publish'),
path('post/<pk>/remove/', views.post_remove, name='post_remove'),
path('post/<int:pk>/comment/', views.add_comment_to_post, name='add_comment_to_post'),
path('comment/<int:pk>/approve/', views.comment_approve, name='comment_approve'),
path('comment/<int:pk>/remove/', views.comment_remove, name='comment_remove'),
path('like/', views.like_post, name="like_post"),
]
urlpatterns=[
路径(“”,views.post_list,name='post_list'),
路径('post/',views.post_detail,name='post_detail'),
路径('post/new/',views.post_new,name='post_new'),
路径('post//edit/',views.post\u edit,name='post\u edit'),
路径('drafts/',views.post_draft_list,name='post_draft_list'),
路径('post//publish/',views.post\u publish,name='post\u publish'),
路径('post//remove/',views.post\u remove,name='post\u remove'),
路径('post//comment/',views.add_comment_to_post,name='add_comment_to_post'),
路径('comment//approve/',views.comment\u approve,name='comment\u approve'),
路径('comment//remove/',views.comment\u remove,name='comment\u remove'),
路径('like/',views.like_post,name=“like_post”),
]
目录截图
现在,我在本地主机上运行此操作时遇到的错误是:-
正确的AJAX代码是
$(document).ready(function(event){
$(document).on('click', '#like', function(event){
event.preventDefault();
var pk = $(this).attr('value');
$.ajax({
type: 'POST',
url: '{% url "like_post" %}',
data: {
'id': pk,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function(response){
$('#like-section').html(response['form'])
},
error: function(rs, e){
console.log(rs.responseText);
},
});
});
});
我写这篇文章是作为任何人的参考,你怎么会遇到这种情况呢 确保在base.html中包含以下内容
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(event){
$(document).on('click', '#like', function(event){
event.preventDefault();
var pk = $(this).attr('value');
$.ajax({
type: 'POST',
url: '{% url "like_post" %}',
data: {
'id': pk,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
datatype: 'json',
success: function(response){
$('#like-section').html(response['form'])
},
error: function(rs, e){
console.log(rs.responseText);
},
});
});
});
</script>
</body>
$(document).ready(function(event){
$(document).on('click', '#like', function(event){
event.preventDefault();
var pk = $(this).attr('value');
$.ajax({
type: 'POST',
url: '{% url "like_post" %}',
data: {
'id': pk,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function(response){
$('#like-section').html(response['form'])
},
error: function(rs, e){
console.log(rs.responseText);
},
});
});
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(event){
$(document).on('click', '#like', function(event){
event.preventDefault();
var pk = $(this).attr('value');
$.ajax({
type: 'POST',
url: '{% url "like_post" %}',
data: {
'id': pk,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
datatype: 'json',
success: function(response){
$('#like-section').html(response['form'])
},
error: function(rs, e){
console.log(rs.responseText);
},
});
});
});
</script>
</body>
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render, get_object_or_404
from django.template.loader import render_to_string
from django.utils import timezone
from .models import Post
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
is_liked = False
if post.likes.filter(id=request.user.id).exists():
is_liked = True
return render(request, 'blog/post_detail.html', {'post': post, 'is_liked': is_liked, 'total_likes': post.total_likes(), })
def like_post(request):
post = get_object_or_404(Post, id=request.POST.get('id'))
is_liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
is_liked = False
else:
post.likes.add(request.user)
is_liked = True
context = {
'post': post,
'is_liked': is_liked,
'total_likes': post.total_likes(),
}
if request.is_ajax():
html = render_to_string('blog/like_section.html', context, request=request)
return JsonResponse({'form': html})