为什么会出现空约束错误?

2024-04-19 14:47:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在事实(帖子)上添加评论。当我试图提交一个评论,我得到以下错误?我在用Postgres供参考

IntegrityError at /fc/2/comment/
null value in column "comment_id" violates not-null constraint
DETAIL:  Failing row contains (8, It has plugins too, 2018-10-03 07:41:25.249524+00, 1, null).

Exception Value:    
null value in column "comment_id" violates not-null constraint
DETAIL:  Failing row contains (8, It has plugins too, 2018-10-03 07:41:25.249524+00, 1, null).

型号:

class Fact(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
        default=timezone.now)
    published_date = models.DateTimeField(
        blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

class Comment(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    comment = models.ForeignKey('fc.Fact', on_delete=models.CASCADE, related_name='comments')
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)

查看:

def add_comment_to_post(request,pk):
fc = get_object_or_404(Fact, pk=pk)
if request.method =="POST":
    form =CommentForm(request.POST)
    if form.is_valid():
        comment = form.save(commit=False)
        comment.fc = fc
        comment.save()
        return redirect('fc_detail',pk=fc.pk)
else:
    form =CommentForm()
return render(request,'add_comment_to_post.html',{'form':form})

窗体视图:

{% extends 'base.html' %}

{% block content %}

    <h1>Check this fact</h1>
    <form method="POST" class="post-form">{% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="save btn btn-default">Save</button>
    </form>

{% endblock %}

形式:

class FcForm(forms.ModelForm):

class Meta:
    model = Fact
    fields = ('title', 'text',)

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('author', 'text',)

为什么注释id为空,我本以为Django会像我的事实模型那样自动填充它。你知道吗

谢谢你的帮助。你知道吗

谢谢你。你知道吗


Tags: textselfformiddatemodelsrequestsave
1条回答
网友
1楼 · 发布于 2024-04-19 14:47:54

应该是的

comment.comment = fc

而不是

comment.fc = fc


因此你的观点将是

def add_comment_to_post(request, pk):
    fc = get_object_or_404(Fact, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.comment = fc # change is here <<<
            comment.save()
            return redirect('fc_detail', pk=fc.pk)
    else:
        form = CommentForm()
    return render(request, 'add_comment_to_post.html', {'form': form})

相关问题 更多 >