我正在尝试打印博客下方的评论,但单击提交按钮后出现上述错误。我只想在网页顶部显示一条成功消息,为此我编写了以下行:messages.success(request, 'your comment has been added'),但出现错误!models.py:from django.db import modelsfrom django.contrib.auth.models import Userfrom 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.authorclass 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, includefrom blog import viewsurlpatterns = [ path('postComment', views.postComment, name='postComment'), path('', views.blogHome, name='home'), path('<str:slug>', views.blogPost, name='blogpost'),]view.py:from django.shortcuts import render, HttpResponse, redirectfrom blog.models import Post, BlogCommentdef 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)
3 回答
![?](http://img1.sycdn.imooc.com/5458471300017f3702200220-100-100.jpg)
慕田峪9158850
TA贡献1794条经验 获得超7个赞
你的错误在模板中。name
您的输入之一设置错误:
在你的代码中:
<input type="hidden" name = "comment" value = "{{post.sno}}">
正确版本:
<input type="hidden" name = "postSno" value = "{{post.sno}}">
![?](http://img1.sycdn.imooc.com/533e4c0500010c7602000200-100-100.jpg)
凤凰求蛊
TA贡献1825条经验 获得超4个赞
为了解决您的第一个问题,您应该将该行post = Post.objects.get(sno=postSno)(在postComment函数中)更改为:
from django.http import Http404
try:
post = Post.objects.get(sno=postSno)
except Post.DoesNotExist:
return Http404("Post does not exist") # or return HttpResponse("Post does not exist")
因为在某些情况下该查询可能无法返回任何结果,因此会引发DoesNotExistError。第二个问题(我的意思是NameError at /blog/postComment name 'comments' is not defined)来自相同的函数...更改此行将comment = BlogComment(comment=comments, user=user, post=post)解决comment = BlogComment(comment=comment or '', user=user, post=post)此问题。
添加回答
举报
0/150
提交
取消