Search code examples
djangodjango-modelsdjango-viewsdjango-templatesdjango-apps

matching query does not exist. DoesNotExist at /blog/postComment


I am trying to add the feature of commenting and replying to it in my blog. But it is constantly throwing me the error of "BlogComment matching query does not exist."

def postComment(request):
    if request.method == "POST":
        comment = request.POST.get('comment')
        user = request.user
        postSno = request.POST.get('postSno')
        post = Post.objects.get(sno=postSno)
        parentSno = request.POST.get('parentSno')
        if parentSno == "":
            comment = BlogComment(comment=comment, user=user, post=post)
            comment.save()
            messages.success(request, "Your comment has been posted successfully")
        else:
            parent = BlogComment.objects.get(sno=parentSno)
            comment = BlogComment(comment=comment, user=user, post=post, parent=parent)
            comment.save()
            messages.success(request, "Your reply has been posted successfully")

Solution

  • The get() method returns None by default when the specified key does not exist.

    So you should check if parentSno is not None: instead of if parentSno == "":.

    (alternately, you could also change that default value by using the second argument of the get() method: parentSno = request.POST.get('parentSno', "") (see here for example)).