[Answered ]-Django jquery ajax comment reply create multiple values

1👍

Your issue is related to the following line:

if reply_id:
    comment_qs = Comment.objects.get(id=reply_id).exists()

It returns 2 objects. You have to remove duplicates from your database.

Then you can use one of the two following codes.

First method: if CommentForm is ModelForm:

... 

if request.method=='POST':
    querydict = request.POST
    comment_form = CommentForm(querydict)
    if comment_form.is_valid():
        comment = comment_form.save(commit=False)
        comment.post = post
        comment.user = request.user
        comment.reply_id = querydict.get('comment_id')
        comment.save()      
else:
    comment_form = CommentForm()
...

Or as second method: if your form is not ModelForm or some other reason

... 

if request.method=='POST':
    querydict = request.POST
    comment_form = CommentForm(querydict)
    if comment_form.is_valid():
        comment = Comment.objects.create(
            post=post, user=request.user, 
            content=querydict.get('content'), 
            reply_id=querydict.get('comment_id')
        )
        
else:
    comment_form = CommentForm()
...

In Ajax, I would also disable the button on submit:

var form = $(this);
form.find('input[type="submit"]').attr('disabled', true);

And when ajax complete back enable:

complete: function (data) {
    form.find('input[type="submit"]').attr('disabled', false);
}
👤NKSM

Leave a comment