我正在嘗試打印博客下方的評論,但單擊提交按鈕后出現上述錯誤。我只想在網頁頂部顯示一條成功消息,為此我編寫了以下行: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 回答

慕田峪9158850
TA貢獻1794條經驗 獲得超7個贊
你的錯誤在模板中。name
您的輸入之一設置錯誤:
在你的代碼中:
<input type="hidden" name = "comment" value = "{{post.sno}}">
正確版本:
<input type="hidden" name = "postSno" value = "{{post.sno}}">

鳳凰求蠱
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
提交
取消