I am trying to add a like button using Ajax and & Jquery in Like Button but I keep getting the below error:
LikeView() missing 1 required positional argument: 'pk'
Here is the view.py:
class PostDetailView(DetailView):
model = Post
template_name = "post_detail.html"
def get_context_data(self, *args, **kwargs):
context = super(PostDetailView, self).get_context_data()
stuff = get_object_or_404(Post, id=self.kwargs['pk'])
total_likes = stuff.total_likes()
liked = False
if stuff.likes.filter(id=self.request.user.id).exists():
liked = True
context["total_likes"] = total_likes
context["liked"] = liked
return context
def LikeView(request, pk):
# post = get_object_or_404(Post, id=request.POST.get('post_id'))
post = get_object_or_404(Post, id=request.POST.get('id'))
like = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
like = False
else:
post.likes.add(request.user)
like = True
context["total_likes"] = total_likes
context["liked"] = liked
if request.is_ajax:
html = render_to_string('like_section.html', context, request=request)
return JsonResponse({'form': html})
Here is the url.py in the main project, I have moved it to the main 'url.py'
urlpatterns = [
path('like/', views.LikeView, name='like_post'),
here is the updated template
<form class="mt-0" action="{% url 'like_post' %}" method='POST'>
{% csrf_token %}
<strong> Likes
: {{total_likes}} </strong>
{% if user.is_authenticated %}
{% if liked %}
<button id='like' type='submit' name='post_id' class= "btn btn-danger btn-sm" value="{{post.id}}"> Unlike </button>
{% else %}
<button id='like' type='submit' name='post_id' class= "btn btn-primary btn-sm" value="{{post.id}}"> Like </button>
{% endif %}
{% else %}
<p><small><a href="{% url 'login' %}"> Login</a> to Like </small></p>
{% endif %}
</form>
here is the ajax
<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'])
console.log($('#like-section').html(response['form']));
},
error:function(rs, e){
console.log(rs.responseText);
},
});
});
});
</script>
My url pattern in the main project
path('like/', views.LikeView, name='like_post'),
-
ahmed.hisham87
4 years, 11 months ago
why var declation in $ in ajax call. You can simply assign like this "var pk= this_.attr("href");" .. try changing this and let us know .
- Vengatcould you please show me where exactly to change it by copying it in the ajax code
- ahmed.hisham87 4 years, 11 months agochange this line "$var pk= $(this).attr('value');" to "var pk= $(this).attr('value');"
- VengatActually there is an action taking place but i have to refresh manually to change from like to unlike and the other way around
- ahmed.hisham87 4 years, 11 months agoare you getting "missing pk error" now? . If not we are in right direction
- Vengatcan you console the response and check the output in success, "success:function(response){ console.log(response); }|
- Vengathow do i do this ? console the response and check the output in success, "success:function(response){ console.log(response); }|
- ahmed.hisham87 4 years, 11 months agonothing happens I have to refresh to see the change from like to unlike
- ahmed.hisham87 4 years, 11 months agowhere is this $('#like-section').html(response['form']) button?.. i dont see like-section id in your form
- Vengatdef LikeView(request): # post = get_object_or_404(Post, id=request.POST.get('post_id')) post = get_object_or_404(Post, id=request.POST.get('id')) # stuff = get_object_or_404(Post, id=self.kwargs['pk']) # total_likes = stuff.total_likes() liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True
context = {
# 'total_likes': total_likes,
'liked': liked,
'post': post
}
if request.is_ajax:
html = render_to_string('like_section.html', context, request=request)
return JsonResponse({'form': html})
-
ahmed.hisham87
4 years, 11 months ago
i think the ajax now is working fine the problem now is with the count if i added it in the context the button is not working if it is removed it works perfectly and the like is added and removed in the admin
- ahmed.hisham87 4 years, 11 months agoi hope you are referring LikeView. If yes, total_like is a variable is assigned to that, are you getting the total_like count in your ajax success output?
- Vengatyes thank you so much it is working now
Awesome !!!. You can console the log & check the count value whether its passing or not.
- Vengatthe count value is passing but i removed it from the function because it is causing the error and I dont know how to return it back : i have commented it in the following code to help me with it
def LikeView(request): # post = get_object_or_404(Post, id=request.POST.get('post_id')) post = get_object_or_404(Post, id=request.POST.get('id')) # stuff = get_object_or_404(Post, id=self.kwargs['pk']) # total_likes = stuff.total_likes() liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True
context = {
# 'total_likes': total_likes,
'liked': liked,
'post': post
}
if request.is_ajax:
html = render_to_string('like_section.html', context, request=request)
return JsonResponse({'form': html})
-
ahmed.hisham87
4 years, 11 months ago
cool !!. feel free to contact us whenever you need any support from us.
- Vengat
Can you try removing the "submit" type from button?. Seems like you have ajax call but it has POST method on the FORM