Home > OS >  Page not found (404) No comment found matching the query
Page not found (404) No comment found matching the query

Time:11-17

views.py

    class CommentCreatView(LoginRequiredMixin, CreateView): 
       model = Comment
       fields = ['text']
       template_name = 'home/add-comment.html'
       success_url = 'homepage'
      
       
       def form_valid(self,form):
          form.instance.user = self.request.user 
          post = self.get_object()  
          form.instance.post = post
          return super().form_valid(form)

urls.py

from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
from .views import PostCreateView, PostsListView, PostDetailView, CommentCreatView

urlpatterns = [
   path('', PostsListView.as_view(), name='homepage'),
   path('post/<int:pk>/', PostDetailView.as_view(), name='post-and-comments'),
   path('post/<int:pk>/comment', CommentCreatView.as_view(), name='add-comment'),
   path('creat', PostCreateView.as_view(), name='creat-post')
]   static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

add-comment.html

{% extends "home/base.html" %}

{% load crispy_forms_tags %} 
<!-- allow us to use crispy filter on any of our forms -->
{% block content %}
    <div class="content-section">
        <form method="POST">
             <!--this method post is to protect our form fromcertain attacks  -->
            {% csrf_token %}
            {{form|crispy}}
            <button class="btn btn-outline-danger  mt-1 mb-1 mr-1 ml-1" type="submit">Add Comment</button>
            </div>
        </form>
    </div>

{% endblock content %}

So I opens it home/post/6/comment , I see the form and when I submit it. I get this error and the comment isnt saved error screenshot

CodePudding user response:

The .get_object(…) [Django-doc] method will try to find a Comment with as primary key the one you specified in the path (here 6). You do not want to find a comment but the Post with that primary key. You thus should rewrite this to:

class CommentCreatView(LoginRequiredMixin, CreateView): 
    model = Comment
    fields = ['text']
    template_name = 'home/add-comment.html'
    success_url = 'homepage'
      
    def form_valid(self,form):
       form.instance.user = self.request.user
       form.instance.post_id = self.kwargs['pk']
       return super().form_valid(form)
  • Related