簡體   English   中英

未找到頁面 (404) 未找到與查詢匹配的評論

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

視圖.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)

網址.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)

添加評論.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 %}

所以我打開它 home/post/6/comment ,我看到了表單,當我提交時。 我收到此錯誤並且評論未保存錯誤屏幕截圖

.get_object(…) [Django-doc]方法將嘗試查找以您在路徑中指定的主鍵作為主鍵的Comment (此處為6 )。 您不想找到評論而是使用該主鍵的Post 因此,您應該將其重寫為:

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