Why does my page reload when a User try commenting on a second or third post in list view, but when user comment on a first post it doesn't reload page but work perfectly , When using ajax with Django why doesn't ajax work for second and third post but only first post! can anyone help !
#Comment function for listview
def post_listview(request, c_slug=None,**kwargs):
user_info = request.user
user_id = kwargs.get('user_id')
context = {}
for user in Post.objects.all():
if request.user.is_authenticated:
friend_list = FriendList.objects.get(user=request.user )
friends = friend_list.friends.all()
context['friends'] = friends
context['posts'] = Post.objects.prefetch_related('comments').filter(\
username__in=list(friends)+[request.user,]).order_by('-date_posted')
time_delta = datetime.now() - timedelta(hours=28)
return render(request,'feed/feed.html',context)
def feedComment(request,id):
if request.method == 'GET':
comment = request.GET.get('comment_text')
post_obj = Post.objects.get(id=id)
create_comment = Comment.objects.create(post=post_obj, username=request.user, comment=comment)
create_comment.save()
return JsonResponse({'comment':create_comment.comment,})
jquery ajax comment function for list view
<script type="text/javascript">
var send_btn = $('#send_btn');
send_btn.on('click', function(event){
event.preventDefault();
var comment = $('#comment').val();
var ul_menu = $('#menu');
$.ajax({
type: 'GET',
url: '{% url "feed:post-detail" post.id %}',
data: {comment_text:comment, id:'{{ product.id }}',
csrfmiddlewaretoken: "{{ csrf_token }}"},
dataType: 'json',
success: function(data){
if(data.comment)
{
$('#my_form').trigger('reset');
}
}
});
});
</script>
Form for comment
{% for post in posts %}
<form for="my_form">
{% csrf_token %}
<div class="bg-gray-100 rounded-full relative dark:bg-gray-800 border-t" >
<input placeholder="Add your Comment.." id="comment" name="comment" class="bg-transparent max-h-10 shadow-none px-5">
<div class="-m-0.5 absolute bottom-0 flex items-center right-3 text-xl">
<a href=''>
<ion-icon name="happy-outline" class="hover:bg-gray-200 p-1.5 rounded-full">{{ emoji }}</ion-icon>
</a>
<a href="#">
<ion-icon name="image-outline" class="hover:bg-gray-200 p-1.5 rounded-full"></ion-icon>
</a>
<a href="#">
<ion-icon name="link-outline" class="hover:bg-gray-200 p-1.5 rounded-full"></ion-icon>
</a>
</div>
</div>
<input class="btn btn-outline-success my-3" id="send_btn" type="submit" value="Comment">
</form>
</div>
</div>
{% endfor %}