简体   繁体   English

未找到页面 (404) 未找到与查询匹配的评论

[英]Page not found (404) No comment found matching the query

views.py视图.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网址.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添加评论.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.所以我打开它 home/post/6/comment ,我看到了表单,当我提交时。 I get this error and the comment isnt saved error screenshot我收到此错误并且评论未保存错误屏幕截图

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 ). .get_object(…) [Django-doc]方法将尝试查找以您在路径中指定的主键作为主键的Comment (此处为6 )。 You do not want to find a comment but the Post with that primary key.您不想找到评论而是使用该主键的Post 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM