Django comment saving to DB but not to post

Question:

Comments are saving to DB but not linking to Post, unless I manually go to Admin page and link.

MODELS.PY

class Post(models.Model):
    title = models.CharField(max_length=50)
    description = models.CharField(max_length=50)
    info = models.TextField(max_length=2000)
    slug = models.SlugField(null=True, unique=True, max_length=300)
    created = models.DateField(null=True, auto_now_add=True)
    approved = models.BooleanField(default=False, blank=True)
    id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)


class Comment(models.Model):
    post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE, null=True)
    name = models.CharField(max_length=50, verbose_name="Name")
    comment = models.TextField(max_length=500, verbose_name="Comment")
    created = models.DateField(null=True, auto_now_add=True)
    approved = models.BooleanField(default=False, blank=True)
    id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)

FORMS.PY

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['name','comment']

VIEWS.PY

def create_comment(request, slug):
    form = CommentForm()
    post = Post.objects.get(slug=slug)

    if request.method == "POST":
        form = CommentForm(request.POST)
        comment = form.save()
        comment.post = post
        comment.save()

        messages.success(request, 'Your comment was successfully submitted!')
        return render(request, 'post.html', {'post': post, 'form':form})
    return render(request, 'post.html', {'post': post, 'form':form})

From Admin page I can add comment and manually link to post, but from frontend form, comment is created and saved to DB but not linked to any post. Any idea what I’m doing incorrectly?

Asked By: PolarBear

||

Answers:

Where does this review object instance come from, woudn’t it be the comment object?

Also, check if the the form is valid:

def create_comment(request, slug):
    form = CommentForm()
    post = Post.objects.get(slug=slug)

    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save()
            comment.post = post
            comment.save()

            messages.success(request, 'Your comment was successfully submitted!')
            return render(request, 'post.html', {'post': post, 'form':form})
            
    return render(request, 'post.html', {'post': post, 'form':form})
Answered By: Niko