Error when using comment form on website: (1048, "Column 'comment_post_id' cannot be null")

I’m trying to implement a comment section below each blog on my site. I’ve got the form rendering but when I try to post a comment I get the following error:

(1048, "Column ‘comment_post_id’ cannot be null")

I cannot see what I’m doing wrong, I’ve also followed a tutorial step by step, although it is 2 years old.

here’s my code: sorry if I missed any, please ask if you require more.

models.py:

class BlogPost(models.Model):
    blog_title = models.CharField(max_length=100, null=False, blank=False, default="")
    blog_article = RichTextUploadingField(null=True, blank=True, default="ici")
    blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png")
    blog_date = models.DateField(auto_now_add=True)
    blog_published = models.BooleanField(default=False)
    blog_featured = models.BooleanField(default=False)
    slug = models.SlugField()
        
    def save(self, *args, **kwargs):
        self.slug = self.slug or slugify(self.blog_title)
        super().save(*args, **kwargs)

    def __str__(self):
        return self.blog_title
    

class blogComment(models.Model, ):
    comment_post = models.ForeignKey(BlogPost, related_name="comments", on_delete=models.CASCADE)
    comment_name = models.CharField(max_length=100)
    comment_text = models.TextField(max_length=1000)
    comment_date = models.DateTimeField(auto_now_add=True)
    comment_status = models.BooleanField(default=True)

    class Meta:
            ordering = ("comment_date",)

    def __str__(self):
        return '%s -- Name: %s'%(self.comment_post.blog_title, self.comment_name)

views.py:

def viewBlog(request, slug):
    
    try:
        blog = BlogPost.objects.get(slug=slug)
    except BlogPost.DoesNotExist:
        print("ViewBlog with this slug does not exist")
        blog = None

    comments = blog.comments.filter(comment_status=True)

    user_comment = None

    if request.method == 'POST':
        comment_form = commentForm(request.POST)
        if comment_form.is_valid():
            user_comment = comment_form.save(commit=False)
            user_comment.blog = blog
            user_comment.save()
            return HttpResponseRedirect('/' + blog.slug)
    else:
        comment_form = commentForm()

    return render(request, 'view-blog.html', {'blog': blog, 'slug': slug, 'comments': user_comment, 'comments': comments, 'comment_form': comment_form})

>Solution :

You’re trying to assign a BlogPost object to the .blog attribute of your user_comment. Try the following, it should work:

if request.method == 'POST':
    comment_form = commentForm(request.POST)
    if comment_form.is_valid():
        user_comment = comment_form.save(commit=False)
        user_comment.comment_post = blog
        user_comment.save()
        return HttpResponseRedirect('/' + blog.slug)
else:
    comment_form = commentForm()

One thing I would do for making your code look better is rename the fields of your blogComment model without the ‘comment_’ prefix. So comment_post -> post. Also use PascalCase for classes, so BlogComment and convert your functions to lower_case_with_underscores. All of this is according to the PEP-8 coding conventions and will make your code read more comfortable for others: https://peps.python.org/pep-0008/

Leave a Reply