NOT NULL 约束失败:blogs_comment.blog_id

NOT NULL constraint failed: blogs_comment.blog_id

我是 django 的初学者,请帮助我已经尝试解决了 2 个小时,非常感谢!

<我在 /blog/431cdef3-d9e7-4abd-bf53-eaa7b188d0fd 处收到此 django 错误 IntegrityError>

python #Views

from django.shortcuts import render
from .models import Blog
from .forms import CommentForm

def home(request):
    template = 'blogs/home.html'
    blogs = Blog.objects.all()
    context = {'blogs':blogs}

    return render(request, template, context)

def blog(request, pk):
    template = 'blogs/blog.html'
    blog = Blog.objects.get(pk=pk)
    context = {'blog':blog}

    if request.method == 'POST':
        form = CommentForm(request.POST)
        form.save()
    else:
        form = CommentForm()
    context['form'] = form
    return render(request, template, context) 

#表格

from django.forms import ModelForm
from .models import Comment
class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ['description']

#型号

from django.db import models
import uuid


class Blog(models.Model):
    header = models.CharField(max_length=200)
    posts = models.TextField(null=True)
    footer = models.TextField(null=True, blank=True)
    id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
    def __str__(self):
        return self.header

class Comment(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='comments')
    description = models.TextField(blank=True, null=True)
    id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
    def __str__(self):
        return self.description `

您没有添加 Foreignkey key 值。试试这个。

def blog(request, pk):
    template = 'blogs/blog.html'
    blog = Blog.objects.get(pk=pk)
    context = {'blog':blog}

    if request.method == 'POST':
        form = CommentForm(request.POST, instance=blog)
        if form.is_valid():
      
            form.save()
    else:
        form = CommentForm(instance=blog)
    context['form'] = form
    return render(request, template, context) 

试试这个:

    def blog(request, pk):
        template = 'blogs/blog.html'
        blog = Blog.objects.get(pk=pk)
        context = {'blog':blog}
    
        if request.method == 'POST':
            form = CommentForm(request.POST)
            if form.is_valid():
                comment = form.save(commit=False) # don't save the comment yet
                comment.blog = blog # assign the blog
                comment.save() # then save
        else:
            form = CommentForm()
        context['form'] = form
        return render(request, template, context) 

在将评论提交到数据库之前,先将博客添加到评论中。