NOT NULL 约束失败:social_media_app_blogcomment.user_id

NOT NULL constraint failed: social_media_app_blogcomment.user_id

我正在为我的博客制作这个评论系统。我已经制作了模型、ModelForm 和视图来显示评论和博客。我真的很困惑如何保存与特定博客相关的评论。我试图用视图保存评论,但遇到 IntegrityError。如果能提供一点帮助,我们将不胜感激。

这是我的 views.py:

@login_required #View to show the blogs and comments related to it
def readblog(request, blog_pk):
    Blog = get_object_or_404(blog, pk=blog_pk)
    return render(request, 'social_media/readblog.html', {'Blog':Blog,'Form':CommentForm()})

@login_required #view to save the comments
def commentblog(request,blog_pk):
    Blog = get_object_or_404(blog,pk=blog_pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            Form = form.save(commit=False)
            Form.Blog = Blog
            Form.save()
    return redirect('usersfeed')

Urls.py:

path('commentblog/<int:blog_pk>', views.commentblog, name='commentblog'),
path('readblog/<int:blog_pk>', views.readblog, name='readblog'),

HTML 用于撰写和保存评论的页面(连同博客):

{{ Blog.title }}
<br>
{{ Blog.text }}    
<br>
{% if Blog.image %}
    <img src="{{ Blog.image.url }}" alt="">
{% endif %}
<br>
<form action="{% url 'commentblog' Blog.id %}" method="post">
    {% csrf_token %}
    {{ Form.as_p }}
    <button type="submit">Comment!</button>
</form>
{% for i in Blog.BlogComment.all %}
    {{ i.comment }}
    <b>user:{{ i.user }}</b>
    <br>
{% endfor %}

评论的型号:

class BlogComment(models.Model): # --run-syncdb  <- (Research about this!)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    comment = models.CharField(max_length=250, null=True)
    blog = models.ForeignKey(blog, related_name='BlogComment', on_delete=models.CASCADE, blank=True, null=True)

    def __str__(self):
        return self.comment

Forms.py:

class CommentForm(forms.ModelForm):
    class Meta:
        model = BlogComment
        fields = ['comment']

您需要添加用户,因为它在您的模型中不是空字段:

def commentblog(request,blog_pk):
    blog_obj = get_object_or_404(blog,pk=blog_pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            form_obj = form.save(commit=False)
            form_obj.blog = blog_obj

            # add user instance
            form_obj.user = request.user

            form_obj.save()
    return redirect('usersfeed')