[Answered ]-IntegrityError at /blog/5 NOT NULL constraint failed: blog_comment.post_id

1👍

The reason this fails is because the commit=True, which thus aims to save the item.

But likely a more robust way to do this, is to inject that data in the instance wrapped in the form directly, so:

from django.shortcuts import get_object_or_404, redirect

def get_post_details(request, post_id):
    unique_post = get_object_or_404(Post, pk=post_id)
    all_comments = Comment.objects.filter(post=unique_post)
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST, request.FILES)
        if comment_form.is_valid():
            comment_form.instance.post = unique_post
            comment_form.instance.user = request.user
            comment_form.save()
            return redirect(get_post_details, post_id)
    else:
        comment_form = CommentForm()
    
    context = {
        'post': unique_post,
        'comments': all_comments,
        'comment_form': comment_form
    }
    return render(request, 'blog/post_details.html', context)

Leave a comment