NOT NULL constraint failed: blogs_comment.blog_id

Solution for NOT NULL constraint failed: blogs_comment.blog_id
is Given Below:

I’m a beginner at django please help I’ve been trying to solve it for 2 hours, Thank you so much!

<I got this django error IntegrityError at /blog/431cdef3-d9e7-4abd-bf53-eaa7b188d0fd>

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) 

#Forms

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

#Models

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 `

Try with this:

    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) 

Add the blog to the comment first before committing the comment to the database.

You didn’t add with Foreignkey key value. Try this one.

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)