how to add like button to each blog post in the same page with django

Viewed 24

i am building a blog platform, i tried to add like button to each post in the same page with Ajax so that whenever the like button is press it will automatically work without refreshing but it shows this error

    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:\Users\HP\anaconda3\lib\site-packages\django\urls\resolvers.py, line 803, in _reverse_with_prefix
Raised during:  blog.views.HomeView
Python Executable:  C:\Users\HP\anaconda3\python.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

here is my view file

views.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]

please how can i add like button to each blog post with Ajax in same page with refreshing the page

1 Answers

i'm assuming while rendering all the Blogs you ll have Like button for each blogs so you can do like this

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

and then define it in js pass blog_id in request.POST instead URL.

Related