gpt4 book ai didi

django - "IntegrityError. NOT NULL constraint failed: blog_comment.post_id "代表什么?

转载 作者:行者123 更新时间:2023-12-04 15:45:43 26 4
gpt4 key购买 nike

我已经在我的应用程序中添加了一个 Comment 模型,但是当提交表单时,弹出这个错误:

NOT NULL 约束失败:blog_comment.post_id

这是模型.py:

class Post(models.Model):
title = models.CharField(max_length=100, null=True, blank=True)
caption = models.CharField(max_length=100, null=True, blank=True)
image = models.ImageField(upload_to='post_pics/', null=True, blank=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)

def __str__(self):
return self.title

def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})

class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
text = models.TextField(null=True)
date_posted = models.DateTimeField(default=timezone.now)

def __str__(self):
return self.text

def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})

这是在 views.py 中创建评论的部分:

class AddCommentView(LoginRequiredMixin, CreateView):
model = Comment
fields = ['text']

def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)

我的表格.py:

class CommentForm(forms.ModelForm):

class Meta:
model = Comment
fields = ['text']

html 格式:

    <div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">New Comment</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Publish</button>
</div>
</form>
</div>

最佳答案

您必须为 post 设置值,因为它是一个外键。在 form_valid 中,您应该定义 post = Post.objects.get(id=current_post_id) 并且您可以从 url 获取 current_post_id 或将其接收为一个参数。然后赋值:form.instance.post = post

关于django - "IntegrityError. NOT NULL constraint failed: blog_comment.post_id "代表什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55872523/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com