IntegrityError at /blog/5 NOT NULL constraint failed: blog_comment.post_id

Я пытаюсь реализовать в своем блоге раздел комментариев, который выглядит следующим образом: enter image description here

У меня нет ввода имени user или post, потому что он должен принимать в качестве входных данных пользователя запроса и ID поста, в котором он делает комментарий.

Моя модель комментариев:

class Comment(models.Model):
post = models.ForeignKey(
    Post, on_delete=models.CASCADE)
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
approved_comment = models.BooleanField(default=False)

class Meta:
    ordering = ['-created_on']

def __str__(self):
    max_len = 75

    if len(self.body) > max_len:
        string = self.body[:max_len] + "..."
    else:
        string = self.body
    return string

Форма комментария:

class CommentForm(forms.ModelForm):

class Meta:
    model = Comment
    fields = ('body',)
    exclude = ['user', 'post', ]

Функция просмотра:

def get_post_details(request, post_id):

unique_post = Post.objects.get(id=post_id)
all_comments = Comment.objects.filter(post=unique_post)

new_comment = None

if request.method == 'POST':
    comment_form = CommentForm(data=request.POST)

    if comment_form.is_valid():
        new_comment = comment_form.save(commit=True)
        new_comment.post = unique_post
        new_comment.user = request.user
        new_comment.save()
        return get_post_details(request, post_id)
else:
    comment_form = CommentForm()

context_dict = {
    'post': unique_post,
    'comments': all_comments,
    'new_comment': new_comment,
    'comment_form': comment_form
}

return render(request, 'blog/post_details.html', context=context_dict)

Я не уверен, чего не хватает, но когда я пытаюсь добавить комментарий, я получаю следующую ошибку:

Я искал по всему stackoverflow и проблема всегда казалась в том, что пользователь забывал добавить секцию comment.post = post в представление, но у меня она определена.

Любая помощь приветствуется!

Причина неудачи заключается в том, что commit=True, который таким образом стремится сохранить элемент.

Но, вероятно, более надежным способом сделать это является внедрение этих данных в экземпляр, обернутый в форму напрямую, так:

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)
Вернуться на верх