首页 > 解决方案 > DoesNotExist at /blog/postComment 帖子匹配查询不存在

问题描述

我正在尝试在博客下方打印评论,但单击提交按钮后出现上述错误。我只想在网页顶部显示一条成功消息,为此我写了一行:messages.success(request, 'your comment has been added'),但出现了错误!

模型.py

from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now
# Create your models here.


class Post(models.Model):
    sno = models.AutoField(primary_key=True)
    title = models.CharField(max_length=50)
    content = models.TextField()
    author = models.CharField(max_length=50)
    slug = models.SlugField(max_length=200)
    timeStamp = models.DateTimeField(blank=True)

    def __str__(self):
        return self.title + " by " + self.author


class BlogComment(models.Model):
    sno = models.AutoField(primary_key=True)
    comment = models.TextField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True)
    timestamp = models.DateTimeField(default=now)

urls.py

from django.urls import path, include
from blog import views

urlpatterns = [
    path('postComment', views.postComment, name='postComment'),
    path('', views.blogHome, name='home'),
    path('<str:slug>', views.blogPost, name='blogpost'),
]

视图.py

from django.shortcuts import render, HttpResponse, redirect
from blog.models import Post, BlogComment


def blogHome(request):
    allpost = Post.objects.all()
    context = {'allposts': allpost}
    return render(request, 'blog/blogHome.html', context)


def blogPost(request, slug):
    post = Post.objects.filter(slug=slug).first()
    comments = BlogComment.objects.filter(post=post)
    context = {'post': post, 'comments': comments}
    return render(request, 'blog/blogPost.html', context)
    


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)

        comment = BlogComment(comment=comments, user=user, post=post)
        comment.save()
        messages.success(request, 'your comment has been added')

        return redirect(f"/blog/{post.slug}")

    return redirect('home')

blogPost.html

{% extends 'base.html' %}
{% block title %}
{{ post.title}}
{% endblock title %}

{% block body %}

<div class="container">
    <div class="jumbotron my-4">
    <div class="blog-post">
        <h2 class="blog-post-title">{{post.title}}</h2>
        <p class="blog-post-meta">{{post.timeStamp}} by <a href="#">{{post.author}}</a></p>

        <p>{{post.content}}</p>
      </div>
    </div>
</div>

<div>
  <div class="container">
    <h2>Comments</h2>
      <form action="/blog/postComment" method = 'post'>
        {% csrf_token %}
        <input type="text" name = 'comment' placeholder = 'type here'>
        <input type="hidden" name = "comment" value = "{{post.sno}}">
        <input type="submit" value = 'submit'>
      </form>
    <div class="row my-2">
      <div class="col-md-2">image here</div>
      <div class="col-md-10">comments here</div>
    </div>
  </div>
</div>

{% endblock body %}

错误日志

DoesNotExist at /blog/postComment
Post matching query does not exist.
Request Method: POST
Request URL:    http://127.0.0.1:8000/blog/postComment
Django Version: 3.1
Exception Type: DoesNotExist
Exception Value:    
Post matching query does not exist.
Exception Location: C:\Users\jayant nigam\projects\practise\lib\site-packages\django\db\models\query.py, line 429, in get
Python Executable:  C:\Users\jayant nigam\projects\practise\Scripts\python.exe
Python Version: 3.8.5
Python Path:    
['C:\\Users\\jayant nigam\\projects\\everythingcs',
 'C:\\Python38\\python38.zip',
 'C:\\Python38\\DLLs',
 'C:\\Python38\\lib',
 'C:\\Python38',
 'C:\\Users\\jayant nigam\\projects\\practise',
 'C:\\Users\\jayant nigam\\projects\\practise\\lib\\site-packages']
Server time:    Fri, 02 Oct 2020 19:21:31 +0000

我不知道为什么会出现这个错误!

标签: pythondjango

解决方案


您的错误在模板中。您将其中一项输入设置错误name

在您的代码中:

<input type="hidden" name = "comment" value = "{{post.sno}}">

正确的版本:

<input type="hidden" name = "postSno" value = "{{post.sno}}">

推荐阅读