/blog/2处的完整性错误NOT NULL约束失败:blog_comment.post_id



我在尝试向应用程序添加评论时出错。

我的表单是:

from django import forms
from .models import Comment
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = [
'content'
]

模型为:

class Post(models.Model):
title = models.CharField(max_length=50)
content = models.TextField()
author = models.ForeignKey(User , on_delete=models.CASCADE)
image = models.ImageField(upload_to='blog/'  , blank=True, null=True)
# tags
category = models.ForeignKey('Category'  ,null=True, on_delete=models.SET_NULL)
created  = models.DateTimeField(default=timezone.now)
tags = TaggableManager(blank=True)

class Meta:
verbose_name = ' post'
verbose_name_plural = 'posts'
def __str__(self):
return self.title

class Category(models.Model):
category_name = models.CharField(max_length=50)

class Meta:
verbose_name = ' category'
verbose_name_plural = 'catogires'
def __str__(self):
return self.category_name

class Comment(models.Model):
user = models.ForeignKey(User , on_delete=models.CASCADE)
post = models.ForeignKey(Post , on_delete=models.CASCADE)
content = models.TextField()
created = models.DateTimeField(default=timezone.now)

def __str__(self):
return str(self.content)

我的观点是:

from django.shortcuts import render
from .models import Post , Category , Comment
from taggit.models import Tag
from .forms import CommentForm
def post_detail(request , id):
post_detail = Post.objects.get(id=id)
categories = Category.objects.all()
all_tags = Tag.objects.all()
comments = Comment.objects.filter(post=post_detail)

if request.method == 'POST' :
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.user = request.user
new_comment.post = post_detail
new_comment.save()
else:
comment_form = CommentForm()
context = {
'post_detail' : post_detail ,
'categories' : categories ,
'all_tags' : all_tags ,
'comments' : comments ,
'comment_form' : comment_form
}
return render(request , 'Post/post_detail.html' , context)


def post_by_tag(request , tag):
post_by_tag = Post.objects.filter(tags__name__in=[tag])
context = {
'post_list' : post_by_tag ,
}
return render(request , 'Post/post_list.html' , context)

请帮我解决这个问题。我已经检查了几个来源,但我无法解决它。我发现了一些类似的代码,专门为博客中的帖子添加评论,并试图在我自己的代码中使用它们的方法。但我解决不了。

基本上,方法名和变量名是相同的:

def post_detail(request , id): # <-- Here
post_detail = Post.objects.get(id=id) # <-- Here

将变量名称更改为其他名称,如post

def post_detail(request , id):
post = Post.objects.get(id=id)
categories = Category.objects.all()
all_tags = Tag.objects.all()
comments = Comment.objects.filter(post=post)

if request.method == 'POST' :
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.user = request.user
new_comment.post = post
else:
comment_form = CommentForm()
context = {
'post_detail' : post ,
# rest of the code

最新更新