如何使用django为同一页面中的每条博客文章添加点赞按钮



我正在构建一个博客平台,我试图用Ajax在同一页面中的每个帖子中添加类似按钮,这样每当按下类似按钮时,它都会自动工作,而不会刷新,但它显示了这个错误

NoReverseMatch at /
Reverse for 'like_post' with arguments '('',)' not found. 1 pattern(s) tried: ['like/(?P<pk>[0-9]+)\Z']
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 4.1
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'like_post' with arguments '('',)' not found. 1 pattern(s) tried: ['like/(?P<pk>[0-9]+)\Z']
Exception Location: C:UsersHPanaconda3libsite-packagesdjangourlsresolvers.py, line 803, in _reverse_with_prefix
Raised during:  blog.views.HomeView
Python Executable:  C:UsersHPanaconda3python.exe
Python Version: 3.9.7
Python Path:    
['C:\Users\HP\Dacurate-1',
'C:\Users\HP\anaconda3\python39.zip',
'C:\Users\HP\anaconda3\DLLs',
'C:\Users\HP\anaconda3\lib',
'C:\Users\HP\anaconda3',
'C:\Users\HP\anaconda3\lib\site-packages',
'C:\Users\HP\anaconda3\lib\site-packages\locket-0.2.1-py3.9.egg',
'C:\Users\HP\anaconda3\lib\site-packages\win32',
'C:\Users\HP\anaconda3\lib\site-packages\win32\lib',
'C:\Users\HP\anaconda3\lib\site-packages\Pythonwin']
Server time:    Sun, 11 Sep 2022 23:17:55 +0000

这是我的视图文件

视图.py

def CategoryView(request,cats):
category_post=Post.objects.filter(category=cats.replace('-',' '))
return render(request,'category.html',{'cats':cats.title().replace('-',' '),'category_post':category_post})

def CategoryListView(request):
cat_menu_list=Category.objects.all()
return render(request,'category_list.html',{'cat_menu_list':cat_menu_list})

class UserRegisterView(CreateView):
form_class=SignUpForm
template_name='register.html'
success_url=reverse_lazy('home')


def LikeView(request, pk):
post=get_object_or_404(Post, id=int(request.POST.get('post_id')))

if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user.id)
result = post.like_count
post.save()
else:
post.likes.add(request.user)
post.like_count += 1
result = post.like_count
post.save()
return JsonResponse({'result': result,})

def FollowerView(request, pk):
post=get_object_or_404(Post, id=request.POST.get('follow_id'))

followed=False
if post.followers.filter(id=request.user.id).exists():
post.followers.remove(request.user.id)
followed=False
else:
post.followers.add(request.user.id)
followed=True
#return redirect (reverse('home', post.pk) + '#{{post.pk}}')
#return HttpResponseRedirect(reverse('article-detail', args=[post.pk])+ '#{{post.pk}}')
return redirect('home')


class HomeView(ListView):
model=Post
template_name='home.html'
ordering=['-id']
def get_context_data(self, *args, **kwargs):
cat_menu=Category.objects.all()
context=super(HomeView, self).get_context_data(*args,**kwargs)
context['cat_menu']= cat_menu
return context

urls.py

from django.urls import path
from .views import AddPostView1, HomeView,ArticleDetailView,AddPostView,AddPostView1,UpdatePostView,DeletePostView,LikeView,UserEditView,PasswordsChangeView,ShowProfilePageView,EditProfilePageView,CreateProfilePageView,AddCommentView,UserRegisterView,FollowerView,CategoryView,CategoryListView,UpdateQuestionView,AddCommentView1
from . import views

urlpatterns = [

path('',HomeView.as_view(), name='home'),
path('register/',UserRegisterView.as_view(),name='register'),
path('article/<int:pk>', ArticleDetailView.as_view() , name='article-detail'),
path('add_post/',AddPostView.as_view(),name='add-post'),
path('add_post1/',AddPostView1.as_view(),name='add-post1'),
path('article/edit/<int:pk>',UpdatePostView.as_view(),name='update-post'),
path('article/update/<int:pk>',UpdateQuestionView.as_view(),name='update-question'),
path('article/<int:pk>/remove',DeletePostView.as_view(),name='delete-post'),
path('like/<int:pk>',LikeView,name='like_post'),   #like 

path('follow/<int:pk>',FollowerView,name='follow'),
path('edit_profile/',UserEditView.as_view(),name='edit-profile'),
path('password/', PasswordsChangeView.as_view(template_name='change-password.html')),
path('password_success', views.password_success, name='password-success'),
path('<int:pk>/profile/',ShowProfilePageView.as_view(), name='show-profile'),
path('<int:pk>/edit_profile/',EditProfilePageView.as_view(), name='edit-profile-page'),
path('create_profile_page/',CreateProfilePageView.as_view(), name='create-profile-page'),
path('article/<int:pk>/comment/',AddCommentView.as_view(),name='comment'),
path('article/<int:pk>/comment1/',AddCommentView1.as_view(),name='comment1'),
path('category/<str:cats>/',CategoryView,name='category'),
path('category-list',CategoryListView,name='category-list'),

]

home.html

<div class="w3-col s3 m3 l3" id="{{post.pk}}">

<form action="{% url 'like_post' post.pk %}"  method="POST">
{% csrf_token %}

<button type="submit"  name="post_id" value="{{post.id}}" ><img src="{% static 'like1.png' %}" style="width:20px;margin:auto;"></button>
{{post.likes.count}}

</form>

ajax

[<script>

$(document).on('click', '#like-button', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "like_post"  post.pk %}',
data: {
postid: $('#like-button').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success: function (json) {
document.getElementById("like_count").innerHTML = json['result']
},
error: function (xhr, errmsg, err) {
}
});
})
</script>][1]

请告诉我如何在刷新页面的同时,在同一页面中用Ajax为每条博客文章添加点赞按钮

我假设在渲染所有博客时,每个博客都有"点赞"按钮,这样你就可以像这个一样

<button onclick=("likeFunction(blog_id)">Like</button >

然后在请求中通过blog_id在js中定义它。POST改为URL。

最新更新