【问题标题】:How do I resolve IntegrityError: NOT NULL constraint failed?如何解决 IntegrityError: NOT NULL 约束失败?
【发布时间】:2020-05-27 22:30:13
【问题描述】:

我尝试让用户将 cmets 添加到正在制作的博客文章中...... 当我运行 makemigrations 和 migrate 时,一切似乎都很好。表单显示良好,但当我填写表单并单击提交按钮时显示以下错误。 Django.db.utils.IntegrityError: NOT NULL 约束失败:blog_comment.author_id

我是 Django 新手,正在学习教程。除了超级用户,本教程没有其他用户。我了解了用户,所以我让用户注册使用博客。本教程在表单中提供了一个名称字段,以便评论者可以输入他们的姓名。在这里,我想为该字段使用当前用户(请参阅下面的 models.py 以了解我是如何做到的)。 任何解决此问题的帮助将不胜感激。

models.py

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,)
    comment = models.TextField()   
    created = models.DateTimeField(auto_now_add=True)  
    updated = models.DateTimeField(auto_now=True)    
    active = models.BooleanField(default=True)

    class Meta:
        ordering = ('created',)

    def __str__(self):
        return f'Comment by {self.author} on {self.post}'

forms.py

class CommentForm(forms.ModelForm):

    class Meta:
        model = Comment
        fields = ('comment',)

views.py

login_required
def post_detail(request, post, pk):
    post = get_object_or_404(Post, id=pk, slug=post, status='published')
    comments = post.comments.filter(active=True)
    new_comment = None

    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.post = post
            new_comment.save()
    else:
        comment_form = CommentForm()
    return render(request,
        'post_detail.html',
        {'post': post,
        'comments': comments,
        'new_comment': new_comment,
        'comment_form': comment_form})

PS:我看到过类似的问题,并删除了我的迁移文件并重新运行了迁移,但它仍然无法正常工作。

【问题讨论】:

    标签: django django-models django-forms django-views


    【解决方案1】:

    在 if comment.is_valid(): 块中,

    之前;

    new_comment.save()
    

    添加,

    new_comment.author = request.user
    

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2023-03-29
      • 2020-12-19
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 2022-08-10
      • 1970-01-01
      • 2021-08-07
      相关资源
      最近更新 更多