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

时间:2018-10-03 07:53:19

标签: python django postgresql

我正在尝试向事实(帖子)添加评论。当我尝试提交评论时,出现以下错误?我正在使用Postgres FYI

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',)

为什么comment_id为null,我会认为Django会像使用Fact模型那样自动填充它。

对此有所帮助。

谢谢。

1 个答案:

答案 0 :(得分:3)

应该是

.sidebar {
    transition: left 0.3s ease-out;
}

代替

.sidebar.hide {
    left: -295px;
}


因此您的看法将是

comment.comment = fc