I am trying to make the like button in the post_detail.html
page clicked without refreshing the page so, I included the like section in a separate HTML called like-section.html
. The problem is now I am getting a: Not Found: /blogs/like
when I click on the like button and it doesn't change anything when I click it except in the terminal I see this error Not Found: /blogs/like
How do I solve this error and what am I missing
Here is the model.py:
class Post(models.Model):
------------------------------
liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked')
Here is the views.py:
def like_post(request):
user = request.user
post_obj = None
if request.method == 'POST':
post_id = request.POST.get('post_id')
try:
post_obj = Post.objects.get(id=post_id)
except Post.DoesNotExist:
return JsonResponse({'detail': 'Not found'}, status=404)
else:
if user in post_obj.liked.all():
post_obj.liked.remove(user)
else:
post_obj.liked.add(user)
like, created = Like.objects.get_or_create(user=user, post_id=post_id)
if not created:
if like.value == 'Like':
like.value = 'Unlike'
else:
like.value = 'Like'
like.save()
context = {
'post_id': post_id,
}
if request.is_ajax:
html = render_to_string('blog/like_section.html', context,
request=request)
return JsonResponse({'form': html})
elif request.method == 'GET':
post_id = request.GET.get('post_id')
try:
post_obj = Post.objects.get(id=post_id)
except Post.DoesNotExist:
return JsonResponse({'detail': 'Not found'}, status=404)
Here is the like-s;:ection.html:
<form action="{% url 'blog:like-post' %}" method="POST" class="like-form" id="{{post.id}}">
{% csrf_token %}
<input type="hidden" name="post_id" value='{{post.id}}'>
{% if user not in post.liked.all %}
<a id="like" class="bwhite sm-button" style="color: grey; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none;">
<i class="far fa-thumbs-up" type="submit"></i>
</a>
{% else %}
<a id="like" class="bwhite sm-button" style="color: blue;background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none;" >
<i class="far fa-thumbs-up" type="submit"></i>
</a>
{% endif %}
<div class="like-count{{post.id}}">{{ post.num_likes }} Likes</div>
</form>
Here is the script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript"></script>
<script>
$( document ).ready(function() {
let display = false
$(".cmt_btn").click(function () {
if (display===false) {
$(this).next(".comment-box").show("fast");
display=true
} else {
$(this).next(".comment-box").hide("fast");
display=false
}
});
});
</script>
<script>
$(document).on('click', '#like', function(event){
event.preventDefault();
var pk = $(this).attr('value');
$.ajax({
type: 'POST',
url: '{% url "blog:like-post" %}',
data: {'post_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>
here is the urls.py
path('blog/<slug:slug>/', PostDetailView.as_view(), name='post-detail'),
path('blogs/like', like_post, name='like-post'),
Thank you, could you just add some explanation as I am new to javascript and ajax, I am trying to understand the cycle to implement it.
- ahmed.hisham87 4 years, 5 months agobasically you have to use input hidden value method or read the form action url in Javascript to grab the URL. if you still have doubt then let me know, we can connect and discuss.
- Vengat
I usually prefer to read the URL from the form itself.,