Hello! I have a problem. When deleting a comment, the error Post matching query does not exist appears

I have a problem. When deleting a comment, the error Post matching query does not exist appears. And I do not know what to do with it. Thank you in advance!

Error: DoesNotExist at /news/post/6
Post matching query does not exist.

Note! I use the django framework

The error occurs in the "PostDetailView" class on the line:
post = Post.objects.get(pk=pk)

Here is the code: views.py:

from django.shortcuts import render
from django.urls import reverse_lazy
from .forms import PostForm, CommentForm
from .models import Post, Comment
from django.views import View
from django.views.generic.edit import UpdateView, DeleteView


class PostListView(View):
    def get(self, request, *args, **kwargs):
        posts = Post.objects.all().order_by('-created_on')
        form = PostForm()

        context = {
            'post_list': posts,
            'form': form,
        }
        return render(request, 'news/post_list.html', context)

    def post(self, request, *args, **kwargs):
        posts = Post.objects.all().order_by('-created_on')
        form = PostForm(request.POST)

        if form.is_valid():
            new_post = form.save(commit=False)
            new_post.author = request.user
            new_post.save()

        context = {
            'post_list': posts,
            'form': form,
        }
        return render(request, 'news/post_list.html', context)


class PostDetailView(View):
    def get(self, request, pk, *args, **kwargs):
        post = Post.objects.get(pk=pk)
        form = CommentForm()

        comments = Comment.objects.filter(post=post).order_by('-created_on')

        context = {
            'post': post,
            'form': form,
            'comments': comments,
        }
        return render(request, 'news/details_view.html', context)

    def post(self, request, pk, *args, **kwargs):
        post = Post.objects.get(pk=pk)
        form = CommentForm(request.POST)

        if form.is_valid():
            new_comment = form.save(commit=False)
            new_comment.author = request.user
            new_comment.post = post
            new_comment.save()

        comments = Comment.objects.filter(post=post).order_by('-created_on')

        context = {
            'post': post,
            'form': form,
            'comments': comments,
        }
        return render(request, 'news/details_view.html', context)


class PostEditView(UpdateView):
    model = Post
    fields = ['body']
    template_name = 'news/post_edit.html'

    def get_success_url(self):
        pk = self.kwargs['pk']
        return reverse_lazy('post-detail', kwargs={'pk': pk})


class PostDeleteView(DeleteView):
    model = Post
    template_name = 'news/post_delete.html'
    success_url = reverse_lazy('post-list')


class CommentDeleteView(DeleteView):
    model = Comment
    template_name = 'news/comment_delete.html'

    def get_success_url(self):
        pk = self.kwargs['pk']
        return reverse_lazy('post-detail', kwargs={'pk': pk})

comment_delete.html:

{% extends 'main/layout.html' %}
{% load crispy_forms_tags %}
{% load static %}

{% block content%}
<link rel="stylesheet" href="{% static 'news/css/post_list.css'%}">
<div class="container">
    <div class="row mt-5">
        <div class="col-md-5 col-sm-6">
            <a href="{% url 'post-detail' object.pk %}" class="btn btn-light">Вернуться обратно</a>
        </div>
    </div>

    <div class="row justify-content-center mt-3 mb-5">
        <div class="col-md-5 col-sm-12 border-bottom">
            <form method="POST" class="form">
                {% csrf_token %}
                <h5>Вы уверены?</h5>
                <p>Вы уверены, что хотите удалить комментарий это невозможно отменить</p>
                <div class="d-grid gap-2">
                    <button class="btn btn-danger mt-3">Удалить</button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock content %}

details_view.html:

{% extends 'main/layout.html' %}
{% load crispy_forms_tags %}
{% load static %}

{% block title%}Post{% endblock %}

{% block content%}
<link rel="stylesheet" href="{% static 'news/css/post_list.css'%}">
<div class="container">
    <div class="row mt-5">
        <div class="col-md-5 col-sm-6">
            <a href="{% url 'post-list' %}" class="btn btn-light">Вернуться обратно</a>
        </div>
    </div>

    <div class="row justify-content-center mt-3">
        <div class="col-md-5 col-sm-12 border-bottom">
            <p>
                <strong>{{ post.author }}</strong> {{ post.created_on }}
                {% if request.user == post.author %}
                    <a href="{% url 'post-edit' post.pk %}" style="color: #333;"><i class="far fa-edit"></i></a>
                    <a href="{% url 'post-delete' post.pk %}" style="color: #333;"><i class="far fa-trash"></i></a>
                {% endif %}
            </p>
            <p>{{ post.body }}</p>
        </div>
    </div>

    <div class="row justify-content-center mt-3 mb-5">
        <div class="col-md-5 col-sm-12">
            <form method="POST" class="form">
                {% csrf_token %}
                {{ form | crispy }}
                <div class="d-grid gap-2">
                    <button class="btn btn-success mt-3">Написать</button>
                </div>
            </form>
        </div>
    </div>
    {% for comment in comments %}
    <div class="row justify-content-center mt-3 mb-5 border-bottom">
        <div class="col-md-5 col-sm-12">
            <p>
                <strong>{{ comment.author }}</strong> {{ comment.created_on }}
                {% if request.user == post.author %}
                    <a href="{% url 'comment-delete' post.pk comment.pk %}" style="color: #333;"><i class="far fa-trash"></i></a>
                {% endif %}
            </p>
            <p>{{ comment.comment }}</p>
        </div>
    </div>
    {% endfor %}
</div>
{% endblock content %}

news/urls.py:

from django.urls import path
from . import views
from .views import PostListView, PostDetailView, PostEditView, PostDeleteView, CommentDeleteView

urlpatterns = [
    path('', PostListView.as_view(), name='post-list'),
    path('post/<int:pk>', PostDetailView.as_view(), name='post-detail'),
    path('post/edit/<int:pk>', PostEditView.as_view(), name='post-edit'),
    path('post/delete/<int:pk>', PostDeleteView.as_view(), name='post-delete'),
    path('post/<int:post_pk>/comment/delete/<int:pk>', CommentDeleteView.as_view(), name='comment-delete'),
]

I've tried articles and videos from YouTube

As the error message has already told you, this part is the "problem" code:

post = Post.objects.get(pk=pk)

If this query runs and the database doesn't find an object with the supplied pk, it doesn't return an empty result set - it instead throws the exception you are getting now.

You have several options for how to handle this, but here are two variants of what is advisable:

1. Django's built-in tools for this situation:

from django.shortcuts import get_object_or_404  

[...]

def post(self, request, pk, *args, **kwargs):
    post = get_object_or_404(Post, pk=pk)

Under the hood, this will raise the built-in Http404 exception if an object is not found, which redirects the user to a default error page.

2. Manual exception handling

(For example if the Http404 part of the first solution is inadequate for you)

def post(self, request, pk, *args, **kwargs):
    try:
        post = Post.objects.get(pk=pk)
    except:
        post = None
        # And/or some other appropriate action

Keep in mind that in this case you'll have to figure out what to return to the user (or whether to redirect them, etc).

Back to Top